File size: 1,203 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package graphql2

import (
	_ "embed"
	"sort"

	"github.com/target/goalert/validation"
	"github.com/vektah/gqlparser/v2"
	"github.com/vektah/gqlparser/v2/ast"
	"github.com/vektah/gqlparser/v2/validator"
)

var schemaFields []string
var astSchema *ast.Schema

func init() {
	astSchema = NewExecutableSchema(Config{}).Schema()

	for _, typ := range astSchema.Types {
		if typ.Kind != ast.Object {
			continue
		}
		for _, f := range typ.Fields {
			schemaFields = append(schemaFields, typ.Name+"."+f.Name)
		}
	}
	sort.Strings(schemaFields)
}

// SchemaFields will return a list of all fields in the schema.
func SchemaFields() []string { return schemaFields }

// QueryFields will return a list of all fields that the given query references.
func QueryFields(query string) ([]string, error) {
	qDoc, qErr := gqlparser.LoadQueryWithRules(astSchema, query, nil)
	if len(qErr) > 0 {
		return nil, validation.NewFieldError("Query", qErr.Error())
	}

	var fields []string
	var e validator.Events
	e.OnField(func(w *validator.Walker, field *ast.Field) {
		fields = append(fields, field.ObjectDefinition.Name+"."+field.Name)
	})
	validator.Walk(astSchema, qDoc, &e)

	sort.Strings(fields)
	return fields, nil
}