-
-
Notifications
You must be signed in to change notification settings - Fork 474
/
GraphQLHandler.ts
238 lines (204 loc) · 7.14 KB
/
GraphQLHandler.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
import type { DocumentNode, GraphQLError, OperationTypeNode } from 'graphql'
import {
DefaultBodyType,
RequestHandler,
RequestHandlerDefaultInfo,
RequestHandlerOptions,
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 { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'
import {
ParsedGraphQLRequest,
GraphQLMultipartRequestBody,
parseGraphQLRequest,
parseDocumentNode,
} from '../utils/internal/parseGraphQLRequest'
import { getPublicUrlFromRequest } from '../utils/request/getPublicUrlFromRequest'
import { devUtils } from '../utils/internal/devUtils'
import { getAllRequestCookies } from '../utils/request/getRequestCookies'
export type ExpectedOperationTypeNode = OperationTypeNode | 'all'
export type GraphQLHandlerNameSelector = DocumentNode | RegExp | string
export type GraphQLVariables = Record<string, any>
export interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {
operationType: ExpectedOperationTypeNode
operationName: GraphQLHandlerNameSelector
}
export type GraphQLRequestParsedResult = {
match: Match
} & (
| 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 interface GraphQLResponseBody<BodyType extends DefaultBodyType> {
data?: BodyType | null
errors?: readonly Partial<GraphQLError>[] | null
}
export function isDocumentNode(
value: DocumentNode | any,
): value is DocumentNode {
if (value == null) {
return false
}
return typeof value === 'object' && 'kind' in value && 'definitions' in value
}
export class GraphQLHandler extends RequestHandler<
GraphQLHandlerInfo,
GraphQLRequestParsedResult,
GraphQLResolverExtras<any>
> {
private endpoint: Path
constructor(
operationType: ExpectedOperationTypeNode,
operationName: GraphQLHandlerNameSelector,
endpoint: Path,
resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,
options?: RequestHandlerOptions,
) {
let resolvedOperationName = operationName
if (isDocumentNode(operationName)) {
const parsedNode = parseDocumentNode(operationName)
if (parsedNode.operationType !== operationType) {
throw new Error(
`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`,
)
}
if (!parsedNode.operationName) {
throw new Error(
`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`,
)
}
resolvedOperationName = parsedNode.operationName
}
const header =
operationType === 'all'
? `${operationType} (origin: ${endpoint.toString()})`
: `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`
super({
info: {
header,
operationType,
operationName: resolvedOperationName,
},
resolver,
options,
})
this.endpoint = endpoint
}
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)
if (!match.matches) return { match }
const parsedResult = await parseGraphQLRequest(args.request).catch(
(error) => {
console.error(error)
return undefined
},
)
if (typeof parsedResult === 'undefined') {
return { match }
}
return {
match,
query: parsedResult.query,
operationType: parsedResult.operationType,
operationName: parsedResult.operationName,
variables: parsedResult.variables,
}
}
predicate(args: {
request: Request
parsedResult: GraphQLRequestParsedResult
}) {
if (args.parsedResult.operationType === undefined) {
return false
}
if (!args.parsedResult.operationName && this.info.operationType !== 'all') {
const publicUrl = getPublicUrlFromRequest(args.request)
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
const hasMatchingOperationName =
this.info.operationName instanceof RegExp
? this.info.operationName.test(args.parsedResult.operationName || '')
: args.parsedResult.operationName === this.info.operationName
return (
args.parsedResult.match.matches &&
hasMatchingOperationType &&
hasMatchingOperationName
)
}
protected extendResolverArgs(args: {
request: Request
parsedResult: GraphQLRequestParsedResult
}) {
const cookies = getAllRequestCookies(args.request)
return {
query: args.parsedResult.query || '',
operationName: args.parsedResult.operationName || '',
variables: args.parsedResult.variables || {},
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',
)
console.log('Request:', loggedRequest)
console.log('Handler:', this)
console.log('Response:', loggedResponse)
console.groupEnd()
}
}