Skip to content

Commit

Permalink
entc/integration/json: add example for using interfaces in JSON fields (
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m committed Apr 25, 2022
1 parent 04e0dc9 commit 879bb8a
Show file tree
Hide file tree
Showing 11 changed files with 266 additions and 6 deletions.
1 change: 1 addition & 0 deletions entc/integration/json/ent/migrate/schema.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

75 changes: 74 additions & 1 deletion entc/integration/json/ent/mutation.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 49 additions & 0 deletions entc/integration/json/ent/schema/user.go
Expand Up @@ -6,6 +6,9 @@ package schema

import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"

Expand Down Expand Up @@ -38,6 +41,8 @@ func (User) Fields() []ent.Field {
Optional(),
field.Strings("strings").
Optional(),
field.JSON("addr", Addr{}).
Optional(),
}
}

Expand All @@ -50,3 +55,47 @@ type T struct {
Li []int `json:"li,omitempty"`
Ls []string `json:"ls,omitempty"`
}

type Addr struct{ net.Addr }

func (a *Addr) UnmarshalJSON(data []byte) error {
var types struct {
TCP *net.TCPAddr `json:"tcp,omitempty"`
UDP *net.UDPAddr `json:"udp,omitempty"`
}
if err := json.Unmarshal(data, &types); err != nil {
return err
}
switch {
case types.TCP != nil && types.UDP != nil:
return errors.New("TCP and UDP addresses are mutually exclusive")
case types.TCP != nil:
a.Addr = types.TCP
case types.UDP != nil:
a.Addr = types.UDP
}
return nil
}

func (a Addr) MarshalJSON() ([]byte, error) {
var types struct {
TCP *net.TCPAddr `json:"tcp,omitempty"`
UDP *net.UDPAddr `json:"udp,omitempty"`
}
switch a := a.Addr.(type) {
case *net.TCPAddr:
types.TCP = a
case *net.UDPAddr:
types.UDP = a
default:
return nil, fmt.Errorf("unsupported address type: %T", a)
}
return json.Marshal(types)
}

func (a Addr) String() string {
if a.Addr == nil {
return ""
}
return a.Addr.String()
}
14 changes: 13 additions & 1 deletion entc/integration/json/ent/user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions entc/integration/json/ent/user/user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions entc/integration/json/ent/user/where.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions entc/integration/json/ent/user_create.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 879bb8a

Please sign in to comment.