forked from graphql-go/relay
-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.go
179 lines (166 loc) · 4.88 KB
/
node.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
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
package relay
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/graphql-go/graphql"
"golang.org/x/net/context"
"strings"
)
// NodeIDEncoding is Base64 URL encoding without padding.
// It is better than standard encoding because it can be use in URL without percent encoding.
var NodeIDEncoding *base64.Encoding = base64.RawURLEncoding
type NodeDefinitions struct {
NodeInterface *graphql.Interface
NodeField *graphql.Field
NodesField *graphql.Field
}
type NodeDefinitionsConfig struct {
IDFetcher IDFetcherFn
TypeResolve graphql.ResolveTypeFn
}
type IDFetcherFn func(id string, info graphql.ResolveInfo, ctx context.Context) (interface{}, error)
type GlobalIDFetcherFn func(obj interface{}, info graphql.ResolveInfo, ctx context.Context) (string, error)
/*
Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a field config for a `node` root field.
If the typeResolver is omitted, object resolution on the interface will be
handled with the `isTypeOf` method on object types, as with any GraphQL
interface without a provided `resolveType` method.
*/
func NewNodeDefinitions(config NodeDefinitionsConfig) *NodeDefinitions {
nodeInterface := graphql.NewInterface(graphql.InterfaceConfig{
Name: "Node",
Description: "An object with an ID",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.NewNonNull(graphql.ID),
Description: "The id of the object",
},
},
ResolveType: config.TypeResolve,
})
nodeField := &graphql.Field{
Name: "Node",
Description: "Fetches an object given its ID",
Type: nodeInterface,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.ID),
Description: "The ID of an object",
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
if config.IDFetcher == nil {
return nil, nil
}
id := ""
if iid, ok := p.Args["id"]; ok {
id = fmt.Sprintf("%v", iid)
}
return config.IDFetcher(id, p.Info, p.Context)
},
}
nodesField := &graphql.Field{
Name: "Nodes",
Description: "Lookup nodes by a list of IDs.",
Type: graphql.NewNonNull(graphql.NewList(nodeInterface)),
Args: graphql.FieldConfigArgument{
"ids": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(graphql.ID))),
Description: "The list of node IDs.",
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
if config.IDFetcher == nil {
return nil, nil
}
var nodes []interface{}
ifaces := p.Args["ids"].([]interface{})
for _, iface := range ifaces {
id := iface.(string)
node, err := config.IDFetcher(id, p.Info, p.Context)
if err != nil {
return nil, err
}
nodes = append(nodes, node)
}
return nodes, nil
},
}
return &NodeDefinitions{
NodeInterface: nodeInterface,
NodeField: nodeField,
NodesField: nodesField,
}
}
type ResolvedGlobalID struct {
Type string `json:"type"`
ID string `json:"id"`
}
/*
Takes a type name and an ID specific to that type name, and returns a
"global ID" that is unique among all types.
*/
func ToGlobalID(ttype string, id string) string {
str := ttype + ":" + id
encStr := NodeIDEncoding.EncodeToString([]byte(str))
return encStr
}
/*
Takes the "global ID" created by toGlobalID, and returns the type name and ID
used to create it.
*/
func FromGlobalID(globalID string) *ResolvedGlobalID {
strID := ""
b, err := NodeIDEncoding.DecodeString(globalID)
if err == nil {
strID = string(b)
}
tokens := strings.Split(strID, ":")
if len(tokens) < 2 {
return nil
}
return &ResolvedGlobalID{
Type: tokens[0],
ID: tokens[1],
}
}
/*
Creates the configuration for an id field on a node, using `toGlobalId` to
construct the ID from the provided typename. The type-specific ID is fetcher
by calling idFetcher on the object, or if not provided, by accessing the `id`
property on the object.
*/
func GlobalIDField(typeName string, idFetcher GlobalIDFetcherFn) *graphql.Field {
return &graphql.Field{
Name: "id",
Description: "The ID of an object",
Type: graphql.NewNonNull(graphql.ID),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := ""
if idFetcher != nil {
fetched, err := idFetcher(p.Source, p.Info, p.Context)
id = fmt.Sprintf("%v", fetched)
if err != nil {
return id, err
}
} else {
// try to get from p.Source (data)
var objMap interface{}
b, _ := json.Marshal(p.Source)
_ = json.Unmarshal(b, &objMap)
switch obj := objMap.(type) {
case map[string]interface{}:
if iid, ok := obj["id"]; ok {
id = fmt.Sprintf("%v", iid)
}
}
}
globalID := ToGlobalID(typeName, id)
return globalID, nil
},
}
}