directive_build.go

 1package codegen
 2
 3import (
 4	"sort"
 5
 6	"github.com/pkg/errors"
 7)
 8
 9func (cfg *Config) buildDirectives(types NamedTypes) ([]*Directive, error) {
10	var directives []*Directive
11
12	for name, dir := range cfg.schema.Directives {
13		if name == "skip" || name == "include" || name == "deprecated" {
14			continue
15		}
16
17		var args []FieldArgument
18		for _, arg := range dir.Arguments {
19			newArg := FieldArgument{
20				GQLName:   arg.Name,
21				Type:      types.getType(arg.Type),
22				GoVarName: sanitizeArgName(arg.Name),
23			}
24
25			if !newArg.Type.IsInput && !newArg.Type.IsScalar {
26				return nil, errors.Errorf("%s cannot be used as argument of directive %s(%s) only input and scalar types are allowed", arg.Type, dir.Name, arg.Name)
27			}
28
29			if arg.DefaultValue != nil {
30				var err error
31				newArg.Default, err = arg.DefaultValue.Value(nil)
32				if err != nil {
33					return nil, errors.Errorf("default value for directive argument %s(%s) is not valid: %s", dir.Name, arg.Name, err.Error())
34				}
35			}
36			args = append(args, newArg)
37		}
38
39		directives = append(directives, &Directive{
40			Name: name,
41			Args: args,
42		})
43	}
44
45	sort.Slice(directives, func(i, j int) bool { return directives[i].Name < directives[j].Name })
46
47	return directives, nil
48}