-
Notifications
You must be signed in to change notification settings - Fork 0
/
constraintdirective.go
76 lines (70 loc) · 1.98 KB
/
constraintdirective.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package constraintdirective
import (
"github.com/gqlgo/gqlanalysis"
"github.com/vektah/gqlparser/v2/ast"
"slices"
)
func Analyzer(types, excludeFieldNames []string) *gqlanalysis.Analyzer {
return &gqlanalysis.Analyzer{
Name: "constraintdirective",
Doc: "constraintdirective finds field and argument without @constraint directive",
Run: run(types, excludeFieldNames),
}
}
func isTargetType(types []string, t *ast.Type) bool {
if t == nil {
return false
}
if slices.Contains(types, t.NamedType) {
return true
}
return isTargetType(types, t.Elem)
}
func isExcludeFieldName(ignoreFieldNames []string, fieldName string) bool {
return slices.Contains(ignoreFieldNames, fieldName)
}
func run(types, excludeFieldNames []string) func(pass *gqlanalysis.Pass) (interface{}, error) {
return func(pass *gqlanalysis.Pass) (interface{}, error) {
for _, t := range pass.Schema.Types {
if t.BuiltIn {
continue
}
switch t.Kind {
case ast.InputObject:
for _, field := range t.Fields {
if field == nil || field.Type == nil {
continue
}
if !isTargetType(types, field.Type) || isExcludeFieldName(excludeFieldNames, field.Name) {
continue
}
if field.Directives == nil || field.Directives.ForName("constraint") == nil {
if field.Position != nil {
pass.Reportf(field.Position, "%s has no constraint directive", field.Name)
}
}
}
case ast.Object:
for _, field := range t.Fields {
if field == nil {
continue
}
for _, arg := range field.Arguments {
if arg == nil || arg.Type == nil {
continue
}
if !isTargetType(types, arg.Type) || isExcludeFieldName(excludeFieldNames, arg.Name) {
continue
}
if arg.Directives == nil || arg.Directives.ForName("constraint") == nil {
if field.Position != nil {
pass.Reportf(field.Position, "argument %s of %s has no constraint directive", arg.Name, field.Name)
}
}
}
}
}
}
return nil, nil
}
}