forked from wundergraph/graphql-go-tools
/
variable.go
640 lines (571 loc) · 17.8 KB
/
variable.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
package resolve
import (
"context"
"encoding/json"
"fmt"
"io"
"strconv"
"github.com/buger/jsonparser"
"github.com/dchukmasov/graphql-go-tools/pkg/ast"
"github.com/dchukmasov/graphql-go-tools/pkg/graphqljsonschema"
"github.com/dchukmasov/graphql-go-tools/pkg/lexer/literal"
)
type VariableKind int
const (
ContextVariableKind VariableKind = iota + 1
ObjectVariableKind
HeaderVariableKind
)
const (
VariableRendererKindPlain = "plain"
VariableRendererKindPlanWithValidation = "plainWithValidation"
VariableRendererKindJson = "json"
VariableRendererKindJsonWithValidation = "jsonWithValidation"
VariableRendererKindGraphqlWithValidation = "graphqlWithValidation"
VariableRendererKindCsv = "csv"
)
// VariableRenderer is the interface to allow custom implementations of rendering Variables
// Depending on where a Variable is being used, a different method for rendering is required
// E.g. a Variable needs to be rendered conforming to the GraphQL specification, when used within a GraphQL Query
// If a Variable is used within a JSON Object, the contents need to be rendered as a JSON Object
type VariableRenderer interface {
GetKind() string
RenderVariable(ctx context.Context, data []byte, out io.Writer) error
}
// JSONVariableRenderer is an implementation of VariableRenderer
// It renders the provided data as JSON
// If configured, it also does a JSON Validation Check before rendering
type JSONVariableRenderer struct {
JSONSchema string
Kind string
validator *graphqljsonschema.Validator
rootValueType JsonRootType
}
func (r *JSONVariableRenderer) GetKind() string {
return r.Kind
}
func (r *JSONVariableRenderer) RenderVariable(ctx context.Context, data []byte, out io.Writer) error {
if r.validator != nil {
err := r.validator.Validate(ctx, data)
if err != nil {
return fmt.Errorf("could not render JSON variable, %w", err)
}
}
_, err := out.Write(data)
return err
}
func NewJSONVariableRenderer() *JSONVariableRenderer {
return &JSONVariableRenderer{
Kind: VariableRendererKindJson,
}
}
func NewJSONVariableRendererWithValidation(jsonSchema string) *JSONVariableRenderer {
validator := graphqljsonschema.MustNewValidatorFromString(jsonSchema)
return &JSONVariableRenderer{
Kind: VariableRendererKindJsonWithValidation,
JSONSchema: jsonSchema,
validator: validator,
}
}
// NewJSONVariableRendererWithValidationFromTypeRef creates a new JSONVariableRenderer
// The argument typeRef must exist on the operation ast.Document, otherwise it will panic!
func NewJSONVariableRendererWithValidationFromTypeRef(operation, definition *ast.Document, variableTypeRef int) (*JSONVariableRenderer, error) {
jsonSchema := graphqljsonschema.FromTypeRef(operation, definition, variableTypeRef)
validator, err := graphqljsonschema.NewValidatorFromSchema(jsonSchema)
if err != nil {
return nil, err
}
schemaBytes, err := json.Marshal(jsonSchema)
if err != nil {
return nil, err
}
return &JSONVariableRenderer{
Kind: VariableRendererKindJsonWithValidation,
JSONSchema: string(schemaBytes),
validator: validator,
rootValueType: getJSONRootType(operation, definition, variableTypeRef),
}, nil
}
func NewPlainVariableRenderer() *PlainVariableRenderer {
return &PlainVariableRenderer{
Kind: VariableRendererKindPlain,
}
}
func NewPlainVariableRendererWithValidation(jsonSchema string) *PlainVariableRenderer {
validator := graphqljsonschema.MustNewValidatorFromString(jsonSchema)
return &PlainVariableRenderer{
Kind: VariableRendererKindPlanWithValidation,
JSONSchema: jsonSchema,
validator: validator,
}
}
// NewPlainVariableRendererWithValidationFromTypeRef creates a new PlainVariableRenderer
// The argument typeRef must exist on the operation ast.Document, otherwise it will panic!
func NewPlainVariableRendererWithValidationFromTypeRef(operation, definition *ast.Document, variableTypeRef int, variablePath ...string) (*PlainVariableRenderer, error) {
var jsonSchema graphqljsonschema.JsonSchema
if len(variablePath) > 1 {
jsonSchema = graphqljsonschema.FromTypeRef(operation, definition, variableTypeRef, graphqljsonschema.WithPath(variablePath[1:]))
} else {
jsonSchema = graphqljsonschema.FromTypeRef(operation, definition, variableTypeRef)
}
validator, err := graphqljsonschema.NewValidatorFromSchema(jsonSchema)
if err != nil {
return nil, err
}
schemaBytes, err := json.Marshal(jsonSchema)
if err != nil {
return nil, err
}
rootValueType := getJSONRootType(operation, definition, variableTypeRef)
return &PlainVariableRenderer{
Kind: VariableRendererKindPlanWithValidation,
JSONSchema: string(schemaBytes),
validator: validator,
rootValueType: rootValueType,
}, nil
}
// PlainVariableRenderer is an implementation of VariableRenderer
// It renders the provided data as plain text
// E.g. a provided JSON string of "foo" will be rendered as foo, without quotes.
// If a nested JSON Object is provided, it will be rendered as is.
// This renderer can be used e.g. to render the provided scalar into a URL.
type PlainVariableRenderer struct {
JSONSchema string
Kind string
validator *graphqljsonschema.Validator
rootValueType JsonRootType
}
func (p *PlainVariableRenderer) GetKind() string {
return p.Kind
}
func (p *PlainVariableRenderer) RenderVariable(ctx context.Context, data []byte, out io.Writer) error {
if p.validator != nil {
err := p.validator.Validate(ctx, data)
if err != nil {
return fmt.Errorf("could not render plain text variable, %w", err)
}
}
data, _ = extractStringWithQuotes(p.rootValueType, data)
_, err := out.Write(data)
return err
}
// NewGraphQLVariableRendererFromTypeRef creates a new GraphQLVariableRenderer
// The argument typeRef must exist on the operation ast.Document, otherwise it will panic!
func NewGraphQLVariableRendererFromTypeRef(operation, definition *ast.Document, variableTypeRef int) (*GraphQLVariableRenderer, error) {
jsonSchema := graphqljsonschema.FromTypeRef(operation, definition, variableTypeRef)
validator, err := graphqljsonschema.NewValidatorFromSchema(jsonSchema)
if err != nil {
return nil, err
}
schemaBytes, err := json.Marshal(jsonSchema)
if err != nil {
return nil, err
}
return &GraphQLVariableRenderer{
Kind: VariableRendererKindGraphqlWithValidation,
JSONSchema: string(schemaBytes),
validator: validator,
rootValueType: getJSONRootType(operation, definition, variableTypeRef),
}, nil
}
func NewGraphQLVariableRendererFromTypeRefWithOverrides(operation, definition *ast.Document, variableTypeRef int, overrides map[string]graphqljsonschema.JsonSchema) (*GraphQLVariableRenderer, error) {
jsonSchema := graphqljsonschema.FromTypeRef(operation, definition, variableTypeRef, graphqljsonschema.WithOverrides(overrides))
validator, err := graphqljsonschema.NewValidatorFromSchema(jsonSchema)
if err != nil {
return nil, err
}
schemaBytes, err := json.Marshal(jsonSchema)
if err != nil {
return nil, err
}
return &GraphQLVariableRenderer{
Kind: VariableRendererKindGraphqlWithValidation,
JSONSchema: string(schemaBytes),
validator: validator,
rootValueType: getJSONRootType(operation, definition, variableTypeRef),
}, nil
}
func NewGraphQLVariableRendererFromTypeRefWithoutValidation(operation, definition *ast.Document, variableTypeRef int) (*GraphQLVariableRenderer, error) {
return &GraphQLVariableRenderer{
Kind: VariableRendererKindGraphqlWithValidation,
rootValueType: getJSONRootType(operation, definition, variableTypeRef),
}, nil
}
// NewGraphQLVariableRendererFromJSONRootTypeWithoutValidation - to be used in tests only
func NewGraphQLVariableRendererFromJSONRootTypeWithoutValidation(rootType JsonRootType) (*GraphQLVariableRenderer, error) {
return &GraphQLVariableRenderer{
Kind: VariableRendererKindGraphqlWithValidation,
rootValueType: rootType,
}, nil
}
// NewGraphQLVariableRenderer - to be used in tests only
func NewGraphQLVariableRenderer(jsonSchema string) *GraphQLVariableRenderer {
validator := graphqljsonschema.MustNewValidatorFromString(jsonSchema)
rootValueType, err := graphqljsonschema.TopLevelType(jsonSchema)
if err != nil {
panic(err)
}
return &GraphQLVariableRenderer{
Kind: VariableRendererKindGraphqlWithValidation,
JSONSchema: jsonSchema,
validator: validator,
rootValueType: JsonRootType{
Value: rootValueType,
Kind: JsonRootTypeKindSingle,
},
}
}
type JsonRootTypeKind int
const (
JsonRootTypeKindSingle JsonRootTypeKind = iota
JsonRootTypeKindMultiple
)
type JsonRootType struct {
Value jsonparser.ValueType
Values []jsonparser.ValueType
Kind JsonRootTypeKind
}
func (t JsonRootType) Satisfies(dataType jsonparser.ValueType) bool {
switch t.Kind {
case JsonRootTypeKindSingle:
return dataType == t.Value
case JsonRootTypeKindMultiple:
for _, valueType := range t.Values {
if dataType == valueType {
return true
}
}
}
return false
}
func getJSONRootType(operation, definition *ast.Document, variableTypeRef int) JsonRootType {
variableTypeRef = operation.ResolveListOrNameType(variableTypeRef)
if operation.TypeIsList(variableTypeRef) {
return JsonRootType{
Value: jsonparser.Array,
Kind: JsonRootTypeKindSingle,
}
}
name := operation.TypeNameString(variableTypeRef)
node, exists := definition.Index.FirstNodeByNameStr(name)
if !exists {
return JsonRootType{
Value: jsonparser.Unknown,
Kind: JsonRootTypeKindSingle,
}
}
defTypeRef := node.Ref
if node.Kind == ast.NodeKindEnumTypeDefinition {
return JsonRootType{
Value: jsonparser.String,
Kind: JsonRootTypeKindSingle,
}
}
if node.Kind == ast.NodeKindScalarTypeDefinition {
typeName := definition.ScalarTypeDefinitionNameString(defTypeRef)
switch typeName {
case "Boolean":
return JsonRootType{
Value: jsonparser.Boolean,
Kind: JsonRootTypeKindSingle,
}
case "Int", "Float":
return JsonRootType{
Value: jsonparser.Number,
Kind: JsonRootTypeKindSingle,
}
case "ID":
return JsonRootType{
Values: []jsonparser.ValueType{jsonparser.String, jsonparser.Number},
Kind: JsonRootTypeKindMultiple,
}
case "String", "Date":
return JsonRootType{
Value: jsonparser.String,
Kind: JsonRootTypeKindSingle,
}
case "_Any":
return JsonRootType{
Value: jsonparser.Object,
Kind: JsonRootTypeKindSingle,
}
default:
return JsonRootType{
Value: jsonparser.String,
Kind: JsonRootTypeKindSingle,
}
}
}
return JsonRootType{
Value: jsonparser.Object,
Kind: JsonRootTypeKindSingle,
}
}
// GraphQLVariableRenderer is an implementation of VariableRenderer
// It renders variables according to the GraphQL Specification
type GraphQLVariableRenderer struct {
JSONSchema string
Kind string
validator *graphqljsonschema.Validator
rootValueType JsonRootType
}
func (g *GraphQLVariableRenderer) GetKind() string {
return g.Kind
}
// add renderer that renders both variable name and variable value
// before rendering, evaluate if the value contains null values
// if an object contains only null values, set the object to null
// do this recursively until reaching the root of the object
func (g *GraphQLVariableRenderer) RenderVariable(ctx context.Context, data []byte, out io.Writer) error {
if g.validator != nil {
err := g.validator.Validate(ctx, data)
if err != nil {
return fmt.Errorf("could not render GraphQL variable, %w", err)
}
}
var desiredType jsonparser.ValueType
data, desiredType = extractStringWithQuotes(g.rootValueType, data)
return g.renderGraphQLValue(data, desiredType, out)
}
func (g *GraphQLVariableRenderer) renderGraphQLValue(data []byte, valueType jsonparser.ValueType, out io.Writer) (err error) {
switch valueType {
case jsonparser.String:
_, _ = out.Write(literal.BACKSLASH)
_, _ = out.Write(literal.QUOTE)
for i := range data {
switch data[i] {
case '"':
_, _ = out.Write(literal.BACKSLASH)
_, _ = out.Write(literal.BACKSLASH)
_, _ = out.Write(literal.QUOTE)
default:
_, _ = out.Write(data[i : i+1])
}
}
_, _ = out.Write(literal.BACKSLASH)
_, _ = out.Write(literal.QUOTE)
case jsonparser.Object:
_, _ = out.Write(literal.LBRACE)
first := true
err = jsonparser.ObjectEach(data, func(key []byte, value []byte, objectFieldValueType jsonparser.ValueType, offset int) error {
if !first {
_, _ = out.Write(literal.COMMA)
} else {
first = false
}
_, _ = out.Write(key)
_, _ = out.Write(literal.COLON)
return g.renderGraphQLValue(value, objectFieldValueType, out)
})
if err != nil {
return err
}
_, _ = out.Write(literal.RBRACE)
case jsonparser.Null:
_, _ = out.Write(literal.NULL)
case jsonparser.Boolean:
_, _ = out.Write(data)
case jsonparser.Array:
_, _ = out.Write(literal.LBRACK)
first := true
var arrayErr error
_, err = jsonparser.ArrayEach(data, func(value []byte, arrayItemValueType jsonparser.ValueType, offset int, err error) {
if !first {
_, _ = out.Write(literal.COMMA)
} else {
first = false
}
arrayErr = g.renderGraphQLValue(value, arrayItemValueType, out)
})
if arrayErr != nil {
return arrayErr
}
if err != nil {
return err
}
_, _ = out.Write(literal.RBRACK)
case jsonparser.Number:
_, _ = out.Write(data)
}
return
}
func NewCSVVariableRenderer(arrayValueType JsonRootType) *CSVVariableRenderer {
return &CSVVariableRenderer{
Kind: VariableRendererKindCsv,
arrayValueType: arrayValueType,
}
}
func NewCSVVariableRendererFromTypeRef(operation, definition *ast.Document, variableTypeRef int) *CSVVariableRenderer {
return &CSVVariableRenderer{
Kind: VariableRendererKindCsv,
arrayValueType: getJSONRootType(operation, definition, variableTypeRef),
}
}
// CSVVariableRenderer is an implementation of VariableRenderer
// It renders the provided list of Values as comma separated Values in plaintext (no JSON encoding of Values)
type CSVVariableRenderer struct {
Kind string
arrayValueType JsonRootType
}
func (c *CSVVariableRenderer) GetKind() string {
return c.Kind
}
func (c *CSVVariableRenderer) RenderVariable(_ context.Context, data []byte, out io.Writer) error {
isFirst := true
_, err := jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
if !c.arrayValueType.Satisfies(dataType) {
return
}
if isFirst {
isFirst = false
} else {
_, _ = out.Write(literal.COMMA)
}
_, _ = out.Write(value)
})
return err
}
type ContextVariable struct {
Path []string
Renderer VariableRenderer
}
func (c *ContextVariable) TemplateSegment() TemplateSegment {
return TemplateSegment{
SegmentType: VariableSegmentType,
VariableKind: ContextVariableKind,
VariableSourcePath: c.Path,
Renderer: c.Renderer,
}
}
func (c *ContextVariable) Equals(another Variable) bool {
if another == nil {
return false
}
if another.GetVariableKind() != c.GetVariableKind() {
return false
}
anotherContextVariable := another.(*ContextVariable)
if len(c.Path) != len(anotherContextVariable.Path) {
return false
}
for i := range c.Path {
if c.Path[i] != anotherContextVariable.Path[i] {
return false
}
}
return true
}
func (_ *ContextVariable) GetVariableKind() VariableKind {
return ContextVariableKind
}
type ObjectVariable struct {
Path []string
Renderer VariableRenderer
}
func (o *ObjectVariable) TemplateSegment() TemplateSegment {
return TemplateSegment{
SegmentType: VariableSegmentType,
VariableKind: ObjectVariableKind,
VariableSourcePath: o.Path,
Renderer: o.Renderer,
}
}
func (o *ObjectVariable) Equals(another Variable) bool {
if another == nil {
return false
}
if another.GetVariableKind() != o.GetVariableKind() {
return false
}
anotherObjectVariable := another.(*ObjectVariable)
if len(o.Path) != len(anotherObjectVariable.Path) {
return false
}
for i := range o.Path {
if o.Path[i] != anotherObjectVariable.Path[i] {
return false
}
}
return true
}
func (o *ObjectVariable) GetVariableKind() VariableKind {
return ObjectVariableKind
}
type HeaderVariable struct {
Path []string
}
func (h *HeaderVariable) TemplateSegment() TemplateSegment {
return TemplateSegment{
SegmentType: VariableSegmentType,
VariableKind: HeaderVariableKind,
VariableSourcePath: h.Path,
}
}
func (h *HeaderVariable) GetVariableKind() VariableKind {
return HeaderVariableKind
}
func (h *HeaderVariable) Equals(another Variable) bool {
if another == nil {
return false
}
if another.GetVariableKind() != h.GetVariableKind() {
return false
}
anotherHeaderVariable := another.(*HeaderVariable)
if len(h.Path) != len(anotherHeaderVariable.Path) {
return false
}
for i := range h.Path {
if h.Path[i] != anotherHeaderVariable.Path[i] {
return false
}
}
return true
}
type Variable interface {
GetVariableKind() VariableKind
Equals(another Variable) bool
TemplateSegment() TemplateSegment
}
type Variables []Variable
func NewVariables(variables ...Variable) Variables {
return variables
}
const (
variablePrefixSuffix = "$$"
)
func (v *Variables) AddVariable(variable Variable) (name string, exists bool) {
index := -1
for i := range *v {
if (*v)[i].Equals(variable) {
index = i
exists = true
break
}
}
if index == -1 {
*v = append(*v, variable)
index = len(*v) - 1
}
i := strconv.Itoa(index)
name = variablePrefixSuffix + i + variablePrefixSuffix
return
}
type VariableSchema struct {
}
func extractStringWithQuotes(rootValueType JsonRootType, data []byte) ([]byte, jsonparser.ValueType) {
desiredType := jsonparser.Unknown
switch rootValueType.Kind {
case JsonRootTypeKindSingle:
desiredType = rootValueType.Value
case JsonRootTypeKindMultiple:
_, tt, _, _ := jsonparser.Get(data)
if rootValueType.Satisfies(tt) {
desiredType = tt
}
}
if desiredType == jsonparser.String {
return data[1 : len(data)-1], desiredType
}
return data, desiredType
}