File: selected.go

package info (click to toggle)
golang-github-graph-gophers-graphql-go 1.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,516 kB
  • sloc: sh: 373; javascript: 21; makefile: 5
file content (314 lines) | stat: -rw-r--r-- 8,528 bytes parent folder | download
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
package selected

import (
	"context"
	"fmt"
	"reflect"
	"sync"

	"github.com/graph-gophers/graphql-go/ast"
	"github.com/graph-gophers/graphql-go/errors"
	"github.com/graph-gophers/graphql-go/internal/exec/packer"
	"github.com/graph-gophers/graphql-go/internal/exec/resolvable"
	"github.com/graph-gophers/graphql-go/internal/query"
	"github.com/graph-gophers/graphql-go/introspection"
)

type Request struct {
	Schema             *ast.Schema
	Doc                *ast.ExecutableDefinition
	Vars               map[string]interface{}
	Mu                 sync.Mutex
	Errs               []*errors.QueryError
	AllowIntrospection bool
}

func (r *Request) AddError(err *errors.QueryError) {
	r.Mu.Lock()
	r.Errs = append(r.Errs, err)
	r.Mu.Unlock()
}

func ApplyOperation(r *Request, s *resolvable.Schema, op *ast.OperationDefinition) []Selection {
	var obj *resolvable.Object
	switch op.Type {
	case query.Query:
		obj = s.Query.(*resolvable.Object)
	case query.Mutation:
		obj = s.Mutation.(*resolvable.Object)
	case query.Subscription:
		obj = s.Subscription.(*resolvable.Object)
	}
	return applySelectionSet(r, s, obj, op.Selections)
}

type Selection interface {
	isSelection()
}

type SchemaField struct {
	resolvable.Field
	Alias       string
	Args        map[string]interface{}
	PackedArgs  reflect.Value
	Sels        []Selection
	Async       bool
	FixedResult reflect.Value
}

func (f *SchemaField) Resolve(ctx context.Context, resolver reflect.Value) (output interface{}, err error) {
	var args interface{}

	if f.ArgsPacker != nil {
		args = f.PackedArgs.Interface()
	}

	return f.Field.Resolve(ctx, resolver, args)
}

type TypeAssertion struct {
	resolvable.TypeAssertion
	Sels []Selection
}

type TypenameField struct {
	resolvable.Object
	Alias string
}

func (*SchemaField) isSelection()   {}
func (*TypeAssertion) isSelection() {}
func (*TypenameField) isSelection() {}

func applySelectionSet(r *Request, s *resolvable.Schema, e *resolvable.Object, sels []ast.Selection) (flattenedSels []Selection) {
	for _, sel := range sels {
		switch sel := sel.(type) {
		case *ast.Field:
			field := sel
			if skipByDirective(r, field.Directives) {
				continue
			}

			switch field.Name.Name {
			case "__typename":
				// __typename is available even though r.AllowIntrospection == false
				// because it is necessary when using union types and interfaces: https://graphql.org/learn/schema/#union-types
				flattenedSels = append(flattenedSels, &TypenameField{
					Object: *e,
					Alias:  field.Alias.Name,
				})

			case "__schema":
				if r.AllowIntrospection {
					flattenedSels = append(flattenedSels, &SchemaField{
						Field:       s.FieldSchema,
						Alias:       field.Alias.Name,
						Sels:        applySelectionSet(r, s, s.Meta.Schema, field.SelectionSet),
						Async:       true,
						FixedResult: reflect.ValueOf(introspection.WrapSchema(r.Schema)),
					})
				}

			case "__type":
				if r.AllowIntrospection {
					p := packer.ValuePacker{ValueType: reflect.TypeOf("")}
					v, err := p.Pack(field.Arguments.MustGet("name").Deserialize(r.Vars))
					if err != nil {
						r.AddError(errors.Errorf("%s", err))
						return nil
					}

					var resolvedType *introspection.Type
					t, ok := r.Schema.Types[v.String()]
					if ok {
						resolvedType = introspection.WrapType(t)
					}

					flattenedSels = append(flattenedSels, &SchemaField{
						Field:       s.FieldType,
						Alias:       field.Alias.Name,
						Sels:        applySelectionSet(r, s, s.Type, field.SelectionSet),
						Async:       true,
						FixedResult: reflect.ValueOf(resolvedType),
					})
				}

			default:
				fe := e.Fields[field.Name.Name]

				var args map[string]interface{}
				var packedArgs reflect.Value
				if fe.ArgsPacker != nil {
					args = make(map[string]interface{})
					for _, arg := range field.Arguments {
						args[arg.Name.Name] = arg.Value.Deserialize(r.Vars)
					}
					var err error
					packedArgs, err = fe.ArgsPacker.Pack(args)
					if err != nil {
						r.AddError(errors.Errorf("%s", err))
						return
					}
				}

				fieldSels := applyField(r, s, fe.ValueExec, field.SelectionSet)
				flattenedSels = append(flattenedSels, &SchemaField{
					Field:      *fe,
					Alias:      field.Alias.Name,
					Args:       args,
					PackedArgs: packedArgs,
					Sels:       fieldSels,
					Async:      fe.HasContext || fe.ArgsPacker != nil || fe.HasError || HasAsyncSel(fieldSels),
				})
			}

		case *ast.InlineFragment:
			frag := sel
			if skipByDirective(r, frag.Directives) {
				continue
			}
			flattenedSels = append(flattenedSels, applyFragment(r, s, e, &frag.Fragment)...)

		case *ast.FragmentSpread:
			spread := sel
			if skipByDirective(r, spread.Directives) {
				continue
			}
			flattenedSels = append(flattenedSels, applyFragment(r, s, e, &r.Doc.Fragments.Get(spread.Name.Name).Fragment)...)

		default:
			panic("invalid type")
		}
	}
	return
}

func applyFragment(r *Request, s *resolvable.Schema, e *resolvable.Object, frag *ast.Fragment) []Selection {
	if frag.On.Name != e.Name {
		t := r.Schema.Resolve(frag.On.Name)
		face, ok := t.(*ast.InterfaceTypeDefinition)
		if !ok && frag.On.Name != "" {
			a, ok2 := e.TypeAssertions[frag.On.Name]
			if !ok2 {
				panic(fmt.Errorf("%q does not implement %q", frag.On, e.Name)) // TODO proper error handling
			}

			return []Selection{&TypeAssertion{
				TypeAssertion: *a,
				Sels:          applySelectionSet(r, s, a.TypeExec.(*resolvable.Object), frag.Selections),
			}}
		}
		// check if the fragment is on an interface which the current resolvable type implements
		// see the second test in [TestFragments] in the graphql_test.go file.
		if _, found := e.Interfaces[frag.On.Name]; found {
			return applyInterfaceFragment(r, s, e, frag)
		}
		if ok && len(face.PossibleTypes) > 0 {
			sels := []Selection{}
			for _, t := range face.PossibleTypes {
				if t.Name == e.Name {
					return applySelectionSet(r, s, e, frag.Selections)
				}

				if a, ok := e.TypeAssertions[t.Name]; ok {
					sels = append(sels, &TypeAssertion{
						TypeAssertion: *a,
						Sels:          applySelectionSet(r, s, a.TypeExec.(*resolvable.Object), frag.Selections),
					})
				}
			}
			if len(sels) == 0 {
				panic(fmt.Errorf("%q does not implement %q", e.Name, frag.On)) // TODO proper error handling
			}
			return sels
		}
	}
	return applySelectionSet(r, s, e, frag.Selections)
}

func applyInterfaceFragment(r *Request, s *resolvable.Schema, e *resolvable.Object, frag *ast.Fragment) []Selection {
	// if the fragment is on an interface the object type implements, then filter out
	// selections for any fragments that don't match this type.
	var sels []ast.Selection
	for _, sel := range frag.Selections {
		switch sel := sel.(type) {
		case *ast.Field:
			sels = append(sels, sel)
		case *ast.InlineFragment:
			if sel.On.Name != e.Name {
				if _, ok := e.Interfaces[sel.On.Name]; !ok {
					continue
				}
			}
			sels = append(sels, sel)
		case *ast.FragmentSpread:
			f := &r.Doc.Fragments.Get(sel.Name.Name).Fragment
			if f.On.Name != e.Name {
				if _, ok := e.Interfaces[f.On.Name]; !ok {
					continue
				}
			}
			sels = append(sels, sel)
		}
	}
	return applySelectionSet(r, s, e, sels)
}

func applyField(r *Request, s *resolvable.Schema, e resolvable.Resolvable, sels []ast.Selection) []Selection {
	switch e := e.(type) {
	case *resolvable.Object:
		return applySelectionSet(r, s, e, sels)
	case *resolvable.List:
		return applyField(r, s, e.Elem, sels)
	case *resolvable.Scalar:
		return nil
	default:
		panic("unreachable")
	}
}

func skipByDirective(r *Request, directives ast.DirectiveList) bool {
	if d := directives.Get("skip"); d != nil {
		p := packer.ValuePacker{ValueType: reflect.TypeOf(false)}
		v, err := p.Pack(d.Arguments.MustGet("if").Deserialize(r.Vars))
		if err != nil {
			r.AddError(errors.Errorf("%s", err))
		}
		if err == nil && v.Bool() {
			return true
		}
	}

	if d := directives.Get("include"); d != nil {
		p := packer.ValuePacker{ValueType: reflect.TypeOf(false)}
		v, err := p.Pack(d.Arguments.MustGet("if").Deserialize(r.Vars))
		if err != nil {
			r.AddError(errors.Errorf("%s", err))
		}
		if err == nil && !v.Bool() {
			return true
		}
	}

	return false
}

func HasAsyncSel(sels []Selection) bool {
	for _, sel := range sels {
		switch sel := sel.(type) {
		case *SchemaField:
			if sel.Async {
				return true
			}
		case *TypeAssertion:
			if HasAsyncSel(sel.Sels) {
				return true
			}
		case *TypenameField:
			// sync
		default:
			panic("unreachable")
		}
	}
	return false
}