/
processRequest.js
345 lines (296 loc) · 9.39 KB
/
processRequest.js
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
'use strict'
const Busboy = require('busboy')
const { WriteStream } = require('fs-capacitor')
const createError = require('http-errors')
const isObject = require('isobject')
const objectPath = require('object-path')
const Upload = require('./Upload')
const { SPEC_URL } = require('./constants')
const ignoreStream = require('./ignoreStream')
/**
* Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
* It parses the `operations` and `map` fields to create an
* [`Upload`]{@link Upload} instance for each expected file upload, placing
* references wherever the file is expected in the
* [GraphQL operation]{@link GraphQLOperation} for the
* [`Upload` scalar]{@link GraphQLUpload} to derive it’s value. Errors are
* created with [`http-errors`](https://npm.im/http-errors) to assist in
* sending responses with appropriate HTTP status codes. Used in
* [`graphqlUploadExpress`]{@link graphqlUploadExpress} and
* [`graphqlUploadKoa`]{@link graphqlUploadKoa} and can be used to create
* custom middleware.
* @kind function
* @name processRequest
* @type {ProcessRequestFunction}
* @example <caption>How to import.</caption>
* ```js
* const { processRequest } = require('graphql-upload')
* ```
*/
module.exports = function processRequest(
request,
response,
{
maxFieldSize = 1000000, // 1 MB
maxFileSize = Infinity,
maxFiles = Infinity
} = {}
) {
return new Promise((resolve, reject) => {
let released
let exitError
let currentStream
let operations
let operationsPath
let map
const parser = new Busboy({
headers: request.headers,
limits: {
fieldSize: maxFieldSize,
fields: 2, // Only operations and map.
fileSize: maxFileSize,
files: maxFiles
}
})
/**
* Exits request processing with an error. Successive calls have no effect.
* @kind function
* @name processRequest~exit
* @param {object} error Error instance.
* @ignore
*/
const exit = error => {
if (exitError) return
exitError = error
reject(exitError)
parser.destroy()
if (currentStream) currentStream.destroy(exitError)
if (map)
for (const upload of map.values())
if (!upload.file) upload.reject(exitError)
request.unpipe(parser)
// With a sufficiently large request body, subsequent events in the same
// event frame cause the stream to pause after the parser is destroyed. To
// ensure that the request resumes, the call to .resume() is scheduled for
// later in the event loop.
setImmediate(() => {
request.resume()
})
}
/**
* Releases resources and cleans up Capacitor temporary files. Successive
* calls have no effect.
* @kind function
* @name processRequest~release
* @ignore
*/
const release = () => {
if (released) return
released = true
if (map)
for (const upload of map.values())
if (upload.file) upload.file.capacitor.release()
}
/**
* Handles when the request is closed before it properly ended.
* @kind function
* @name processRequest~abort
* @ignore
*/
const abort = () => {
exit(
createError(
499,
'Request disconnected during file upload stream parsing.'
)
)
}
parser.on(
'field',
(fieldName, value, fieldNameTruncated, valueTruncated) => {
if (exitError) return
if (valueTruncated)
return exit(
createError(
413,
`The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`
)
)
switch (fieldName) {
case 'operations':
try {
operations = JSON.parse(value)
} catch (error) {
return exit(
createError(
400,
`Invalid JSON in the ‘operations’ multipart field (${SPEC_URL}).`
)
)
}
if (!isObject(operations) && !Array.isArray(operations))
return exit(
createError(
400,
`Invalid type for the ‘operations’ multipart field (${SPEC_URL}).`
)
)
operationsPath = objectPath(operations)
break
case 'map': {
if (!operations)
return exit(
createError(
400,
`Misordered multipart fields; ‘map’ should follow ‘operations’ (${SPEC_URL}).`
)
)
let parsedMap
try {
parsedMap = JSON.parse(value)
} catch (error) {
return exit(
createError(
400,
`Invalid JSON in the ‘map’ multipart field (${SPEC_URL}).`
)
)
}
if (!isObject(parsedMap))
return exit(
createError(
400,
`Invalid type for the ‘map’ multipart field (${SPEC_URL}).`
)
)
const mapEntries = Object.entries(parsedMap)
// Check max files is not exceeded, even though the number of files to
// parse might not match th(e map provided by the client.
if (mapEntries.length > maxFiles)
return exit(
createError(413, `${maxFiles} max file uploads exceeded.`)
)
map = new Map()
for (const [fieldName, paths] of mapEntries) {
if (!Array.isArray(paths))
return exit(
createError(
400,
`Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${SPEC_URL}).`
)
)
map.set(fieldName, new Upload())
for (const [index, path] of paths.entries()) {
if (typeof path !== 'string')
return exit(
createError(
400,
`Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${SPEC_URL}).`
)
)
try {
operationsPath.set(path, map.get(fieldName))
} catch (error) {
return exit(
createError(
400,
`Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${SPEC_URL}).`
)
)
}
}
}
resolve(operations)
}
}
}
)
parser.on('file', (fieldName, stream, filename, encoding, mimetype) => {
if (exitError) {
ignoreStream(stream)
return
}
if (!map) {
ignoreStream(stream)
return exit(
createError(
400,
`Misordered multipart fields; files should follow ‘map’ (${SPEC_URL}).`
)
)
}
currentStream = stream
stream.on('end', () => {
currentStream = null
})
const upload = map.get(fieldName)
if (!upload) {
// The file is extraneous. As the rest can still be processed, just
// ignore it and don’t exit with an error.
ignoreStream(stream)
return
}
let fileError
const capacitor = new WriteStream()
capacitor.on('error', () => {
stream.unpipe()
stream.resume()
})
stream.on('limit', () => {
fileError = createError(
413,
`File truncated as it exceeds the ${maxFileSize} byte size limit.`
)
stream.unpipe()
capacitor.destroy(fileError)
})
stream.on('error', error => {
fileError = error
stream.unpipe()
capacitor.destroy(exitError)
})
const file = {
filename,
mimetype,
encoding,
createReadStream() {
const error = fileError || (released ? exitError : null)
if (error) throw error
return capacitor.createReadStream()
}
}
Object.defineProperty(file, 'capacitor', { value: capacitor })
stream.pipe(capacitor)
upload.resolve(file)
})
parser.once('filesLimit', () =>
exit(createError(413, `${maxFiles} max file uploads exceeded.`))
)
parser.once('finish', () => {
request.unpipe(parser)
request.resume()
if (!operations)
return exit(
createError(
400,
`Missing multipart field ‘operations’ (${SPEC_URL}).`
)
)
if (!map)
return exit(
createError(400, `Missing multipart field ‘map’ (${SPEC_URL}).`)
)
for (const upload of map.values())
if (!upload.file)
upload.reject(createError(400, 'File missing in the request.'))
})
parser.once('error', exit)
response.once('finish', release)
response.once('close', release)
request.once('close', abort)
request.once('end', () => {
request.removeListener('close', abort)
})
request.pipe(parser)
})
}