entc/integration/json: add example for using interfaces in JSON fields (#2497)

This commit is contained in:
Ariel Mashraki
2022-04-25 13:34:05 +03:00
committed by GitHub
parent 04e0dc936b
commit 879bb8a905
11 changed files with 266 additions and 6 deletions

View File

@@ -71,15 +71,19 @@ func Time(name string) *timeBuilder {
// Optional()
//
func JSON(name string, typ interface{}) *jsonBuilder {
t := reflect.TypeOf(typ)
b := &jsonBuilder{&Descriptor{
Name: name,
Info: &TypeInfo{
Type: TypeJSON,
Ident: t.String(),
PkgPath: t.PkgPath(),
Type: TypeJSON,
},
}}
t := reflect.TypeOf(typ)
if t == nil {
b.desc.Err = errors.New("expect a Go value as JSON type, but got nil")
return b
}
b.desc.Info.Ident = t.String()
b.desc.Info.PkgPath = t.PkgPath()
b.desc.goType(typ, t)
switch t.Kind() {
case reflect.Slice, reflect.Array, reflect.Ptr, reflect.Map:

View File

@@ -508,6 +508,8 @@ func TestJSON(t *testing.T) {
assert.Equal(t, "net/url", fd.Info.PkgPath)
fd = field.JSON("values", map[string]*url.Values{}).Descriptor()
assert.Equal(t, "net/url", fd.Info.PkgPath)
fd = field.JSON("addr", net.Addr(nil)).Descriptor()
assert.EqualError(t, fd.Err, "expect a Go value as JSON type, but got nil")
}
func TestField_Tag(t *testing.T) {