-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
292 lines (252 loc) · 7.63 KB
/
index.js
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
'use strict'
const fp = require('fastify-plugin')
const LRU = require('tiny-lru')
const routes = require('./lib/routes')
const { BadRequest, MethodNotAllowed, InternalServerError } = require('http-errors')
const { compileQuery } = require('graphql-jit')
const { Factory } = require('single-user-cache')
const {
parse,
buildSchema,
getOperationAST,
GraphQLObjectType,
GraphQLScalarType,
GraphQLEnumType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLSchema,
extendSchema,
validate,
validateSchema,
execute
} = require('graphql')
const queryDepth = require('./lib/queryDepth')
const kLoaders = Symbol('fastify-gql.loaders')
function buildCache (opts) {
if (Object.prototype.hasOwnProperty.call(opts, 'cache')) {
if (opts.cache === false) {
// no cache
return null
} else if (typeof opts.cache === 'number') {
// cache size as specified
return LRU(opts.cache)
}
}
// default cache, 1024 entries
return LRU(1024)
}
module.exports = fp(async function (app, opts) {
const lru = buildCache(opts)
const lruErrors = buildCache(opts)
const minJit = opts.jit || 0
const queryDepthLimit = opts.queryDepth
if (typeof minJit !== 'number') {
throw new Error('the jit option must be a number')
}
const root = {}
let schema = opts.schema
if (typeof schema === 'string') {
schema = buildSchema(schema)
} else if (!opts.schema) {
schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {}
}),
mutation: opts.defineMutation ? new GraphQLObjectType({
name: 'Mutation',
fields: {}
}) : undefined
})
}
app.ready(async function (err) {
if (err) {
throw err
}
const schemaValidationErrors = validateSchema(schema)
if (schemaValidationErrors.length > 0) {
const err = new Error('schema issues')
err.errors = schemaValidationErrors
throw err
}
})
const graphqlCtx = Symbol('ctx')
if (opts.routes !== false) {
app.register(routes, {
errorHandler: opts.errorHandler,
graphiql: opts.graphiql,
prefix: opts.prefix,
context: opts.context,
schema,
subscription: opts.subscription
})
}
app.decorateReply(graphqlCtx, null)
app.decorateReply('graphql', function (source, context, variables, operationName) {
return app.graphql(source, Object.assign({ reply: this }, context), variables, operationName)
})
app.decorate('graphql', fastifyGraphQl)
fastifyGraphQl.extendSchema = function (s) {
if (typeof s === 'string') {
s = parse(s)
}
schema = extendSchema(schema, s)
}
fastifyGraphQl.defineResolvers = function (resolvers) {
for (const name of Object.keys(resolvers)) {
const type = schema.getType(name)
if (typeof resolvers[name] === 'function') {
root[name] = resolvers[name]
} else if (type instanceof GraphQLObjectType) {
const fields = type.getFields()
const resolver = resolvers[name]
if (resolver.isTypeOf) {
type.isTypeOf = resolver.isTypeOf
delete resolver.isTypeOf
}
for (const prop of Object.keys(resolver)) {
if (name === 'Subscription') {
fields[prop] = {
...fields[prop],
...resolver[prop]
}
} else {
fields[prop].resolve = resolver[prop]
}
}
} else if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
const resolver = resolvers[name]
for (const prop of Object.keys(resolver)) {
type[prop] = resolver[prop]
}
} else if (type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType) {
const resolver = resolvers[name]
type.resolveType = resolver.resolveType
} else {
throw new Error(`Cannot find type ${name}`)
}
}
}
let factory
fastifyGraphQl.defineLoaders = function (loaders) {
// set up the loaders factory
if (!factory) {
factory = new Factory()
app.decorateReply(kLoaders)
app.addHook('onRequest', async function (req, reply) {
reply[kLoaders] = factory.create({ req, reply, app })
})
}
function defineLoader (name) {
// async needed because of throw
return async function (obj, params, { reply }) {
if (!reply) {
throw new Error('loaders only work via reply.graphql()')
}
return reply[kLoaders][name]({ obj, params })
}
}
const resolvers = {}
for (const typeKey of Object.keys(loaders)) {
const type = loaders[typeKey]
resolvers[typeKey] = {}
for (const prop of Object.keys(type)) {
const name = typeKey + '-' + prop
resolvers[typeKey][prop] = defineLoader(name)
if (typeof type[prop] === 'function') {
factory.add(name, type[prop])
} else {
factory.add(name, type[prop].opts, type[prop].loader)
}
}
}
fastifyGraphQl.defineResolvers(resolvers)
}
if (opts.resolvers) {
fastifyGraphQl.defineResolvers(opts.resolvers)
}
if (opts.loaders) {
fastifyGraphQl.defineLoaders(opts.loaders)
}
async function fastifyGraphQl (source, context, variables, operationName) {
context = Object.assign({ app: this }, context)
const reply = context.reply
// Parse, with a little lru
const cached = lru !== null && lru.get(source)
let document = null
if (!cached) {
// We use two caches to avoid errors bust the good
// cache. This is a protection against DoS attacks
const cachedError = lruErrors !== null && lruErrors.get(source)
if (cachedError) {
// this query errored
const err = new BadRequest()
err.errors = cachedError.validationErrors
throw err
}
try {
document = parse(source)
} catch (syntaxError) {
const err = new BadRequest()
err.errors = [syntaxError]
throw err
}
// Validate
const validationErrors = validate(schema, document)
if (validationErrors.length > 0) {
if (lruErrors) {
lruErrors.set(source, { document, validationErrors })
}
const err = new BadRequest()
err.errors = validationErrors
throw err
}
if (queryDepthLimit) {
const queryDepthErrors = queryDepth(document.definitions, queryDepthLimit)
if (queryDepthErrors.length > 0) {
const err = new BadRequest()
err.errors = queryDepthErrors
throw err
}
}
if (lru) {
lru.set(source, { document, validationErrors, count: 1, jit: null })
}
} else {
document = cached.document
}
if (reply && reply.request.raw.method === 'GET') {
// let's validate we cannot do mutations here
const operationAST = getOperationAST(document, operationName)
if (operationAST.operation !== 'query') {
const err = new MethodNotAllowed()
err.errors = [new Error('Operation cannot be perfomed via a GET request')]
throw err
}
}
// minJit is 0 by default
if (cached && cached.count++ === minJit) {
cached.jit = compileQuery(schema, document, operationName)
}
if (cached && cached.jit !== null) {
const res = await cached.jit.query(root, context, variables || {})
return res
}
const execution = await execute(
schema,
document,
root,
context,
variables,
operationName
)
if (execution.errors) {
const err = new InternalServerError()
err.errors = execution.errors
throw err
}
return execution
}
}, {
name: 'fastify-gql'
})