forked from mswjs/msw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphQLHandler.ts
More file actions
441 lines (382 loc) · 13.1 KB
/
Copy pathGraphQLHandler.ts
File metadata and controls
441 lines (382 loc) · 13.1 KB
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
import { invariant } from 'outvariant'
import {
parse,
type DocumentNode,
type GraphQLError,
type OperationTypeNode,
} from 'graphql'
import {
RequestHandler,
type DefaultBodyType,
type RequestHandlerDefaultInfo,
type RequestHandlerExecutionResult,
type RequestHandlerOptions,
type ResponseResolver,
} from './RequestHandler'
import { getTimestamp } from '../utils/logging/getTimestamp'
import { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'
import { serializeRequest } from '../utils/logging/serializeRequest'
import { serializeResponse } from '../utils/logging/serializeResponse'
import {
type Match,
matchRequestUrl,
type Path,
} from '../utils/matching/matchRequestUrl'
import {
type ParsedGraphQLRequest,
type GraphQLMultipartRequestBody,
parseGraphQLRequest,
parseDocumentNode,
type ParsedGraphQLQuery,
} from '../utils/internal/parseGraphQLRequest'
import { toPublicUrl } from '../utils/request/toPublicUrl'
import { devUtils } from '../utils/internal/devUtils'
import { getAllRequestCookies } from '../utils/request/getRequestCookies'
import { type ResponseResolutionContext } from '../utils/executeHandlers'
import { kDefaultContentType, type StrictRequest } from '../HttpResponse'
import { getAllAcceptedMimeTypes } from '../utils/request/getAllAcceptedMimeTypes'
export interface DocumentTypeDecoration<
Result = { [key: string]: any },
Variables = { [key: string]: any },
> {
__apiType?: (variables: Variables) => Result
__resultType?: Result
__variablesType?: Variables
}
export type GraphQLOperationType = OperationTypeNode | 'all'
export type GraphQLHandlerNameSelector = DocumentNode | RegExp | string
export type GraphQLQuery = Record<string, any> | null
export type GraphQLVariables = Record<string, any>
export interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {
operationType: GraphQLOperationType
operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate
}
export type GraphQLRequestParsedResult = {
match: Match
cookies: Record<string, string>
} & (
| ParsedGraphQLRequest<GraphQLVariables>
/**
* An empty version of the ParsedGraphQLRequest
* which simplifies the return type of the resolver
* when the request is to a non-matching endpoint
*/
| {
operationType?: undefined
operationName?: undefined
query?: undefined
variables?: undefined
}
)
export type GraphQLResolverExtras<Variables extends GraphQLVariables> = {
query: string
operationName: string
variables: Variables
cookies: Record<string, string>
}
export type GraphQLRequestBody<VariablesType extends GraphQLVariables> =
| GraphQLJsonRequestBody<VariablesType>
| GraphQLMultipartRequestBody
| Record<string, any>
| undefined
export interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {
query: string
variables?: Variables
}
export type GraphQLResponseBody<BodyType extends DefaultBodyType> =
| {
data?: BodyType | null
errors?: readonly Partial<GraphQLError>[] | null
extensions?: Record<string, any>
}
| null
| undefined
export type GraphQLCustomPredicate = (args: {
request: Request
query: string
operationType: GraphQLOperationType
operationName: string
variables: GraphQLVariables
cookies: Record<string, string>
}) => GraphQLCustomPredicateResult | Promise<GraphQLCustomPredicateResult>
export type GraphQLCustomPredicateResult = boolean | { matches: boolean }
export type GraphQLPredicate<Query = any, Variables = any> =
| GraphQLHandlerNameSelector
| DocumentTypeDecoration<Query, Variables>
| GraphQLCustomPredicate
export function isDocumentNode(
value: DocumentNode | any,
): value is DocumentNode {
if (value == null) {
return false
}
return typeof value === 'object' && 'kind' in value && 'definitions' in value
}
function isDocumentTypeDecoration(
value: unknown,
): value is DocumentTypeDecoration<any, any> {
return value instanceof String
}
export class GraphQLHandler extends RequestHandler<
GraphQLHandlerInfo,
GraphQLRequestParsedResult,
GraphQLResolverExtras<any>
> {
private endpoint: Path
static parsedRequestCache = new WeakMap<
Request,
ParsedGraphQLRequest<GraphQLVariables>
>()
static #parseOperationName(
predicate: GraphQLPredicate,
operationType: GraphQLOperationType,
): GraphQLHandlerInfo['operationName'] {
const getOperationName = (node: ParsedGraphQLQuery): string => {
invariant(
node.operationType === operationType,
'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "%s" but got "%s").',
operationType,
node.operationType,
)
invariant(
node.operationName,
'Failed to create a GraphQL handler: provided a DocumentNode without operation name',
)
return node.operationName
}
if (isDocumentNode(predicate)) {
return getOperationName(parseDocumentNode(predicate))
}
if (isDocumentTypeDecoration(predicate)) {
const documentNode = parse(predicate.toString())
invariant(
isDocumentNode(documentNode),
'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',
predicate,
)
return getOperationName(parseDocumentNode(documentNode))
}
return predicate
}
constructor(
operationType: GraphQLOperationType,
predicate: GraphQLPredicate,
endpoint: Path,
resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,
options?: RequestHandlerOptions,
) {
const operationName = GraphQLHandler.#parseOperationName(
predicate,
operationType,
)
const displayOperationName =
typeof operationName === 'function' ? '[custom predicate]' : operationName
const header =
operationType === 'all'
? `${operationType} (origin: ${endpoint.toString()})`
: `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`
super({
info: {
header,
operationType,
operationName: GraphQLHandler.#parseOperationName(
predicate,
operationType,
),
},
resolver,
options,
})
this.endpoint = endpoint
}
/**
* Parses the request body, once per request, cached across all
* GraphQL handlers. This is done to avoid multiple parsing of the
* request body, which each requires a clone of the request.
*/
async parseGraphQLRequestOrGetFromCache(
request: Request,
): Promise<ParsedGraphQLRequest<GraphQLVariables>> {
if (!GraphQLHandler.parsedRequestCache.has(request)) {
GraphQLHandler.parsedRequestCache.set(
request,
await parseGraphQLRequest(request).catch((error) => {
console.error(error)
return undefined
}),
)
}
return GraphQLHandler.parsedRequestCache.get(request)
}
async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {
/**
* If the request doesn't match a specified endpoint, there's no
* need to parse it since there's no case where we would handle this
*/
const match = matchRequestUrl(new URL(args.request.url), this.endpoint)
const cookies = getAllRequestCookies(args.request)
if (!match.matches) {
return {
match,
cookies,
}
}
const parsedResult = await this.parseGraphQLRequestOrGetFromCache(
args.request,
)
if (typeof parsedResult === 'undefined') {
return {
match,
cookies,
}
}
return {
match,
cookies,
query: parsedResult.query,
operationType: parsedResult.operationType,
operationName: parsedResult.operationName,
variables: parsedResult.variables,
}
}
async predicate(args: {
request: Request
parsedResult: GraphQLRequestParsedResult
}): Promise<boolean> {
if (args.parsedResult.operationType === undefined) {
return false
}
if (!args.parsedResult.operationName && this.info.operationType !== 'all') {
const publicUrl = toPublicUrl(args.request.url)
devUtils.warn(`\
Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)
return false
}
const hasMatchingOperationType =
this.info.operationType === 'all' ||
args.parsedResult.operationType === this.info.operationType
/**
* Check if the operation name matches the outgoing GraphQL request.
* @note Unlike the HTTP handler, the custom predicate functions are invoked
* during predicate, not parsing, because GraphQL request parsing happens first,
* and non-GraphQL requests are filtered out automatically.
*/
const hasMatchingOperationName = await this.matchOperationName({
request: args.request,
parsedResult: args.parsedResult,
})
return (
args.parsedResult.match.matches &&
hasMatchingOperationType &&
hasMatchingOperationName
)
}
public async run(args: {
request: StrictRequest<any>
requestId: string
resolutionContext?: ResponseResolutionContext
}): Promise<RequestHandlerExecutionResult<GraphQLRequestParsedResult> | null> {
const result = await super.run(args)
if (result?.response == null) {
return result
}
if (!(kDefaultContentType in result.response)) {
return result
}
const acceptedMimeTypes = getAllAcceptedMimeTypes(
args.request.headers.get('accept'),
)
if (acceptedMimeTypes.length === 0) {
return result
}
const graphqlResponseIndex = acceptedMimeTypes.indexOf(
'application/graphql-response+json',
)
const jsonIndex = acceptedMimeTypes.indexOf('application/json')
/**
* Use the "application/graphql-response+json" response content type
* only when the client accepts it AND prefers it over "application/json"
* (i.e. it appears earlier in the precedence-sorted list, or "application/json"
* is not listed at all).
* @see https://github.com/graphql/graphql-over-http/blob/4d1df1fb829ec2dd3ecbf3c6aa4025bd356c270d/spec/GraphQLOverHTTP.md#accept
*/
if (
graphqlResponseIndex !== -1 &&
(jsonIndex === -1 || graphqlResponseIndex <= jsonIndex)
) {
result.response.headers.set(
'content-type',
'application/graphql-response+json',
)
}
return result
}
private async matchOperationName(args: {
request: Request
parsedResult: GraphQLRequestParsedResult
}): Promise<boolean> {
if (typeof this.info.operationName === 'function') {
const customPredicateResult = await this.info.operationName({
request: args.request,
...this.extendResolverArgs({
request: args.request,
parsedResult: args.parsedResult,
}),
})
/**
* @note Keep the { matches } signature in case we decide to support path parameters
* in GraphQL handlers. If that happens, the custom predicate would have to be moved
* to the parsing phase, the same as we have for the HttpHandler, and the user will
* have a possibility to return parsed path parameters from the custom predicate.
*/
return typeof customPredicateResult === 'boolean'
? customPredicateResult
: customPredicateResult.matches
}
if (this.info.operationName instanceof RegExp) {
return this.info.operationName.test(args.parsedResult.operationName || '')
}
return args.parsedResult.operationName === this.info.operationName
}
protected extendResolverArgs(args: {
request: Request
parsedResult: GraphQLRequestParsedResult
}) {
return {
query: args.parsedResult.query || '',
operationType: args.parsedResult.operationType!,
operationName: args.parsedResult.operationName || '',
variables: args.parsedResult.variables || {},
cookies: args.parsedResult.cookies,
}
}
async log(args: {
request: Request
response: Response
parsedResult: GraphQLRequestParsedResult
}) {
const loggedRequest = await serializeRequest(args.request)
const loggedResponse = await serializeResponse(args.response)
const statusColor = getStatusCodeColor(loggedResponse.status)
const requestInfo = args.parsedResult.operationName
? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`
: `anonymous ${args.parsedResult.operationType}`
console.groupCollapsed(
devUtils.formatMessage(
`${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${
loggedResponse.statusText
}%c)`,
),
`color:${statusColor}`,
'color:inherit',
)
// eslint-disable-next-line no-console
console.log('Request:', loggedRequest)
// eslint-disable-next-line no-console
console.log('Handler:', this)
// eslint-disable-next-line no-console
console.log('Response:', loggedResponse)
console.groupEnd()
}
}