forked from graphql-go/graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (69 loc) · 1.78 KB
/
main.go
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/graphql-go/graphql"
)
type User struct {
ID int `json:"id"`
}
var UserType = graphql.NewObject(graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.Int,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
rootValue := p.Info.RootValue.(map[string]interface{})
if rootValue["data-from-parent"] == "ok" &&
rootValue["data-before-execution"] == "ok" {
user := p.Source.(User)
return user.ID, nil
}
return nil, nil
},
},
},
})
func main() {
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"users": &graphql.Field{
Type: graphql.NewList(UserType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
rootValue := p.Info.RootValue.(map[string]interface{})
rootValue["data-from-parent"] = "ok"
result := []User{
User{ID: 1},
}
return result, nil
},
},
},
}),
})
if err != nil {
log.Fatal(err)
}
ctx := context.WithValue(context.Background(), "currentUser", User{ID: 100})
// Instead of trying to modify context within a resolve function, use:
// `graphql.Params.RootObject` is a mutable optional variable and available on
// each resolve function via: `graphql.ResolveParams.Info.RootValue`.
rootObject := map[string]interface{}{
"data-before-execution": "ok",
}
result := graphql.Do(graphql.Params{
Context: ctx,
RequestString: "{ users { id } }",
RootObject: rootObject,
Schema: schema,
})
b, err := json.Marshal(result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", string(b)) // {"data":{"users":[{"id":1}]}}
}