-
Notifications
You must be signed in to change notification settings - Fork 5
/
config.go
261 lines (226 loc) · 8.13 KB
/
config.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
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
package apifu
import (
"context"
"encoding/json"
"net/http"
"sync"
"github.com/sirupsen/logrus"
"github.com/ccbrown/api-fu/graphql"
)
// Config defines the schema and other parameters for an API.
type Config struct {
Logger logrus.FieldLogger
WebSocketOriginCheck func(r *http.Request) bool
// If given, these fields will be added to the Node interface.
AdditionalNodeFields map[string]*graphql.FieldDefinition
// Invoked to get nodes by their global ids.
ResolveNodesByGlobalIds func(ctx context.Context, ids []string) ([]interface{}, error)
// If given, Apollo persisted queries are supported by the API:
// https://www.apollographql.com/docs/react/api/link/persisted-queries/
PersistedQueryStorage PersistedQueryStorage
// When calculating field costs, this is used as the default. This is typically either
// `graphql.FieldCost{Resolver: 1}` or left as zero.
DefaultFieldCost graphql.FieldCost
// Execute is invoked to execute a GraphQL request. If not given, this is simply
// graphql.Execute. You may wish to provide this to perform request logging or
// pre/post-processing.
Execute func(*graphql.Request, *RequestInfo) *graphql.Response
// If given, this function is invoked when the servers receives the graphql-ws connection init
// payload. If an error is returned, it will be sent to the client and the connection will be
// closed. Otherwise the returned context will become associated with the connection.
//
// This is commonly used for authentication.
HandleGraphQLWSInit func(ctx context.Context, parameters json.RawMessage) (context.Context, error)
// Explicitly adds named types to the schema. This is generally only required for interface
// implementations that aren't explicitly referenced elsewhere in the schema.
AdditionalTypes map[string]graphql.NamedType
// If given, these function will be executed as the schema is built. It is executed on a clone
// of the schema and can be used to make last minute modifications to types, such as injecting
// documentation.
PreprocessGraphQLSchemaDefinition func(schema *graphql.SchemaDefinition) error
// If given, this function will be invoked to get the feature set for a request.
Features func(ctx context.Context) graphql.FeatureSet
initOnce sync.Once
nodeInterface *graphql.InterfaceType
query *graphql.ObjectType
mutation *graphql.ObjectType
subscription *graphql.ObjectType
}
func (cfg *Config) init() {
cfg.initOnce.Do(func() {
if cfg.AdditionalTypes == nil {
cfg.AdditionalTypes = make(map[string]graphql.NamedType)
}
cfg.nodeInterface = &graphql.InterfaceType{
Name: "Node",
Fields: map[string]*graphql.FieldDefinition{
"id": {
Type: graphql.NewNonNullType(graphql.IDType),
Description: "The global id of the node.",
},
},
}
for k, v := range cfg.AdditionalNodeFields {
cfg.nodeInterface.Fields[k] = v
}
cfg.query = &graphql.ObjectType{
Name: "Query",
Fields: map[string]*graphql.FieldDefinition{
"node": {
Type: cfg.nodeInterface,
Description: "Gets a node by its global id.",
Arguments: map[string]*graphql.InputValueDefinition{
"id": {
Type: graphql.NewNonNullType(graphql.IDType),
Description: "The global id of the node to get.",
},
},
Cost: graphql.FieldResolverCost(1),
Resolve: func(ctx graphql.FieldContext) (interface{}, error) {
// TODO: batching?
if id, ok := ctx.Arguments["id"].(string); ok {
nodes, err := ctxAPI(ctx.Context).config.ResolveNodesByGlobalIds(ctx.Context, []string{id})
if err != nil || len(nodes) == 0 {
return nil, err
}
return nodes[0], nil
} else {
return nil, nil
}
},
},
"nodes": {
Type: graphql.NewListType(cfg.nodeInterface),
Description: "Gets nodes for multiple ids. Non-existent nodes are not returned and the order of the returned nodes is arbitrary, so clients should check their ids.",
Arguments: map[string]*graphql.InputValueDefinition{
"ids": {
Type: graphql.NewNonNullType(graphql.NewListType(graphql.NewNonNullType(graphql.IDType))),
Description: "The global ids of the nodes to get.",
},
},
Cost: func(ctx graphql.FieldCostContext) graphql.FieldCost {
ids, _ := ctx.Arguments["ids"].([]interface{})
return graphql.FieldCost{
Resolver: 1,
Multiplier: len(ids),
}
},
Resolve: func(ctx graphql.FieldContext) (interface{}, error) {
var ids []string
for _, id := range ctx.Arguments["ids"].([]interface{}) {
if id, ok := id.(string); ok {
ids = append(ids, id)
}
}
return ctxAPI(ctx.Context).config.ResolveNodesByGlobalIds(ctx.Context, ids)
},
},
},
}
})
}
func (cfg *Config) graphqlSchemaDefinition() (*graphql.SchemaDefinition, error) {
additionalTypes := make([]graphql.NamedType, 0, len(cfg.AdditionalTypes))
for _, t := range cfg.AdditionalTypes {
additionalTypes = append(additionalTypes, t)
}
ret := &graphql.SchemaDefinition{
Query: cfg.query,
Mutation: cfg.mutation,
Subscription: cfg.subscription,
AdditionalTypes: additionalTypes,
Directives: map[string]*graphql.DirectiveDefinition{
"include": graphql.IncludeDirective,
"skip": graphql.SkipDirective,
},
}
if cfg.PreprocessGraphQLSchemaDefinition != nil {
ret = ret.Clone()
if err := cfg.PreprocessGraphQLSchemaDefinition(ret); err != nil {
return nil, err
}
}
return ret, nil
}
func (cfg *Config) graphqlSchema() (*graphql.Schema, error) {
def, err := cfg.graphqlSchemaDefinition()
if err != nil {
return nil, err
}
return graphql.NewSchema(def)
}
// AddNamedType adds a named type to the schema. This is generally only required for interface
// implementations that aren't explicitly referenced elsewhere in the schema.
func (cfg *Config) AddNamedType(t graphql.NamedType) {
cfg.init()
cfg.AdditionalTypes[t.TypeName()] = t
}
// NodeInterface returns the node interface.
func (cfg *Config) NodeInterface() *graphql.InterfaceType {
cfg.init()
return cfg.nodeInterface
}
// MutationType returns the root mutation type.
func (cfg *Config) MutationType() *graphql.ObjectType {
cfg.init()
if cfg.mutation == nil {
cfg.mutation = &graphql.ObjectType{
Name: "Mutation",
Fields: map[string]*graphql.FieldDefinition{},
}
}
return cfg.mutation
}
// AddMutation adds a mutation to your schema.
func (cfg *Config) AddMutation(name string, def *graphql.FieldDefinition) {
t := cfg.MutationType()
if _, ok := t.Fields[name]; ok {
panic("a mutation with that name already exists")
}
t.Fields[name] = def
}
// AddSubscription adds a subscription operation to your schema.
//
// When a subscription is started, your resolver will be invoked with ctx.IsSubscribe set to true.
// When this happens, you should return a pointer to a SubscriptionSourceStream (or an error). For
// example:
//
// Resolve: func(ctx graphql.FieldContext) (interface{}, error) {
// if ctx.IsSubscribe {
// ticker := time.NewTicker(time.Second)
// return &apifu.SubscriptionSourceStream{
// EventChannel: ticker.C,
// Stop: ticker.Stop,
// }, nil
// } else if ctx.Object != nil {
// return ctx.Object, nil
// } else {
// return nil, fmt.Errorf("Subscriptions are not supported using this protocol.")
// }
// },
func (cfg *Config) AddSubscription(name string, def *graphql.FieldDefinition) {
cfg.init()
if cfg.subscription == nil {
cfg.subscription = &graphql.ObjectType{
Name: "Subscription",
Fields: map[string]*graphql.FieldDefinition{},
}
}
if _, ok := cfg.subscription.Fields[name]; ok {
panic("a subscription with that name already exists")
}
cfg.subscription.Fields[name] = def
}
// QueryType returns the root query type.
func (cfg *Config) QueryType() *graphql.ObjectType {
cfg.init()
return cfg.query
}
// AddQueryField adds a field to your schema's query object.
func (cfg *Config) AddQueryField(name string, def *graphql.FieldDefinition) {
t := cfg.QueryType()
if _, ok := t.Fields[name]; ok {
panic("a field with that name already exists")
}
t.Fields[name] = def
}