Skip to content

Commit

Permalink
fix #1876: Optional Any type should allow nil values (#2231)
Browse files Browse the repository at this point in the history
* Anonymous func that checks value of arg type interface for nil

* Added unit test for `CallArgs()`

* Fixed type of argument in unit test
  • Loading branch information
vediatoni committed Jun 8, 2022
1 parent 65e6810 commit c355df9
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
15 changes: 14 additions & 1 deletion codegen/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,20 @@ func (f *Field) CallArgs() string {
}

for _, arg := range f.Args {
args = append(args, "fc.Args["+strconv.Quote(arg.Name)+"].("+templates.CurrentImports.LookupType(arg.TypeReference.GO)+")")
tmp := "fc.Args[" + strconv.Quote(arg.Name) + "].(" + templates.CurrentImports.LookupType(arg.TypeReference.GO) + ")"

if types.IsInterface(arg.TypeReference.GO) {
tmp = fmt.Sprintf(`
func () interface{} {
if fc.Args["%s"] == nil {
return nil
}
return fc.Args["%s"].(interface{})
}()`, arg.Name, arg.Name,
)
}

args = append(args, tmp)
}

return strings.Join(args, ", ")
Expand Down
67 changes: 67 additions & 0 deletions codegen/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/99designs/gqlgen/codegen/config"
"github.com/stretchr/testify/require"
ast2 "github.com/vektah/gqlparser/v2/ast"
)

func TestFindField(t *testing.T) {
Expand Down Expand Up @@ -114,3 +115,69 @@ func TestEqualFieldName(t *testing.T) {
})
}
}

func TestField_CallArgs(t *testing.T) {
tt := []struct {
Name string
Field
Expected string
}{
{
Name: "Field with method that has context, and two args (string, interface)",
Field: Field{
MethodHasContext: true,
Args: []*FieldArgument{
{
ArgumentDefinition: &ast2.ArgumentDefinition{
Name: "test",
},
TypeReference: &config.TypeReference{
GO: &types.Interface{},
},
},
{
ArgumentDefinition: &ast2.ArgumentDefinition{
Name: "test2",
},
TypeReference: &config.TypeReference{
GO: types.Typ[types.String],
},
},
},
},
Expected: `ctx, ` + `
func () interface{} {
if fc.Args["test"] == nil {
return nil
}
return fc.Args["test"].(interface{})
}(), fc.Args["test2"].(string)`,
},
{
Name: "Resolver field that isn't root object with single int argument",
Field: Field{
Object: &Object{
Root: false,
},
IsResolver: true,
Args: []*FieldArgument{
{
ArgumentDefinition: &ast2.ArgumentDefinition{
Name: "test",
},
TypeReference: &config.TypeReference{
GO: types.Typ[types.Int],
},
},
},
},
Expected: `rctx, obj, fc.Args["test"].(int)`,
},
}

for _, tc := range tt {
t.Run(tc.Name, func(t *testing.T) {
require.Equal(t, tc.CallArgs(), tc.Expected)
})
}
}

0 comments on commit c355df9

Please sign in to comment.