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
|
package resolvable
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/graph-gophers/graphql-go/ast"
"github.com/graph-gophers/graphql-go/decode"
"github.com/graph-gophers/graphql-go/internal/exec/packer"
)
const (
Query = "Query"
Mutation = "Mutation"
Subscription = "Subscription"
)
type Schema struct {
*Meta
ast.Schema
Query Resolvable
Mutation Resolvable
Subscription Resolvable
QueryResolver reflect.Value
MutationResolver reflect.Value
SubscriptionResolver reflect.Value
}
type Resolvable interface {
isResolvable()
}
type Object struct {
Name string
Fields map[string]*Field
TypeAssertions map[string]*TypeAssertion
Interfaces map[string]struct{}
}
type Field struct {
ast.FieldDefinition
TypeName string
MethodIndex int
FieldIndex []int
HasContext bool
HasError bool
IsFieldFunc bool
ArgsPacker *packer.StructPacker
ValueExec Resolvable
TraceLabel string
}
func (f *Field) UseMethodResolver() bool {
return f.MethodIndex != -1 || f.IsFieldFunc
}
func (f *Field) Resolve(ctx context.Context, resolver reflect.Value, args interface{}) (output interface{}, err error) {
if !f.UseMethodResolver() {
res := resolver
// TODO extract out unwrapping ptr logic to a common place
if res.Kind() == reflect.Ptr {
res = res.Elem()
}
return res.FieldByIndex(f.FieldIndex).Interface(), nil
}
var in []reflect.Value
var callOut []reflect.Value
if f.HasContext {
in = append(in, reflect.ValueOf(ctx))
}
if f.ArgsPacker != nil {
in = append(in, reflect.ValueOf(args))
}
if f.IsFieldFunc { // resolver is a struct field of type func
res := resolver
if res.Kind() == reflect.Pointer {
res = resolver.Elem()
}
callOut = res.FieldByIndex(f.FieldIndex).Call(in)
} else {
callOut = resolver.Method(f.MethodIndex).Call(in)
}
result := callOut[0]
if f.HasError && !callOut[1].IsNil() {
resolverErr := callOut[1].Interface().(error)
return result.Interface(), resolverErr
}
return result.Interface(), nil
}
type TypeAssertion struct {
MethodIndex int
TypeExec Resolvable
}
type List struct {
Elem Resolvable
}
type Scalar struct{}
func (*Object) isResolvable() {}
func (*List) isResolvable() {}
func (*Scalar) isResolvable() {}
func ApplyResolver(s *ast.Schema, resolver interface{}, useFieldResolvers bool) (*Schema, error) {
if resolver == nil {
return &Schema{Meta: newMeta(s), Schema: *s}, nil
}
b := newBuilder(s, useFieldResolvers)
var query, mutation, subscription Resolvable
resolvers := map[string]interface{}{}
rv := reflect.ValueOf(resolver)
// use separate resolvers in case Query, Mutation and/or Subscription methods are defined
for _, op := range [...]string{Query, Mutation, Subscription} {
m := rv.MethodByName(op)
if m.IsValid() { // if the root resolver has a method for the current operation
mt := m.Type()
if mt.NumIn() != 0 {
return nil, fmt.Errorf("method %q of %v must not accept any arguments, got %d", op, rv.Type(), mt.NumIn())
}
if mt.NumOut() != 1 {
return nil, fmt.Errorf("method %q of %v must have 1 return value, got %d", op, rv.Type(), mt.NumOut())
}
ot := mt.Out(0)
if ot.Kind() != reflect.Pointer && ot.Kind() != reflect.Interface {
return nil, fmt.Errorf("method %q of %v must return an interface or a pointer, got %+v", op, rv.Type(), ot)
}
out := m.Call(nil)
res := out[0]
if res.IsNil() {
return nil, fmt.Errorf("method %q of %v must return a non-nil result, got %v", op, rv.Type(), res)
}
switch res.Kind() {
case reflect.Pointer:
resolvers[op] = res.Elem().Addr().Interface()
case reflect.Interface:
resolvers[op] = res.Elem().Interface()
default:
panic("ureachable")
}
}
// If a method for the current operation is not defined in the root resolver,
// then use the root resolver for the operation.
if resolvers[op] == nil {
resolvers[op] = resolver
}
}
if t, ok := s.RootOperationTypes["query"]; ok {
if err := b.assignExec(&query, t, reflect.TypeOf(resolvers[Query])); err != nil {
return nil, err
}
}
if t, ok := s.RootOperationTypes["mutation"]; ok {
if err := b.assignExec(&mutation, t, reflect.TypeOf(resolvers[Mutation])); err != nil {
return nil, err
}
}
if t, ok := s.RootOperationTypes["subscription"]; ok {
if err := b.assignExec(&subscription, t, reflect.TypeOf(resolvers[Subscription])); err != nil {
return nil, err
}
}
if err := b.finish(); err != nil {
return nil, err
}
return &Schema{
Meta: newMeta(s),
Schema: *s,
QueryResolver: reflect.ValueOf(resolvers[Query]),
MutationResolver: reflect.ValueOf(resolvers[Mutation]),
SubscriptionResolver: reflect.ValueOf(resolvers[Subscription]),
Query: query,
Mutation: mutation,
Subscription: subscription,
}, nil
}
type execBuilder struct {
schema *ast.Schema
resMap map[typePair]*resMapEntry
packerBuilder *packer.Builder
useFieldResolvers bool
}
type typePair struct {
graphQLType ast.Type
resolverType reflect.Type
}
type resMapEntry struct {
exec Resolvable
targets []*Resolvable
}
func newBuilder(s *ast.Schema, useFieldResolvers bool) *execBuilder {
return &execBuilder{
schema: s,
resMap: make(map[typePair]*resMapEntry),
packerBuilder: packer.NewBuilder(),
useFieldResolvers: useFieldResolvers,
}
}
func (b *execBuilder) finish() error {
for _, entry := range b.resMap {
for _, target := range entry.targets {
*target = entry.exec
}
}
return b.packerBuilder.Finish()
}
func (b *execBuilder) assignExec(target *Resolvable, t ast.Type, resolverType reflect.Type) error {
k := typePair{t, resolverType}
ref, ok := b.resMap[k]
if !ok {
ref = &resMapEntry{}
b.resMap[k] = ref
var err error
ref.exec, err = b.makeExec(t, resolverType)
if err != nil {
return err
}
}
ref.targets = append(ref.targets, target)
return nil
}
func (b *execBuilder) makeExec(t ast.Type, resolverType reflect.Type) (Resolvable, error) {
var nonNull bool
t, nonNull = unwrapNonNull(t)
switch t := t.(type) {
case *ast.ObjectTypeDefinition:
return b.makeObjectExec(t.Name, t.Fields, nil, t.Interfaces, nonNull, resolverType)
case *ast.InterfaceTypeDefinition:
return b.makeObjectExec(t.Name, t.Fields, t.PossibleTypes, nil, nonNull, resolverType)
case *ast.Union:
return b.makeObjectExec(t.Name, nil, t.UnionMemberTypes, nil, nonNull, resolverType)
}
if !nonNull {
if resolverType.Kind() != reflect.Ptr {
return nil, fmt.Errorf("%s is not a pointer", resolverType)
}
resolverType = resolverType.Elem()
}
switch t := t.(type) {
case *ast.ScalarTypeDefinition:
return makeScalarExec(t, resolverType)
case *ast.EnumTypeDefinition:
return &Scalar{}, nil
case *ast.List:
if resolverType.Kind() != reflect.Slice {
return nil, fmt.Errorf("%s is not a slice", resolverType)
}
e := &List{}
if err := b.assignExec(&e.Elem, t.OfType, resolverType.Elem()); err != nil {
return nil, err
}
return e, nil
default:
panic("invalid type: " + t.String())
}
}
func makeScalarExec(t *ast.ScalarTypeDefinition, resolverType reflect.Type) (Resolvable, error) {
implementsType := false
switch r := reflect.New(resolverType).Interface().(type) {
case *int32:
implementsType = t.Name == "Int"
case *float64:
implementsType = t.Name == "Float"
case *string:
implementsType = t.Name == "String"
case *bool:
implementsType = t.Name == "Boolean"
case decode.Unmarshaler:
implementsType = r.ImplementsGraphQLType(t.Name)
}
if !implementsType {
return nil, fmt.Errorf("can not use %s as %s", resolverType, t.Name)
}
return &Scalar{}, nil
}
func (b *execBuilder) makeObjectExec(typeName string, fields ast.FieldsDefinition, possibleTypes []*ast.ObjectTypeDefinition, interfaces []*ast.InterfaceTypeDefinition, nonNull bool, resolverType reflect.Type) (*Object, error) {
if !nonNull {
if resolverType.Kind() != reflect.Ptr && resolverType.Kind() != reflect.Interface {
return nil, fmt.Errorf("%s is not a pointer or interface", resolverType)
}
}
methodHasReceiver := resolverType.Kind() != reflect.Interface
Fields := make(map[string]*Field)
rt := unwrapPtr(resolverType)
fieldsCount, fieldTagsCount := fieldCount(rt, map[string]int{}, map[string]int{})
for _, f := range fields {
var fieldIndex []int
methodIndex := findMethod(resolverType, f.Name)
if b.useFieldResolvers && methodIndex == -1 {
// If a resolver field is ambiguous thrown an error unless there is exactly one field with the given graphql
// reflect tag. In that case use the field with the reflect tag.
if fieldTagsCount[f.Name] > 1 {
return nil, fmt.Errorf("%s does not resolve %q: multiple fields have a graphql reflect tag %q", resolverType, typeName, f.Name)
} else if fieldsCount[strings.ToLower(stripUnderscore(f.Name))] > 1 && fieldTagsCount[f.Name] != 1 {
return nil, fmt.Errorf("%s does not resolve %q: ambiguous field %q", resolverType, typeName, f.Name)
}
fieldIndex = findField(rt, f.Name, []int{}, fieldTagsCount)
}
if methodIndex == -1 && len(fieldIndex) == 0 {
var hint string
if findMethod(reflect.PointerTo(resolverType), f.Name) != -1 {
hint = " (hint: the method exists on the pointer type)"
}
return nil, fmt.Errorf("%s does not resolve %q: missing method for field %q%s", resolverType, typeName, f.Name, hint)
}
var m reflect.Method
var sf reflect.StructField
if methodIndex != -1 {
m = resolverType.Method(methodIndex)
} else {
sf = rt.FieldByIndex(fieldIndex)
}
fe, err := b.makeFieldExec(typeName, f, m, sf, methodIndex, fieldIndex, methodHasReceiver)
if err != nil {
var resolverName string
if methodIndex != -1 {
resolverName = m.Name
} else {
resolverName = sf.Name
}
return nil, fmt.Errorf("%s\n\tused by (%s).%s", err, resolverType, resolverName)
}
Fields[f.Name] = fe
}
// Check type assertions when
// 1) using method resolvers
// 2) Or resolver is not an interface type
typeAssertions := make(map[string]*TypeAssertion)
if !b.useFieldResolvers || resolverType.Kind() != reflect.Interface {
for _, impl := range possibleTypes {
methodIndex := findMethod(resolverType, "To"+impl.Name)
if methodIndex == -1 {
return nil, fmt.Errorf("%s does not resolve %q: missing method %q to convert to %q", resolverType, typeName, "To"+impl.Name, impl.Name)
}
m := resolverType.Method(methodIndex)
expectedIn := 0
if methodHasReceiver {
expectedIn = 1
}
if m.Type.NumIn() != expectedIn {
return nil, fmt.Errorf("%s does not resolve %q: method %q should't have any arguments", resolverType, typeName, "To"+impl.Name)
}
if m.Type.NumOut() != 2 {
return nil, fmt.Errorf("%s does not resolve %q: method %q should return a value and a bool indicating success", resolverType, typeName, "To"+impl.Name)
}
a := &TypeAssertion{
MethodIndex: methodIndex,
}
if err := b.assignExec(&a.TypeExec, impl, resolverType.Method(methodIndex).Type.Out(0)); err != nil {
return nil, err
}
typeAssertions[impl.Name] = a
}
}
ifaces := make(map[string]struct{})
for _, iface := range interfaces {
ifaces[iface.Name] = struct{}{}
}
return &Object{
Name: typeName,
Fields: Fields,
TypeAssertions: typeAssertions,
Interfaces: ifaces,
}, nil
}
var (
contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
errorType = reflect.TypeOf((*error)(nil)).Elem()
)
func (b *execBuilder) makeFieldExec(typeName string, f *ast.FieldDefinition, m reflect.Method, sf reflect.StructField, methodIndex int, fieldIndex []int, methodHasReceiver bool) (*Field, error) {
var argsPacker *packer.StructPacker
var hasError bool
var hasContext bool
var isFieldFunc bool
if methodIndex == -1 && len(fieldIndex) > 0 {
if sf.Type.Kind() == reflect.Func {
m.Type = sf.Type
methodHasReceiver = false
isFieldFunc = true
}
}
// Validate resolver method only when there is one
if methodIndex != -1 || isFieldFunc {
in := make([]reflect.Type, m.Type.NumIn())
for i := range in {
in[i] = m.Type.In(i)
}
if methodHasReceiver {
in = in[1:] // first parameter is receiver
}
hasContext = len(in) > 0 && in[0] == contextType
if hasContext {
in = in[1:]
}
if len(f.Arguments) > 0 {
if len(in) == 0 {
return nil, fmt.Errorf("must have `args struct { ... }` argument for field arguments")
}
var err error
argsPacker, err = b.packerBuilder.MakeStructPacker(f.Arguments, in[0])
if err != nil {
return nil, err
}
in = in[1:]
}
if len(in) > 0 {
return nil, fmt.Errorf("too many arguments")
}
maxNumOfReturns := 2
if m.Type.NumOut() < maxNumOfReturns-1 {
return nil, fmt.Errorf("too few return values")
}
if m.Type.NumOut() > maxNumOfReturns {
return nil, fmt.Errorf("too many return values")
}
hasError = m.Type.NumOut() == maxNumOfReturns
if hasError {
if m.Type.Out(maxNumOfReturns-1) != errorType {
return nil, fmt.Errorf(`must have "error" as its last return value`)
}
}
}
fe := &Field{
FieldDefinition: *f,
TypeName: typeName,
MethodIndex: methodIndex,
FieldIndex: fieldIndex,
IsFieldFunc: isFieldFunc,
HasContext: hasContext,
ArgsPacker: argsPacker,
HasError: hasError,
TraceLabel: fmt.Sprintf("GraphQL field: %s.%s", typeName, f.Name),
}
var out reflect.Type
if methodIndex != -1 || isFieldFunc {
out = m.Type.Out(0)
sub, ok := b.schema.RootOperationTypes["subscription"]
if ok && typeName == sub.TypeName() && out.Kind() == reflect.Chan {
out = m.Type.Out(0).Elem()
}
} else {
out = sf.Type
}
if err := b.assignExec(&fe.ValueExec, f.Type, out); err != nil {
return nil, err
}
return fe, nil
}
func findMethod(t reflect.Type, name string) int {
for i := 0; i < t.NumMethod(); i++ {
if strings.EqualFold(stripUnderscore(name), stripUnderscore(t.Method(i).Name)) {
return i
}
}
return -1
}
func findField(t reflect.Type, name string, index []int, matchingTagsCount map[string]int) []int {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.Type.Kind() == reflect.Struct && field.Anonymous {
newIndex := findField(field.Type, name, []int{i}, matchingTagsCount)
if len(newIndex) > 1 {
return append(index, newIndex...)
}
}
if gt, ok := field.Tag.Lookup("graphql"); ok {
if name == gt {
return append(index, i)
}
}
// The current field's tag didn't match, however, if the tag of another field matches,
// then skip the name matching until we find the desired field with the correct tag.
if matchingTagsCount[name] > 0 {
continue
}
if strings.EqualFold(stripUnderscore(name), stripUnderscore(field.Name)) {
return append(index, i)
}
}
return index
}
// fieldCount helps resolve ambiguity when more than one embedded struct contains fields with the same name.
// or when a field has a `graphql` reflect tag with the same name as some other field causing name collision.
func fieldCount(t reflect.Type, count, tagsCount map[string]int) (map[string]int, map[string]int) {
if t.Kind() != reflect.Struct {
return nil, nil
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
var fieldName, gt string
var hasTag bool
if gt, hasTag = field.Tag.Lookup("graphql"); hasTag && gt != "" {
fieldName = gt
} else {
fieldName = strings.ToLower(stripUnderscore(field.Name))
}
if field.Type.Kind() == reflect.Struct && field.Anonymous {
count, tagsCount = fieldCount(field.Type, count, tagsCount)
} else {
if _, ok := count[fieldName]; !ok {
count[fieldName] = 0
}
count[fieldName]++
if !hasTag {
continue
}
if _, ok := count[gt]; !ok {
tagsCount[gt] = 0
}
tagsCount[gt]++
}
}
return count, tagsCount
}
func unwrapNonNull(t ast.Type) (ast.Type, bool) {
if nn, ok := t.(*ast.NonNull); ok {
return nn.OfType, true
}
return t, false
}
func stripUnderscore(s string) string {
return strings.ReplaceAll(s, "_", "")
}
func unwrapPtr(t reflect.Type) reflect.Type {
if t.Kind() == reflect.Ptr {
return t.Elem()
}
return t
}
|