-
Notifications
You must be signed in to change notification settings - Fork 574
/
index.ts
481 lines (427 loc) · 14 KB
/
index.ts
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { graphqlExpress } from 'apollo-server-express'
import { apolloUploadExpress, GraphQLUpload } from 'apollo-upload-server'
import * as bodyParser from 'body-parser-graphql'
import * as cors from 'cors'
import * as express from 'express'
import {
PathParams,
RequestHandler,
RequestHandlerParams,
} from 'express-serve-static-core'
import * as fs from 'fs'
import {
execute,
GraphQLSchema,
subscribe,
DocumentNode,
print,
GraphQLFieldResolver,
ExecutionResult,
} from 'graphql'
import { importSchema } from 'graphql-import'
import { deflate } from 'graphql-deduplicator'
import expressPlayground from 'graphql-playground-middleware-express'
import {
makeExecutableSchema,
addMockFunctionsToSchema,
defaultMergedResolver,
} from 'graphql-tools'
import {
applyMiddleware as applyFieldMiddleware,
FragmentReplacement,
} from 'graphql-middleware'
import { createServer, Server as HttpServer } from 'http'
import { createServer as createHttpsServer, Server as HttpsServer } from 'https'
import * as path from 'path'
import { SubscriptionServer } from 'subscriptions-transport-ws'
import {
SubscriptionServerOptions,
Options,
OptionsWithHttps,
OptionsWithoutHttps,
Props,
ValidationRules,
} from './types'
import { ITypeDefinitions } from 'graphql-tools/dist/Interfaces'
import { defaultErrorFormatter } from './defaultErrorFormatter'
export { MockList } from 'graphql-tools'
export { PubSub, withFilter } from 'graphql-subscriptions'
export { Options, OptionsWithHttps, OptionsWithoutHttps }
export { GraphQLServerLambda } from './lambda'
// TODO remove once `@types/graphql` is fixed for `execute`
type ExecuteFunction = (
schema: GraphQLSchema,
document: DocumentNode,
rootValue?: any,
contextValue?: any,
variableValues?: {
[key: string]: any
},
operationName?: string,
fieldResolver?: GraphQLFieldResolver<any, any>,
) => Promise<ExecutionResult> | AsyncIterator<ExecutionResult>
export class GraphQLServer {
express: express.Application
subscriptionServer: SubscriptionServer | null
subscriptionServerOptions: SubscriptionServerOptions | null = null
options: Options = {
tracing: { mode: 'http-header' },
port: process.env.PORT || 4000,
deduplicator: true,
endpoint: '/',
subscriptions: '/',
playground: '/',
getEndpoint: false,
}
executableSchema: GraphQLSchema
context: any
private middlewareFragmentReplacements: FragmentReplacement[] = []
private middlewares: {
[key: string]: {
path?: PathParams
handlers: RequestHandler[] | RequestHandlerParams[]
}[]
} = { use: [], get: [], post: [] }
constructor(props: Props) {
this.express = express()
this.subscriptionServer = null
this.context = props.context
if (props.schema) {
this.executableSchema = props.schema
} else if (props.typeDefs && props.resolvers) {
const {
directiveResolvers,
schemaDirectives,
resolvers,
resolverValidationOptions,
typeDefs,
mocks,
} = props
const typeDefsString = mergeTypeDefs(typeDefs)
const uploadMixin = typeDefsString.includes('scalar Upload')
? { Upload: GraphQLUpload }
: {}
this.executableSchema = makeExecutableSchema({
directiveResolvers,
schemaDirectives,
typeDefs: typeDefsString,
resolvers: Array.isArray(resolvers)
? [uploadMixin, ...resolvers]
: [uploadMixin, resolvers],
resolverValidationOptions,
})
if (mocks) {
addMockFunctionsToSchema({
schema: this.executableSchema,
mocks: typeof mocks === 'object' ? mocks : undefined,
preserveResolvers: false,
})
}
}
if (props.middlewares) {
const { schema, fragmentReplacements } = applyFieldMiddleware(
this.executableSchema,
...props.middlewares,
)
this.executableSchema = schema
this.middlewareFragmentReplacements = fragmentReplacements
}
}
// use, get and post mimic the methods on express.Application
// because middleware cannot be inserted, they are stored here
// in start(), they are added in the right place in the middleware stack
use(...handlers: RequestHandlerParams[]): this
use(path: PathParams, ...handlers: RequestHandlerParams[]): this
use(path?, ...handlers): this {
this.middlewares.use.push({ path, handlers })
return this
}
get(path: PathParams, ...handlers: RequestHandlerParams[]): this {
this.middlewares.get.push({ path, handlers })
return this
}
post(path: PathParams, ...handlers: RequestHandlerParams[]): this {
this.middlewares.post.push({ path, handlers })
return this
}
createHttpServer(options: OptionsWithoutHttps): HttpServer
createHttpServer(options: OptionsWithHttps): HttpsServer
createHttpServer(options: Options): HttpServer | HttpsServer {
const app = this.express
this.options = { ...this.options, ...options }
if (this.options.subscriptions) {
this.subscriptionServerOptions =
typeof this.options.subscriptions === 'string'
? { path: this.options.subscriptions }
: { path: '/', ...this.options.subscriptions }
}
const tracing = (req: express.Request) => {
const t = this.options.tracing
if (typeof t === 'boolean') {
return t
} else if (t.mode === 'http-header') {
return req.get('x-apollo-tracing') !== undefined
} else {
return t.mode === 'enabled'
}
}
const formatResponse = (req: express.Request) => {
if (!this.options.deduplicator) {
return this.options.formatResponse
}
return (response, ...args) => {
if (
req.get('X-GraphQL-Deduplicate') &&
response.data &&
!response.data.__schema
) {
response.data = deflate(response.data)
}
return this.options.formatResponse
? this.options.formatResponse(response, ...args)
: response
}
}
// CORS support
if (this.options.cors) {
app.use(cors(this.options.cors))
} else if (this.options.cors !== false) {
app.use(cors())
}
app.post(
this.options.endpoint,
bodyParser.graphql(this.options.bodyParserOptions),
)
if (this.options.uploads) {
app.post(this.options.endpoint, apolloUploadExpress(this.options.uploads))
} else if (this.options.uploads !== false) {
app.post(this.options.endpoint, apolloUploadExpress())
}
// All middlewares added before start() was called are applied to
// the express application here, in the order they were provided
// (following Queue pattern)
while (this.middlewares.use.length > 0) {
const middleware = this.middlewares.use.shift()
if (middleware.path) {
app.use(middleware.path, ...middleware.handlers)
} else {
app.use(...middleware.handlers)
}
}
while (this.middlewares.get.length > 0) {
const middleware = this.middlewares.get.shift()
if (middleware.path) {
app.get(middleware.path, ...middleware.handlers)
}
}
while (this.middlewares.post.length > 0) {
const middleware = this.middlewares.post.shift()
if (middleware.path) {
app.post(middleware.path, ...middleware.handlers)
}
}
app.post(
this.options.endpoint,
graphqlExpress(async (request, response) => {
let context
try {
context =
typeof this.context === 'function'
? await this.context({
request,
response,
fragmentReplacements: this.middlewareFragmentReplacements,
})
: this.context
} catch (e) {
console.error(e)
throw e
}
return {
schema: this.executableSchema,
tracing: tracing(request),
cacheControl: this.options.cacheControl,
formatError: this.options.formatError || defaultErrorFormatter,
logFunction: this.options.logFunction,
rootValue: this.options.rootValue,
validationRules:
typeof this.options.validationRules === 'function'
? this.options.validationRules(request, response)
: this.options.validationRules,
fieldResolver: this.options.fieldResolver || defaultMergedResolver,
formatParams: this.options.formatParams,
formatResponse: formatResponse(request),
debug: this.options.debug,
context,
}
}),
)
// Only add GET endpoint if opted in
if (this.options.getEndpoint) {
app.get(
this.options.getEndpoint === true
? this.options.endpoint
: this.options.getEndpoint,
graphqlExpress(async (request, response) => {
let context
try {
context =
typeof this.context === 'function'
? await this.context({ request, response })
: this.context
} catch (e) {
console.error(e)
throw e
}
return {
schema: this.executableSchema,
tracing: tracing(request),
cacheControl: this.options.cacheControl,
formatError: this.options.formatError || defaultErrorFormatter,
logFunction: this.options.logFunction,
rootValue: this.options.rootValue,
validationRules: this.options.validationRules as ValidationRules,
fieldResolver: this.options.fieldResolver || defaultMergedResolver,
formatParams: this.options.formatParams,
formatResponse: this.options.formatResponse,
debug: this.options.debug,
context,
}
}),
)
}
if (this.options.playground) {
const playgroundOptions = {
endpoint: this.options.endpoint,
subscriptionsEndpoint: this.subscriptionServerOptions
? this.subscriptionServerOptions.path
: undefined,
tabs: this.options.defaultPlaygroundQuery
? [
{
endpoint: this.options.endpoint,
query: this.options.defaultPlaygroundQuery,
},
]
: undefined,
}
app.get(this.options.playground, expressPlayground(playgroundOptions))
}
if (!this.executableSchema) {
throw new Error('No schema defined')
}
const server = this.options.https
? createHttpsServer(this.options.https, app)
: createServer(app)
if (this.subscriptionServerOptions) {
this.createSubscriptionServer(server)
}
return server
}
start(
options: Options,
callback?: ((options: Options) => void),
): Promise<HttpServer | HttpsServer>
start(
callback?: ((options: Options) => void),
): Promise<HttpServer | HttpsServer>
start(
optionsOrCallback?: Options | ((options: Options) => void),
callback?: ((options: Options) => void),
): Promise<HttpServer | HttpsServer> {
const options =
optionsOrCallback && typeof optionsOrCallback === 'function'
? {}
: optionsOrCallback
const callbackFunc = callback
? callback
: optionsOrCallback && typeof optionsOrCallback === 'function'
? optionsOrCallback
: () => null
const server = this.createHttpServer(options as Options)
return new Promise((resolve, reject) => {
const combinedServer = server
combinedServer.listen(this.options.port, () => {
callbackFunc({
...this.options,
port: combinedServer.address().port,
})
resolve(combinedServer)
})
})
}
private createSubscriptionServer(combinedServer: HttpServer | HttpsServer) {
this.subscriptionServer = SubscriptionServer.create(
{
schema: this.executableSchema,
// TODO remove once `@types/graphql` is fixed for `execute`
execute: execute as ExecuteFunction,
subscribe,
onConnect: this.subscriptionServerOptions.onConnect
? this.subscriptionServerOptions.onConnect
: async (connectionParams, webSocket) => ({ ...connectionParams }),
onDisconnect: this.subscriptionServerOptions.onDisconnect,
onOperation: async (message, connection, webSocket) => {
// The following should be replaced when SubscriptionServer accepts a formatError
// parameter for custom error formatting.
// See https://github.com/apollographql/subscriptions-transport-ws/issues/182
connection.formatResponse = value => ({
...value,
errors:
value.errors &&
value.errors.map(
this.options.formatError || defaultErrorFormatter,
),
})
let context
try {
context =
typeof this.context === 'function'
? await this.context({ connection })
: this.context
} catch (e) {
console.error(e)
throw e
}
return { ...connection, context }
},
keepAlive: this.subscriptionServerOptions.keepAlive,
},
{
server: combinedServer,
path: this.subscriptionServerOptions.path,
},
)
}
}
function mergeTypeDefs(typeDefs: ITypeDefinitions): string {
if (typeof typeDefs === 'string') {
if (typeDefs.endsWith('graphql')) {
const schemaPath = path.resolve(typeDefs)
if (!fs.existsSync(schemaPath)) {
throw new Error(`No schema found for path: ${schemaPath}`)
}
return importSchema(schemaPath)
} else {
return typeDefs
}
}
if (typeof typeDefs === 'function') {
typeDefs = typeDefs()
}
if (isDocumentNode(typeDefs)) {
return print(typeDefs)
}
if (Array.isArray(typeDefs)) {
return typeDefs.reduce<string>(
(acc, t) => acc + '\n' + mergeTypeDefs(t),
'',
)
}
throw new Error(
'Typedef is not string, function, DocumentNode or array of previous',
)
}
function isDocumentNode(node: any): node is DocumentNode {
return node.kind === 'Document'
}