-
Notifications
You must be signed in to change notification settings - Fork 0
/
filtergen.go
269 lines (222 loc) · 5.77 KB
/
filtergen.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package gqlfiltergen
import (
"bytes"
_ "embed"
"fmt"
"path"
"sort"
"strings"
"github.com/99designs/gqlgen/codegen"
"github.com/99designs/gqlgen/codegen/config"
"github.com/99designs/gqlgen/codegen/templates"
"github.com/99designs/gqlgen/plugin"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/formatter"
"github.com/vektah/gqlparser/v2/parser"
)
const (
filterableDirectiveName = "filterable"
extrasArgumentName = "extras"
extraMinmaxName = "MINMAX"
)
//go:embed filter.functions.go.tpl
var functionsTpl string
var _ plugin.EarlySourceInjector = &Plugin{}
var _ plugin.LateSourceInjector = &Plugin{}
var _ plugin.CodeGenerator = &Plugin{}
var _ plugin.ConfigMutator = &Plugin{}
type Plugin struct {
templateData *TemplateData
opts *Options
}
type Options struct {
InjectCodeAfter string
}
func NewPlugin(opts *Options) *Plugin {
return &Plugin{
opts: opts,
}
}
func (f *Plugin) Name() string {
return "filtergen"
}
func (f *Plugin) InjectSourceEarly() *ast.Source {
return &ast.Source{
Name: "filtergen.directives.graphql",
Input: `
enum FilterableExtra {
"""
Get minimum and maximum value used on all the filters for this field.
Useful when you need to do a range query for performance reasons.
"""
MINMAX
}
directive @filterable(
"""
Add extra functionality to this field apart from the filtering capabilities.
"""
extras: [FilterableExtra!]
) on FIELD_DEFINITION
`,
}
}
func (f *Plugin) InjectSourceLate(schema *ast.Schema) *ast.Source {
processingTypes := make(map[string]*ProcessingObject)
for n, t := range schema.Types {
if _, ok := processingTypes[n]; ok {
continue
}
if t.Kind == ast.Union {
// add unions just in case they have types with filters
processingTypes[n] = &ProcessingObject{
Definition: t,
}
continue
}
for _, f := range t.Fields {
filterable, minmaxeable := getDirectives(f.Directives)
if !filterable {
continue
}
fl := processingTypes[n]
if fl == nil {
fl = &ProcessingObject{}
}
fl.Fields = append(fl.Fields, &ProcessingField{
Field: f,
IsMinmaxeable: minmaxeable,
})
fl.Definition = t
processingTypes[n] = fl
}
}
initTypes := map[string]*ast.Definition{
filterStringName: filterString(filterStringName),
filterIntName: filterNumber(filterIntName),
filterTimeName: filterTime(filterTimeName),
filterBooleanName: filterBoolean(filterBooleanName),
}
outSchema := &ast.Schema{
Types: initTypes,
}
defMap := generateMainFilterDefinition(processingTypes)
td := &TemplateData{}
for k, v := range defMap {
outSchema.Types[k] = v.Ast
td.TypeDatas = append(td.TypeDatas, v.TypeData)
}
f.templateData = td
var buf bytes.Buffer
formatter := formatter.NewFormatter(&buf, formatter.WithComments())
formatter.FormatSchema(outSchema)
return &ast.Source{
Name: "filtergen.graphql",
Input: buf.String(),
BuiltIn: false,
}
}
func getDirectives(cd ast.DirectiveList) (filterable bool, minmaxeable bool) {
if cd == nil {
return
}
for _, d := range cd {
if d.Name == filterableDirectiveName {
filterable = true
}
if a := d.Arguments.ForName(extrasArgumentName); a != nil {
if a.Value.Kind != ast.ListValue {
continue
}
if ch := a.Value.Children; len(ch) != 0 {
if vals := ch.ForName(""); vals != nil {
if strings.Contains(vals.Raw, extraMinmaxName) {
minmaxeable = true
}
}
}
}
}
return
}
func (f *Plugin) MutateConfig(cfg *config.Config) error {
if err := f.injectUserQueries(cfg); err != nil {
return err
}
return cfg.LoadSchema()
}
func (f *Plugin) GenerateCode(data *codegen.Data) error {
// rebuild template data with Go field names
for _, t := range f.templateData.TypeDatas {
dataObj := data.Objects.ByName(t.TypeName)
if dataObj == nil {
continue
}
for _, f := range t.Fields {
for _, of := range dataObj.Fields {
if f.Field == of.FieldDefinition.Name {
f.FilterField = of.GoFieldName
f.IsMethod = of.IsMethod()
}
}
}
sort.Slice(t.Fields, func(i, j int) bool {
return t.Fields[i].FilterField > t.Fields[j].FilterField
})
}
sort.Slice(f.templateData.TypeDatas, func(i, j int) bool {
return f.templateData.TypeDatas[i].FilterName > f.templateData.TypeDatas[j].FilterName
})
filename := path.Join(path.Dir(data.Config.Model.Filename), "filter_methods_gen.go")
return templates.Render(templates.Options{
PackageName: data.Config.Model.Package,
Filename: filename,
Data: f.templateData,
GeneratedHeader: true,
Packages: data.Config.Packages,
Template: functionsTpl,
})
}
const (
queryName = "Query"
subscriptionName = "Subscription"
)
func (f *Plugin) injectUserQueries(cfg *config.Config) error {
orig := cfg.Schema
source := &ast.Source{
Input: f.opts.InjectCodeAfter,
}
schema, err := parser.ParseSchema(source)
if err != nil {
return fmt.Errorf("error injecting user-defined queries: %w", err)
}
if qt := schema.Definitions.ForName(queryName); qt != nil {
if oqt, ok := orig.Types[queryName]; ok {
for _, f := range qt.Fields {
oqt.Fields = append(oqt.Fields, f)
}
} else {
orig.Types[queryName] = qt
}
}
if st := schema.Definitions.ForName(subscriptionName); st != nil {
if ost, ok := orig.Types[subscriptionName]; ok {
for _, f := range st.Fields {
ost.Fields = append(ost.Fields, f)
}
} else {
orig.Types[subscriptionName] = st
}
}
var buf bytes.Buffer
form := formatter.NewFormatter(&buf, formatter.WithComments())
form.FormatSchema(orig)
// TODO: might be a better way to do it
// we need to overwrite sources to correctly generate resolvers for the queries and subscriptions that we injected
cfg.Sources = []*ast.Source{
{
Name: "all",
Input: buf.String(),
},
}
return nil
}