-
Notifications
You must be signed in to change notification settings - Fork 565
/
server.ts
675 lines (630 loc) · 19.2 KB
/
server.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
import { GraphQLError, GraphQLSchema, isSchema, print } from 'graphql'
import {
GetEnvelopedFn,
envelop,
useMaskedErrors,
UseMaskedErrorsOpts,
useExtendContext,
enableIf,
useLogger,
useSchema,
PromiseOrValue,
} from '@envelop/core'
import { useValidationCache, ValidationCache } from '@envelop/validation-cache'
import { ParserCacheOptions, useParserCache } from '@envelop/parser-cache'
import { makeExecutableSchema } from '@graphql-tools/schema'
import { ExecutionResult, IResolvers, TypeSource } from '@graphql-tools/utils'
import {
CORSOptions,
GraphQLServerInject,
YogaInitialContext,
FetchEvent,
FetchAPI,
GraphQLParams,
} from './types'
import {
OnRequestParseDoneHook,
OnRequestParseHook,
Plugin,
RequestParser,
} from './plugins/types'
import {
GraphiQLOptions,
renderGraphiQL,
shouldRenderGraphiQL,
} from './graphiql'
import * as crossUndiciFetch from 'cross-undici-fetch'
import { processRequest } from './processRequest'
import { defaultYogaLogger, titleBold, YogaLogger } from './logger'
import { useGETRequestParser } from './plugins/requestParser/GET'
import { usePOSTRequestParser } from './plugins/requestParser/POST'
import { usePOSTMultipartRequestParser } from './plugins/requestParser/POSTMultipart'
import { getCORSHeadersByRequestAndOptions } from './cors'
interface OptionsWithPlugins<TContext> {
/**
* Envelop Plugins
* @see https://envelop.dev/plugins
*/
plugins: Array<Plugin<TContext> | Plugin | {}>
}
/**
* Configuration options for the server
*/
export type YogaServerOptions<
TServerContext extends Record<string, any>,
TUserContext extends Record<string, any>,
TRootValue,
> = {
/**
* Enable/disable logging or provide a custom logger.
* @default true
*/
logging?: boolean | YogaLogger
/**
* Prevent leaking unexpected errors to the client. We highly recommend enabling this in production.
* If you throw `GraphQLYogaError`/`EnvelopError` within your GraphQL resolvers then that error will be sent back to the client.
*
* You can lean more about this here:
* @see https://graphql-yoga.vercel.app/docs/features/error-masking
*
* Default: `true`
*/
maskedErrors?: boolean | UseMaskedErrorsOpts
/**
* Context
*/
context?:
| ((
initialContext: YogaInitialContext & TServerContext,
) => Promise<TUserContext> | TUserContext)
| Promise<TUserContext>
| TUserContext
cors?:
| ((
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
) => CORSOptions)
| CORSOptions
| boolean
/**
* GraphQL endpoint
*/
endpoint?: string
/**
* GraphiQL options
*
* Default: `true`
*/
graphiql?:
| GraphiQLOptions
| ((
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
) => GraphiQLOptions | boolean)
| boolean
renderGraphiQL?: (options?: GraphiQLOptions) => PromiseOrValue<BodyInit>
schema?:
| GraphQLSchema
| {
typeDefs: TypeSource
resolvers?:
| IResolvers<
TRootValue,
TUserContext & TServerContext & YogaInitialContext
>
| Array<
IResolvers<
TRootValue,
TUserContext & TServerContext & YogaInitialContext
>
>
}
parserCache?: boolean | ParserCacheOptions
validationCache?: boolean | ValidationCache
fetchAPI?: FetchAPI
multipart?: boolean
} & Partial<
OptionsWithPlugins<TUserContext & TServerContext & YogaInitialContext>
>
export function getDefaultSchema() {
return makeExecutableSchema({
typeDefs: /* GraphQL */ `
"""
Greetings from GraphQL Yoga!
"""
type Query {
greetings: String
}
type Subscription {
"""
Current Time
"""
time: String
}
`,
resolvers: {
Query: {
greetings: () =>
'This is the `greetings` field of the root `Query` type',
},
Subscription: {
time: {
subscribe: async function* () {
while (true) {
yield { time: new Date().toISOString() }
await new Promise((resolve) => setTimeout(resolve, 1000))
}
},
},
},
},
})
}
/**
* Base class that can be extended to create a GraphQL server with any HTTP server framework.
* @internal
*/
export class YogaServer<
TServerContext extends Record<string, any>,
TUserContext extends Record<string, any>,
TRootValue,
> {
/**
* Instance of envelop
*/
public readonly getEnveloped: GetEnvelopedFn<
TUserContext & TServerContext & YogaInitialContext
>
public logger: YogaLogger
private readonly corsOptionsFactory: (
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
) => CORSOptions = () => ({})
protected readonly graphiqlOptionsFactory: (
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
) => GraphiQLOptions | boolean
protected endpoint?: string
protected fetchAPI: {
Request: typeof Request
Response: typeof Response
fetch: typeof fetch
ReadableStream: typeof ReadableStream
}
protected plugins: Array<
Plugin<TUserContext & TServerContext & YogaInitialContext, TServerContext>
>
private onRequestParseHooks: OnRequestParseHook<TServerContext>[]
renderGraphiQL: (options?: GraphiQLOptions) => PromiseOrValue<BodyInit>
constructor(
options?: YogaServerOptions<TServerContext, TUserContext, TRootValue>,
) {
this.fetchAPI = {
Request: options?.fetchAPI?.Request ?? crossUndiciFetch.Request,
Response: options?.fetchAPI?.Response ?? crossUndiciFetch.Response,
fetch: options?.fetchAPI?.fetch ?? crossUndiciFetch.fetch,
ReadableStream:
options?.fetchAPI?.ReadableStream ?? crossUndiciFetch.ReadableStream,
}
const schema = options?.schema
? isSchema(options.schema)
? options.schema
: makeExecutableSchema({
typeDefs: options.schema.typeDefs,
resolvers: options.schema.resolvers,
})
: getDefaultSchema()
const logger = options?.logging != null ? options.logging : true
this.logger =
typeof logger === 'boolean'
? logger === true
? defaultYogaLogger
: {
debug: () => {},
error: () => {},
warn: () => {},
info: () => {},
}
: logger
const maskedErrors = options?.maskedErrors ?? true
this.plugins = [
// Use the schema provided by the user
enableIf(schema != null, useSchema(schema!)),
// Performance things
enableIf(options?.parserCache !== false, () =>
useParserCache(
typeof options?.parserCache === 'object'
? options?.parserCache
: undefined,
),
),
enableIf(options?.validationCache !== false, () =>
useValidationCache({
cache:
typeof options?.validationCache === 'object'
? options?.validationCache
: undefined,
}),
),
// Log events - useful for debugging purposes
enableIf(
logger !== false,
useLogger({
skipIntrospection: true,
logFn: (eventName, events) => {
switch (eventName) {
case 'execute-start':
case 'subscribe-start':
this.logger.debug(titleBold('Execution start'))
const {
query,
operationName,
variables,
extensions,
}: YogaInitialContext = events.args.contextValue
if (query) {
this.logger.debug(
'\n' + titleBold('Received GraphQL operation:') + '\n',
query,
)
}
if (operationName) {
this.logger.debug('\t operationName:', operationName)
}
if (variables) {
this.logger.debug('\t variables:', variables)
}
if (extensions) {
this.logger.debug('\t extensions:', extensions)
}
break
case 'execute-end':
case 'subscribe-end':
this.logger.debug(titleBold('Execution end'))
this.logger.debug('\t result:', events.result)
break
}
},
}),
),
enableIf(
options?.context != null,
useExtendContext(async (initialContext) => {
if (options?.context) {
if (typeof options.context === 'function') {
return (options.context as Function)(initialContext)
} else {
return options.context
}
}
}),
),
useGETRequestParser(),
usePOSTRequestParser(),
enableIf(options?.multipart !== false, () =>
usePOSTMultipartRequestParser(),
),
usePOSTMultipartRequestParser(),
...(options?.plugins ?? []),
enableIf(
!!maskedErrors,
useMaskedErrors(
typeof maskedErrors === 'object' ? maskedErrors : undefined,
),
),
]
this.getEnveloped = envelop({
plugins: this.plugins,
}) as GetEnvelopedFn<TUserContext & TServerContext & YogaInitialContext>
this.onRequestParseHooks = []
for (const plugin of this.plugins) {
if (plugin && plugin.onRequestParse != null) {
this.onRequestParseHooks.push(plugin.onRequestParse.bind(plugin))
}
}
if (options?.cors != null) {
if (typeof options.cors === 'function') {
this.corsOptionsFactory = options.cors
} else if (typeof options.cors === 'object') {
const corsOptions = {
...options.cors,
}
this.corsOptionsFactory = () => corsOptions
} else if (options.cors === false) {
this.corsOptionsFactory = () => false
}
}
if (typeof options?.graphiql === 'function') {
this.graphiqlOptionsFactory = options.graphiql
} else if (typeof options?.graphiql === 'object') {
this.graphiqlOptionsFactory = () => options.graphiql as GraphiQLOptions
} else if (options?.graphiql === false) {
this.graphiqlOptionsFactory = () => false
} else {
this.graphiqlOptionsFactory = () => ({})
}
this.renderGraphiQL = options?.renderGraphiQL || renderGraphiQL
this.endpoint = options?.endpoint
}
getCORSResponseHeaders(
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
): Record<string, string> {
const corsOptions = this.corsOptionsFactory(request, ...args)
return getCORSHeadersByRequestAndOptions(request, corsOptions)
}
handleOptions(
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
) {
const headers = this.getCORSResponseHeaders(request, ...args)
const optionsResponse = new this.fetchAPI.Response(null, {
status: 204,
headers,
})
return optionsResponse
}
private id = Date.now().toString()
handleRequest = async (
request: Request,
...args: {} extends TServerContext
? [serverContext?: TServerContext | undefined]
: [serverContext: TServerContext]
) => {
const serverContext = args[0]
try {
if (request.method === 'OPTIONS') {
return this.handleOptions(request, ...args)
}
const requestPath = request.url.split('?')[0]
if (requestPath.endsWith('/health')) {
this.logger.debug(`Responding Health Check`)
return new this.fetchAPI.Response(`{ "message": "alive" }`, {
status: 200,
headers: {
'Content-Type': 'application/json',
'x-yoga-id': this.id,
},
})
}
if (requestPath.endsWith('/readiness')) {
this.logger.debug(`Responding Readiness Check`)
const readinessResponse = await this.fetchAPI.fetch(
request.url.replace('/readiness', '/health'),
)
const { message } = await readinessResponse.json()
if (
readinessResponse.status === 200 &&
readinessResponse.headers.get('x-yoga-id') === this.id &&
message === 'alive'
) {
return new this.fetchAPI.Response(`{ "message": "ready" }`, {
status: 200,
headers: {
'Content-Type': 'application/json',
},
})
}
throw new Error(
`Readiness check failed with status ${readinessResponse.status}`,
)
}
if (this.endpoint != null && !requestPath.endsWith(this.endpoint)) {
this.logger.debug(`Responding 404 Not Found`)
return new this.fetchAPI.Response(
`Unable to ${request.method} ${requestPath}`,
{
status: 404,
statusText: `Not Found`,
},
)
}
if (shouldRenderGraphiQL(request)) {
this.logger.debug(`Rendering GraphiQL`)
let graphiqlOptions = this.graphiqlOptionsFactory(request, ...args)
if (graphiqlOptions) {
const graphiQLBody = await this.renderGraphiQL({
endpoint: this.endpoint,
...(graphiqlOptions === true ? {} : graphiqlOptions),
})
return new this.fetchAPI.Response(graphiQLBody, {
headers: {
'Content-Type': 'text/html',
},
status: 200,
})
}
}
let requestParser: RequestParser = () => ({})
let onRequestParseDoneList: OnRequestParseDoneHook[] = []
for (const onRequestParse of this.onRequestParseHooks) {
const onRequestParseResult = await onRequestParse({
serverContext,
request,
requestParser,
setRequestParser(parser: RequestParser) {
requestParser = parser
},
})
if (onRequestParseResult?.onRequestParseDone != null) {
onRequestParseDoneList.push(onRequestParseResult.onRequestParseDone)
}
}
this.logger.debug(`Extracting GraphQL Parameters`)
let params = await requestParser(request)
for (const onRequestParseDone of onRequestParseDoneList) {
await onRequestParseDone({
params,
setParams(newParams: GraphQLParams) {
params = newParams
},
})
}
const initialContext = {
request,
...params,
...serverContext,
} as YogaInitialContext & TServerContext
const { execute, validate, subscribe, parse, contextFactory, schema } =
this.getEnveloped(initialContext)
this.logger.debug(`Processing GraphQL Parameters`)
const corsHeaders = this.getCORSResponseHeaders(request, initialContext)
const response = await processRequest({
request,
query: initialContext.query,
variables: initialContext.variables,
operationName: initialContext.operationName,
execute,
validate,
subscribe,
parse,
contextFactory,
schema,
extraHeaders: corsHeaders,
Response: this.fetchAPI.Response,
ReadableStream: this.fetchAPI.ReadableStream,
})
return response
} catch (error: any) {
const response = new this.fetchAPI.Response(
JSON.stringify({
errors: [
error instanceof GraphQLError
? error
: {
message: error.message,
},
],
}),
{
status: 500,
statusText: 'Internal Server Error',
},
)
return response
}
}
/**
* Testing utility to mock http request for GraphQL endpoint
*
*
* Example - Test a simple query
* ```ts
* const response = await yoga.inject({
* document: "query { ping }",
* })
* expect(response.statusCode).toBe(200)
* expect(response.data.ping).toBe('pong')
* ```
**/
async inject<TData = any, TVariables = any>({
document,
variables,
operationName,
headers,
serverContext,
}: GraphQLServerInject<TData, TVariables, TServerContext>): Promise<{
response: Response
executionResult: ExecutionResult<TData> | null
}> {
const request = new this.fetchAPI.Request('http://localhost/graphql', {
method: 'POST',
headers,
body: JSON.stringify({
query:
document &&
(typeof document === 'string' ? document : print(document)),
variables,
operationName,
}),
})
const response = await this.handleRequest(
request,
serverContext as TServerContext,
)
let executionResult: ExecutionResult<TData> | null = null
if (response.headers.get('content-type') === 'application/json') {
executionResult = await response.json()
}
return {
response,
executionResult,
}
}
fetch: WindowOrWorkerGlobalScope['fetch'] = (
input: RequestInfo,
init: RequestInit,
) => {
let request: Request
if (typeof input === 'string') {
request = new this.fetchAPI.Request(input, init)
} else {
request = input
}
return this.handleRequest(request, init as any)
}
// FetchEvent is not available in all envs
private fetchEventListener = (event: FetchEvent) =>
event.respondWith(this.handleRequest(event.request, event as any))
start() {
self.addEventListener('fetch', this.fetchEventListener as EventListener)
}
stop() {
self.removeEventListener('fetch', this.fetchEventListener as EventListener)
}
}
export type YogaServerInstance<TServerContext, TUserContext, TRootValue> =
YogaServer<TServerContext, TUserContext, TRootValue> &
(
| WindowOrWorkerGlobalScope['fetch']
| ((context: { request: Request }) => Promise<Response>)
)
export function createServer<
TServerContext extends Record<string, any> = {},
TUserContext extends Record<string, any> = {},
TRootValue = {},
>(
options?: YogaServerOptions<TServerContext, TUserContext, TRootValue>,
): YogaServerInstance<TServerContext, TUserContext, TRootValue> {
const server = new YogaServer<TServerContext, TUserContext, TRootValue>(
options,
)
// TODO: Will be removed once we get rid of classes
const fnHandler = (input: any) => {
if (input.request) {
return server.handleRequest(input.request, input as any)
} else {
return server.handleRequest(input, undefined as any)
}
}
return new Proxy(fnHandler as any, {
get: (_, prop) => {
if (server[prop]) {
if (server[prop].bind) {
return server[prop].bind(server)
}
return server[prop]
} else if (fnHandler[prop]) {
if (fnHandler[prop].bind) {
return fnHandler[prop].bind(fnHandler)
}
return fnHandler[prop]
}
},
apply(_, __, [input]: Parameters<typeof fnHandler>) {
return fnHandler(input)
},
})
}