File: example_selection2_test.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 (49 lines) | stat: -rw-r--r-- 1,706 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
package graphql_test

import (
	"context"
	"fmt"

	"github.com/graph-gophers/graphql-go"
)

type (
	user2         struct{ id, name, email string }
	userResolver2 struct{ u user2 }
)

func (r *userResolver2) ID() graphql.ID                               { return graphql.ID(r.u.id) }
func (r *userResolver2) Name() *string                                { return &r.u.name }
func (r *userResolver2) Email() *string                               { return &r.u.email }
func (r *userResolver2) Friends(ctx context.Context) []*userResolver2 { return nil }

type root2 struct{}

func (r *root2) User(ctx context.Context, args struct{ ID string }) *userResolver2 {
	if graphql.HasSelectedField(ctx, "email") {
		fmt.Println("email requested")
	}
	if graphql.HasSelectedField(ctx, "friends") {
		fmt.Println("friends requested")
	}
	return &userResolver2{u: user2{id: args.ID, name: "Alice", email: "a@example.com"}}
}

// Example_hasSelectedField demonstrates HasSelectedField helper for conditional
// logic without needing the full slice of field names. This can be handy when
// checking for a small number of specific fields (avoids allocating the names
// slice if it hasn't already been built).
func Example_hasSelectedField() {
	const s = `
		schema { query: Query }
		type Query { user(id: ID!): User }
		type User { id: ID! name: String email: String friends: [User!]! }
	`
	schema := graphql.MustParseSchema(s, &root2{})
	// Select a subset of fields including a nested composite field; friends requires its own selection set.
	query := `query { user(id: "U1") { id email friends { id } } }`
	_ = schema.Exec(context.Background(), query, "", nil)
	// Output:
	// email requested
	// friends requested
}