github.com/shish-dev/gqlgen@v0.99.0/codegen/args.go (about) 1 package codegen 2 3 import ( 4 "fmt" 5 "go/types" 6 "strings" 7 8 "github.com/shish-dev/gqlgen/codegen/config" 9 "github.com/shish-dev/gqlgen/codegen/templates" 10 "github.com/vektah/gqlparser/v2/ast" 11 ) 12 13 type ArgSet struct { 14 Args []*FieldArgument 15 FuncDecl string 16 } 17 18 type FieldArgument struct { 19 *ast.ArgumentDefinition 20 TypeReference *config.TypeReference 21 VarName string // The name of the var in go 22 Object *Object // A link back to the parent object 23 Default interface{} // The default value 24 Directives []*Directive 25 Value interface{} // value set in Data 26 } 27 28 // ImplDirectives get not Builtin and location ARGUMENT_DEFINITION directive 29 func (f *FieldArgument) ImplDirectives() []*Directive { 30 d := make([]*Directive, 0) 31 for i := range f.Directives { 32 if !f.Directives[i].Builtin && f.Directives[i].IsLocation(ast.LocationArgumentDefinition) { 33 d = append(d, f.Directives[i]) 34 } 35 } 36 37 return d 38 } 39 40 func (f *FieldArgument) DirectiveObjName() string { 41 return "rawArgs" 42 } 43 44 func (f *FieldArgument) Stream() bool { 45 return f.Object != nil && f.Object.Stream 46 } 47 48 func (b *builder) buildArg(obj *Object, arg *ast.ArgumentDefinition) (*FieldArgument, error) { 49 tr, err := b.Binder.TypeReference(arg.Type, nil) 50 if err != nil { 51 return nil, err 52 } 53 54 argDirs, err := b.getDirectives(arg.Directives) 55 if err != nil { 56 return nil, err 57 } 58 newArg := FieldArgument{ 59 ArgumentDefinition: arg, 60 TypeReference: tr, 61 Object: obj, 62 VarName: templates.ToGoPrivate(arg.Name), 63 Directives: argDirs, 64 } 65 66 if arg.DefaultValue != nil { 67 newArg.Default, err = arg.DefaultValue.Value(nil) 68 if err != nil { 69 return nil, fmt.Errorf("default value is not valid: %w", err) 70 } 71 } 72 73 return &newArg, nil 74 } 75 76 func (b *builder) bindArgs(field *Field, params *types.Tuple) ([]*FieldArgument, error) { 77 var newArgs []*FieldArgument 78 79 nextArg: 80 for j := 0; j < params.Len(); j++ { 81 param := params.At(j) 82 for _, oldArg := range field.Args { 83 if strings.EqualFold(oldArg.Name, param.Name()) { 84 tr, err := b.Binder.TypeReference(oldArg.Type, param.Type()) 85 if err != nil { 86 return nil, err 87 } 88 oldArg.TypeReference = tr 89 90 newArgs = append(newArgs, oldArg) 91 continue nextArg 92 } 93 } 94 95 // no matching arg found, abort 96 return nil, fmt.Errorf("arg %s not in schema", param.Name()) 97 } 98 99 return newArgs, nil 100 } 101 102 func (a *Data) Args() map[string][]*FieldArgument { 103 ret := map[string][]*FieldArgument{} 104 for _, o := range a.Objects { 105 for _, f := range o.Fields { 106 if len(f.Args) > 0 { 107 ret[f.ArgsFunc()] = f.Args 108 } 109 } 110 } 111 112 for _, d := range a.Directives() { 113 if len(d.Args) > 0 { 114 ret[d.ArgsFunc()] = d.Args 115 } 116 } 117 return ret 118 }