graphql-upload 8.0.7 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ const Busboy = require('busboy');
4
+ const { WriteStream } = require('fs-capacitor');
5
+ const createError = require('http-errors');
6
+ const isObject = require('isobject');
7
+ const objectPath = require('object-path');
8
+ const { SPEC_URL } = require('../private/constants');
9
+ const ignoreStream = require('../private/ignoreStream');
10
+ const Upload = require('./Upload');
11
+
12
+ /**
13
+ * Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
14
+ * It parses the `operations` and `map` fields to create an
15
+ * [`Upload`]{@link Upload} instance for each expected file upload, placing
16
+ * references wherever the file is expected in the
17
+ * [GraphQL operation]{@link GraphQLOperation} for the
18
+ * [`Upload` scalar]{@link GraphQLUpload} to derive it’s value. Errors are
19
+ * created with [`http-errors`](https://npm.im/http-errors) to assist in
20
+ * sending responses with appropriate HTTP status codes. Used in
21
+ * [`graphqlUploadExpress`]{@link graphqlUploadExpress} and
22
+ * [`graphqlUploadKoa`]{@link graphqlUploadKoa} and can be used to create
23
+ * custom middleware.
24
+ * @kind function
25
+ * @name processRequest
26
+ * @type {ProcessRequestFunction}
27
+ * @example <caption>Ways to `import`.</caption>
28
+ * ```js
29
+ * import { processRequest } from 'graphql-upload';
30
+ * ```
31
+ *
32
+ * ```js
33
+ * import processRequest from 'graphql-upload/public/processRequest.js';
34
+ * ```
35
+ * @example <caption>Ways to `require`.</caption>
36
+ * ```js
37
+ * const { processRequest } = require('graphql-upload');
38
+ * ```
39
+ *
40
+ * ```js
41
+ * const processRequest = require('graphql-upload/public/processRequest');
42
+ * ```
43
+ */
44
+ module.exports = function processRequest(
45
+ request,
46
+ response,
47
+ {
48
+ maxFieldSize = 1000000, // 1 MB
49
+ maxFileSize = Infinity,
50
+ maxFiles = Infinity,
51
+ } = {}
52
+ ) {
53
+ return new Promise((resolve, reject) => {
54
+ let released;
55
+ let exitError;
56
+ let currentStream;
57
+ let operations;
58
+ let operationsPath;
59
+ let map;
60
+
61
+ const parser = new Busboy({
62
+ headers: request.headers,
63
+ limits: {
64
+ fieldSize: maxFieldSize,
65
+ fields: 2, // Only operations and map.
66
+ fileSize: maxFileSize,
67
+ files: maxFiles,
68
+ },
69
+ });
70
+
71
+ /**
72
+ * Exits request processing with an error. Successive calls have no effect.
73
+ * @kind function
74
+ * @name processRequest~exit
75
+ * @param {object} error Error instance.
76
+ * @ignore
77
+ */
78
+ const exit = (error) => {
79
+ if (exitError) return;
80
+ exitError = error;
81
+
82
+ reject(exitError);
83
+
84
+ parser.destroy();
85
+
86
+ if (currentStream) currentStream.destroy(exitError);
87
+
88
+ if (map)
89
+ for (const upload of map.values())
90
+ if (!upload.file) upload.reject(exitError);
91
+
92
+ request.unpipe(parser);
93
+
94
+ // With a sufficiently large request body, subsequent events in the same
95
+ // event frame cause the stream to pause after the parser is destroyed. To
96
+ // ensure that the request resumes, the call to .resume() is scheduled for
97
+ // later in the event loop.
98
+ setImmediate(() => {
99
+ request.resume();
100
+ });
101
+ };
102
+
103
+ /**
104
+ * Releases resources and cleans up Capacitor temporary files. Successive
105
+ * calls have no effect.
106
+ * @kind function
107
+ * @name processRequest~release
108
+ * @ignore
109
+ */
110
+ const release = () => {
111
+ if (released) return;
112
+ released = true;
113
+
114
+ if (map)
115
+ for (const upload of map.values())
116
+ if (upload.file) upload.file.capacitor.release();
117
+ };
118
+
119
+ /**
120
+ * Handles when the request is closed before it properly ended.
121
+ * @kind function
122
+ * @name processRequest~abort
123
+ * @ignore
124
+ */
125
+ const abort = () => {
126
+ exit(
127
+ createError(
128
+ 499,
129
+ 'Request disconnected during file upload stream parsing.'
130
+ )
131
+ );
132
+ };
133
+
134
+ parser.on(
135
+ 'field',
136
+ (fieldName, value, fieldNameTruncated, valueTruncated) => {
137
+ if (exitError) return;
138
+
139
+ if (valueTruncated)
140
+ return exit(
141
+ createError(
142
+ 413,
143
+ `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`
144
+ )
145
+ );
146
+
147
+ switch (fieldName) {
148
+ case 'operations':
149
+ try {
150
+ operations = JSON.parse(value);
151
+ } catch (error) {
152
+ return exit(
153
+ createError(
154
+ 400,
155
+ `Invalid JSON in the ‘operations’ multipart field (${SPEC_URL}).`
156
+ )
157
+ );
158
+ }
159
+
160
+ if (!isObject(operations) && !Array.isArray(operations))
161
+ return exit(
162
+ createError(
163
+ 400,
164
+ `Invalid type for the ‘operations’ multipart field (${SPEC_URL}).`
165
+ )
166
+ );
167
+
168
+ operationsPath = objectPath(operations);
169
+
170
+ break;
171
+ case 'map': {
172
+ if (!operations)
173
+ return exit(
174
+ createError(
175
+ 400,
176
+ `Misordered multipart fields; ‘map’ should follow ‘operations’ (${SPEC_URL}).`
177
+ )
178
+ );
179
+
180
+ let parsedMap;
181
+ try {
182
+ parsedMap = JSON.parse(value);
183
+ } catch (error) {
184
+ return exit(
185
+ createError(
186
+ 400,
187
+ `Invalid JSON in the ‘map’ multipart field (${SPEC_URL}).`
188
+ )
189
+ );
190
+ }
191
+
192
+ if (!isObject(parsedMap))
193
+ return exit(
194
+ createError(
195
+ 400,
196
+ `Invalid type for the ‘map’ multipart field (${SPEC_URL}).`
197
+ )
198
+ );
199
+
200
+ const mapEntries = Object.entries(parsedMap);
201
+
202
+ // Check max files is not exceeded, even though the number of files to
203
+ // parse might not match th(e map provided by the client.
204
+ if (mapEntries.length > maxFiles)
205
+ return exit(
206
+ createError(413, `${maxFiles} max file uploads exceeded.`)
207
+ );
208
+
209
+ map = new Map();
210
+ for (const [fieldName, paths] of mapEntries) {
211
+ if (!Array.isArray(paths))
212
+ return exit(
213
+ createError(
214
+ 400,
215
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${SPEC_URL}).`
216
+ )
217
+ );
218
+
219
+ map.set(fieldName, new Upload());
220
+
221
+ for (const [index, path] of paths.entries()) {
222
+ if (typeof path !== 'string')
223
+ return exit(
224
+ createError(
225
+ 400,
226
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${SPEC_URL}).`
227
+ )
228
+ );
229
+
230
+ try {
231
+ operationsPath.set(path, map.get(fieldName));
232
+ } catch (error) {
233
+ return exit(
234
+ createError(
235
+ 400,
236
+ `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${SPEC_URL}).`
237
+ )
238
+ );
239
+ }
240
+ }
241
+ }
242
+
243
+ resolve(operations);
244
+ }
245
+ }
246
+ }
247
+ );
248
+
249
+ parser.on('file', (fieldName, stream, filename, encoding, mimetype) => {
250
+ if (exitError) {
251
+ ignoreStream(stream);
252
+ return;
253
+ }
254
+
255
+ if (!map) {
256
+ ignoreStream(stream);
257
+ return exit(
258
+ createError(
259
+ 400,
260
+ `Misordered multipart fields; files should follow ‘map’ (${SPEC_URL}).`
261
+ )
262
+ );
263
+ }
264
+
265
+ currentStream = stream;
266
+ stream.on('end', () => {
267
+ currentStream = null;
268
+ });
269
+
270
+ const upload = map.get(fieldName);
271
+
272
+ if (!upload) {
273
+ // The file is extraneous. As the rest can still be processed, just
274
+ // ignore it and don’t exit with an error.
275
+ ignoreStream(stream);
276
+ return;
277
+ }
278
+
279
+ let fileError;
280
+ const capacitor = new WriteStream();
281
+
282
+ capacitor.on('error', () => {
283
+ stream.unpipe();
284
+ stream.resume();
285
+ });
286
+
287
+ stream.on('limit', () => {
288
+ fileError = createError(
289
+ 413,
290
+ `File truncated as it exceeds the ${maxFileSize} byte size limit.`
291
+ );
292
+ stream.unpipe();
293
+ capacitor.destroy(fileError);
294
+ });
295
+
296
+ stream.on('error', (error) => {
297
+ fileError = error;
298
+ stream.unpipe();
299
+ capacitor.destroy(exitError);
300
+ });
301
+
302
+ const file = {
303
+ filename,
304
+ mimetype,
305
+ encoding,
306
+ createReadStream(options) {
307
+ const error = fileError || (released ? exitError : null);
308
+ if (error) throw error;
309
+ return capacitor.createReadStream(options);
310
+ },
311
+ };
312
+
313
+ Object.defineProperty(file, 'capacitor', { value: capacitor });
314
+
315
+ stream.pipe(capacitor);
316
+ upload.resolve(file);
317
+ });
318
+
319
+ parser.once('filesLimit', () =>
320
+ exit(createError(413, `${maxFiles} max file uploads exceeded.`))
321
+ );
322
+
323
+ parser.once('finish', () => {
324
+ request.unpipe(parser);
325
+ request.resume();
326
+
327
+ if (!operations)
328
+ return exit(
329
+ createError(
330
+ 400,
331
+ `Missing multipart field ‘operations’ (${SPEC_URL}).`
332
+ )
333
+ );
334
+
335
+ if (!map)
336
+ return exit(
337
+ createError(400, `Missing multipart field ‘map’ (${SPEC_URL}).`)
338
+ );
339
+
340
+ for (const upload of map.values())
341
+ if (!upload.file)
342
+ upload.reject(createError(400, 'File missing in the request.'));
343
+ });
344
+
345
+ parser.once('error', exit);
346
+
347
+ response.once('finish', release);
348
+ response.once('close', release);
349
+
350
+ request.once('close', abort);
351
+ request.once('end', () => {
352
+ request.removeListener('close', abort);
353
+ });
354
+
355
+ request.pipe(parser);
356
+ });
357
+ };