/
parseGraphQLRequest.ts
179 lines (152 loc) · 4.47 KB
/
parseGraphQLRequest.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
import type {
DocumentNode,
OperationDefinitionNode,
OperationTypeNode,
} from 'graphql'
import { parse } from 'graphql'
import { GraphQLVariables } from '../../handlers/GraphQLHandler'
import { getPublicUrlFromRequest } from '../request/getPublicUrlFromRequest'
import { MockedRequest } from '../request/MockedRequest'
import { devUtils } from './devUtils'
import { jsonParse } from './jsonParse'
interface GraphQLInput {
query: string | null
variables?: GraphQLVariables
}
export interface ParsedGraphQLQuery {
operationType: OperationTypeNode
operationName?: string
}
export type ParsedGraphQLRequest<
VariablesType extends GraphQLVariables = GraphQLVariables,
> =
| (ParsedGraphQLQuery & {
variables?: VariablesType
})
| undefined
export function parseDocumentNode(node: DocumentNode): ParsedGraphQLQuery {
const operationDef = node.definitions.find((def) => {
return def.kind === 'OperationDefinition'
}) as OperationDefinitionNode
return {
operationType: operationDef?.operation,
operationName: operationDef?.name?.value,
}
}
function parseQuery(query: string): ParsedGraphQLQuery | Error {
try {
const ast = parse(query)
return parseDocumentNode(ast)
} catch (error) {
return error as Error
}
}
export type GraphQLParsedOperationsMap = Record<string, string[]>
export type GraphQLMultipartRequestBody = {
operations: string
map?: string
} & {
[fileName: string]: File
}
function extractMultipartVariables<VariablesType extends GraphQLVariables>(
variables: VariablesType,
map: GraphQLParsedOperationsMap,
files: Record<string, File>,
) {
const operations = { variables }
for (const [key, pathArray] of Object.entries(map)) {
if (!(key in files)) {
throw new Error(`Given files do not have a key '${key}' .`)
}
for (const dotPath of pathArray) {
const [lastPath, ...reversedPaths] = dotPath.split('.').reverse()
const paths = reversedPaths.reverse()
let target: Record<string, any> = operations
for (const path of paths) {
if (!(path in target)) {
throw new Error(`Property '${paths}' is not in operations.`)
}
target = target[path]
}
target[lastPath] = files[key]
}
}
return operations.variables
}
function getGraphQLInput(request: MockedRequest<any>): GraphQLInput | null {
switch (request.method) {
case 'GET': {
const query = request.url.searchParams.get('query')
const variables = request.url.searchParams.get('variables') || ''
return {
query,
variables: jsonParse(variables),
}
}
case 'POST': {
if (request.body?.query) {
const { query, variables } = request.body
return {
query,
variables,
}
}
// Handle multipart body operations.
if (request.body?.operations) {
const { operations, map, ...files } =
request.body as GraphQLMultipartRequestBody
const parsedOperations =
jsonParse<{ query?: string; variables?: GraphQLVariables }>(
operations,
) || {}
if (!parsedOperations.query) {
return null
}
const parsedMap = jsonParse<GraphQLParsedOperationsMap>(map || '') || {}
const variables = parsedOperations.variables
? extractMultipartVariables(
parsedOperations.variables,
parsedMap,
files,
)
: {}
return {
query: parsedOperations.query,
variables,
}
}
}
default:
return null
}
}
/**
* Determines if a given request can be considered a GraphQL request.
* Does not parse the query and does not guarantee its validity.
*/
export function parseGraphQLRequest(
request: MockedRequest<any>,
): ParsedGraphQLRequest {
const input = getGraphQLInput(request)
if (!input || !input.query) {
return undefined
}
const { query, variables } = input
const parsedResult = parseQuery(query)
if (parsedResult instanceof Error) {
const requestPublicUrl = getPublicUrlFromRequest(request)
throw new Error(
devUtils.formatMessage(
'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
request.method,
requestPublicUrl,
parsedResult.message,
),
)
}
return {
operationType: parsedResult.operationType,
operationName: parsedResult.operationName,
variables,
}
}