File: example_selection_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 (47 lines) | stat: -rw-r--r-- 1,480 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
package graphql_test

import (
	"context"
	"fmt"

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

type (
	user         struct{ id, name, email string }
	userResolver struct{ u user }
)

func (r *userResolver) ID() graphql.ID { return graphql.ID(r.u.id) }
func (r *userResolver) Name() *string  { return &r.u.name }
func (r *userResolver) Email() *string { return &r.u.email }
func (r *userResolver) Friends(ctx context.Context) []*userResolver {
	// Return a couple of dummy friends (data itself not important for field selection example)
	return []*userResolver{
		{u: user{id: "F1", name: "Bob"}},
		{u: user{id: "F2", name: "Carol"}},
	}
}

type root struct{}

func (r *root) User(ctx context.Context, args struct{ ID string }) *userResolver {
	fields := graphql.SelectedFieldNames(ctx)
	fmt.Println(fields)
	return &userResolver{u: user{id: args.ID, name: "Alice", email: "a@example.com"}}
}

// Example_selectedFieldNames demonstrates SelectedFieldNames usage in a resolver for
// conditional data fetching (e.g. building a DB projection list).
func Example_selectedFieldNames() {
	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, &root{})
	query := `query { user(id: "U1") { id name friends { id name } } }`
	_ = schema.Exec(context.Background(), query, "", nil)
	// Output:
	// [id name friends friends.id friends.name]
}