forked from kentcdodds/msw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql.ts
196 lines (167 loc) · 5.3 KB
/
graphql.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
import { OperationTypeNode, OperationDefinitionNode, parse } from 'graphql'
import { RequestHandler, MockedRequest } from './handlers/requestHandler'
import { MockedResponse, ResponseComposition } from './response'
import { set } from './context/set'
import { status } from './context/status'
import { delay } from './context/delay'
import { fetch } from './context/fetch'
import { data, DataContext } from './context/data'
import { errors } from './context/errors'
/* Logging */
import { prepareRequest } from './utils/logger/prepareRequest'
import { prepareResponse } from './utils/logger/prepareResponse'
import { getTimestamp } from './utils/logger/getTimestamp'
import { getStatusCodeColor } from './utils/logger/getStatusCodeColor'
import { jsonParse } from './utils/jsonParse'
type GraphQLRequestHandlerSelector = RegExp | string
export type GraphQLMockedRequest<
VariablesType = Record<string, any>
> = MockedRequest & {
variables: VariablesType
}
// GraphQL related context should contain utility functions
// useful for GraphQL. Functions like `xml()` bear no value
// in the GraphQL universe.
export interface GraphQLMockedContext<QueryType> {
set: typeof set
status: typeof status
delay: typeof delay
fetch: typeof fetch
data: DataContext<QueryType>
errors: typeof errors
}
export const graphqlContext: GraphQLMockedContext<any> = {
set,
status,
delay,
fetch,
data,
errors,
}
export type GraphQLResponseResolver<QueryType, VariablesType> = (
req: GraphQLMockedRequest<VariablesType>,
res: ResponseComposition,
context: GraphQLMockedContext<QueryType>,
) => MockedResponse
export interface GraphQLRequestPayload<VariablesType> {
query: string
variables?: VariablesType
}
interface GraphQLRequestParsedResult<VariablesType> {
operationType: OperationTypeNode
operationName: string | undefined
variables: VariablesType | undefined
}
interface ParsedQueryPayload {
operationName: string | undefined
}
export function parseQuery(
query: string,
definitionOperation: OperationTypeNode = 'query',
): ParsedQueryPayload {
const ast = parse(query)
const operationDef = ast.definitions.find(
(def) =>
def.kind === 'OperationDefinition' &&
def.operation === definitionOperation,
) as OperationDefinitionNode
return {
operationName: operationDef?.name?.value,
}
}
const createGraphQLHandler = (operationType: OperationTypeNode) => {
return <QueryType, VariablesType = Record<string, any>>(
expectedOperation: GraphQLRequestHandlerSelector,
resolver: GraphQLResponseResolver<QueryType, VariablesType>,
): RequestHandler<
GraphQLMockedRequest<VariablesType>,
GraphQLMockedContext<QueryType>,
GraphQLRequestParsedResult<VariablesType>
> => {
return {
resolver,
parse(req) {
// According to the GraphQL specification, a GraphQL request can be issued
// using both "GET" and "POST" methods.
switch (req.method) {
case 'GET': {
const query = req.url.searchParams.get('query')
const variablesString = req.url.searchParams.get('variables') || ''
if (!query) {
return null
}
const variables = variablesString
? jsonParse<VariablesType>(variablesString)
: ({} as VariablesType)
const { operationName } = parseQuery(query, operationType)
return {
operationType,
operationName,
variables,
}
}
case 'POST': {
if (!req.body) {
return null
}
const { query, variables } = req.body as GraphQLRequestPayload<
VariablesType
>
const { operationName } = parseQuery(query, operationType)
return {
operationType,
operationName,
variables,
}
}
default:
return null
}
},
getPublicRequest(req, parsed) {
return {
...req,
variables: parsed.variables || ({} as VariablesType),
}
},
predicate(req, parsed) {
if (!parsed || !parsed.operationName) {
return false
}
const isMatchingOperation =
expectedOperation instanceof RegExp
? expectedOperation.test(parsed.operationName)
: expectedOperation === parsed.operationName
return isMatchingOperation
},
defineContext() {
return graphqlContext
},
log(req, res, handler, parsed) {
const { operationName } = parsed
const loggedRequest = prepareRequest(req)
const loggedResponse = prepareResponse(res)
console.groupCollapsed(
'[MSW] %s %s (%c%s%c)',
getTimestamp(),
operationName,
`color:${getStatusCodeColor(res.status)}`,
res.status,
'color:inherit',
)
console.log('Request:', loggedRequest)
console.log('Handler:', {
operationType,
operationName: expectedOperation,
predicate: handler.predicate,
})
console.log('Response:', loggedResponse)
console.groupEnd()
},
}
}
}
export const graphql = {
query: createGraphQLHandler('query'),
mutation: createGraphQLHandler('mutation'),
}