-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrelaycompmul.go
106 lines (94 loc) · 2.52 KB
/
relaycompmul.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package relaycompmul
import (
"fmt"
"strings"
"github.com/gqlgo/gqlanalysis"
"github.com/vektah/gqlparser/v2/ast"
)
var Analyzer = &gqlanalysis.Analyzer{
Name: "relaycompmul",
Doc: "relaycompmul finds a relay cursor connection fields which not have @complexity directive or its mul argument.",
Run: run,
}
func isRelayCursorConnection(field *ast.FieldDefinition) bool {
if !strings.HasSuffix(field.Type.Name(), "Connection") {
return false
}
for _, argn := range []string{"after", "before"} {
if field.Arguments.ForName(argn) == nil {
return false
}
}
for _, argn := range []string{"first", "last"} {
arg := field.Arguments.ForName(argn)
if arg == nil {
return false
}
if arg.Type.Name() != "Int" {
return false
}
}
return true
}
func hasComplexity(field *ast.FieldDefinition) bool {
return field.Directives.ForName("complexity") != nil
}
func hasMul(fn string, field *ast.FieldDefinition) bool {
directive := field.Directives.ForName("complexity")
if directive == nil {
return false
}
mul := directive.Arguments.ForName("mul")
if mul == nil {
return false
}
set := make(map[string]struct{}, 10)
for _, child := range mul.Value.Children {
name := child.Value.Raw
set[name] = struct{}{}
}
_, ok := set[fn]
return ok
}
func run(pass *gqlanalysis.Pass) (interface{}, error) {
if pass == nil || pass.Schema == nil || pass.Schema.Query == nil {
return nil, nil
}
for _, typ := range pass.Schema.Types {
for _, field := range typ.Fields {
if !isRelayCursorConnection(field) {
continue
}
if !hasComplexity(field) {
pass.Report(&gqlanalysis.Diagnostic{
Pos: field.Type.Position,
Message: fmt.Sprintf("field [%s] is Relay Cursor Connections field, but @complexity directive is not found", field.Name),
})
continue
}
first := hasMul("first", field)
last := hasMul("last", field)
const message = "field [%s] is Relay Cursor Connections field, but [%s] argument is not included in [mul] of @complexity"
switch {
case !first && !last:
pass.Report(&gqlanalysis.Diagnostic{
Pos: field.Type.Position,
Message: fmt.Sprintf(message, field.Name, "first, last"),
})
case !first:
pass.Report(&gqlanalysis.Diagnostic{
Pos: field.Type.Position,
Message: fmt.Sprintf(message, field.Name, "first"),
})
case !last:
pass.Report(&gqlanalysis.Diagnostic{
Pos: field.Type.Position,
Message: fmt.Sprintf(message, field.Name, "last"),
})
default:
// no diagnostic
}
}
}
return nil, nil
}