graphql-upload 12.0.0 → 15.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.
@@ -1,76 +0,0 @@
1
- 'use strict';
2
-
3
- const defaultProcessRequest = require('./processRequest');
4
-
5
- /**
6
- * Creates [Express](https://expressjs.com) middleware that processes
7
- * [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec)
8
- * using [`processRequest`]{@link processRequest}, ignoring non-multipart
9
- * requests. It sets the request body to be
10
- * [similar to a conventional GraphQL POST request]{@link GraphQLOperation} for
11
- * following GraphQL middleware to consume.
12
- * @kind function
13
- * @name graphqlUploadExpress
14
- * @param {ProcessRequestOptions} options Middleware options. Any [`ProcessRequestOptions`]{@link ProcessRequestOptions} can be used.
15
- * @param {ProcessRequestFunction} [options.processRequest=processRequest] Used to process [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec).
16
- * @returns {Function} Express middleware.
17
- * @example <caption>Ways to `import`.</caption>
18
- * ```js
19
- * import { graphqlUploadExpress } from 'graphql-upload';
20
- * ```
21
- *
22
- * ```js
23
- * import graphqlUploadExpress from 'graphql-upload/public/graphqlUploadExpress.js';
24
- * ```
25
- * @example <caption>Ways to `require`.</caption>
26
- * ```js
27
- * const { graphqlUploadExpress } = require('graphql-upload');
28
- * ```
29
- *
30
- * ```js
31
- * const graphqlUploadExpress = require('graphql-upload/public/graphqlUploadExpress.js');
32
- * ```
33
- * @example <caption>Basic [`express-graphql`](https://npm.im/express-graphql) setup.</caption>
34
- * ```js
35
- * const express = require('express');
36
- * const graphqlHTTP = require('express-graphql');
37
- * const { graphqlUploadExpress } = require('graphql-upload');
38
- * const schema = require('./schema');
39
- *
40
- * express()
41
- * .use(
42
- * '/graphql',
43
- * graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
44
- * graphqlHTTP({ schema })
45
- * )
46
- * .listen(3000);
47
- * ```
48
- */
49
- module.exports = function graphqlUploadExpress({
50
- processRequest = defaultProcessRequest,
51
- ...processRequestOptions
52
- } = {}) {
53
- return function graphqlUploadExpressMiddleware(request, response, next) {
54
- if (!request.is('multipart/form-data')) return next();
55
-
56
- const finished = new Promise((resolve) => request.on('end', resolve));
57
- const { send } = response;
58
-
59
- response.send = (...args) => {
60
- finished.then(() => {
61
- response.send = send;
62
- response.send(...args);
63
- });
64
- };
65
-
66
- processRequest(request, response, processRequestOptions)
67
- .then((body) => {
68
- request.body = body;
69
- next();
70
- })
71
- .catch((error) => {
72
- if (error.status && error.expose) response.status(error.status);
73
- next(error);
74
- });
75
- };
76
- };
@@ -1,69 +0,0 @@
1
- 'use strict';
2
-
3
- const defaultProcessRequest = require('./processRequest');
4
-
5
- /**
6
- * Creates [Koa](https://koajs.com) middleware that processes
7
- * [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec)
8
- * using [`processRequest`]{@link processRequest}, ignoring non-multipart
9
- * requests. It sets the request body to be
10
- * [similar to a conventional GraphQL POST request]{@link GraphQLOperation} for
11
- * following GraphQL middleware to consume.
12
- * @kind function
13
- * @name graphqlUploadKoa
14
- * @param {ProcessRequestOptions} options Middleware options. Any [`ProcessRequestOptions`]{@link ProcessRequestOptions} can be used.
15
- * @param {ProcessRequestFunction} [options.processRequest=processRequest] Used to process [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec).
16
- * @returns {Function} Koa middleware.
17
- * @example <caption>Ways to `import`.</caption>
18
- * ```js
19
- * import { graphqlUploadKoa } from 'graphql-upload';
20
- * ```
21
- *
22
- * ```js
23
- * import graphqlUploadKoa from 'graphql-upload/public/graphqlUploadKoa.js';
24
- * ```
25
- * @example <caption>Ways to `require`.</caption>
26
- * ```js
27
- * const { graphqlUploadKoa } = require('graphql-upload');
28
- * ```
29
- *
30
- * ```js
31
- * const graphqlUploadKoa = require('graphql-upload/public/graphqlUploadKoa.js');
32
- * ```
33
- * @example <caption>Basic [`graphql-api-koa`](https://npm.im/graphql-api-koa) setup.</caption>
34
- * ```js
35
- * const Koa = require('koa');
36
- * const bodyParser = require('koa-bodyparser');
37
- * const { errorHandler, execute } = require('graphql-api-koa');
38
- * const { graphqlUploadKoa } = require('graphql-upload');
39
- * const schema = require('./schema');
40
- *
41
- * new Koa()
42
- * .use(errorHandler())
43
- * .use(bodyParser())
44
- * .use(graphqlUploadKoa({ maxFileSize: 10000000, maxFiles: 10 }))
45
- * .use(execute({ schema }))
46
- * .listen(3000);
47
- * ```
48
- */
49
- module.exports = function graphqlUploadKoa({
50
- processRequest = defaultProcessRequest,
51
- ...processRequestOptions
52
- } = {}) {
53
- return async function graphqlUploadKoaMiddleware(ctx, next) {
54
- if (!ctx.request.is('multipart/form-data')) return next();
55
-
56
- const finished = new Promise((resolve) => ctx.req.on('end', resolve));
57
-
58
- try {
59
- ctx.request.body = await processRequest(
60
- ctx.req,
61
- ctx.res,
62
- processRequestOptions
63
- );
64
- await next();
65
- } finally {
66
- await finished;
67
- }
68
- };
69
- };
package/public/index.js DELETED
@@ -1,75 +0,0 @@
1
- 'use strict';
2
-
3
- exports.GraphQLUpload = require('./GraphQLUpload');
4
- exports.processRequest = require('./processRequest');
5
- exports.graphqlUploadKoa = require('./graphqlUploadKoa');
6
- exports.graphqlUploadExpress = require('./graphqlUploadExpress');
7
- exports.Upload = require('./Upload');
8
-
9
- /**
10
- * File upload details that are only available after the file’s field in the
11
- * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec)
12
- * has begun streaming in.
13
- * @kind typedef
14
- * @name FileUpload
15
- * @type {object}
16
- * @prop {string} filename File name.
17
- * @prop {string} mimetype File MIME type. Provided by the client and can’t be trusted.
18
- * @prop {string} encoding File stream transfer encoding.
19
- * @prop {FileUploadCreateReadStream} createReadStream Creates a [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the file’s contents, for processing and storage.
20
- */
21
-
22
- /**
23
- * Creates a
24
- * [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams)
25
- * of an [uploading file’s]{@link FileUpload} contents, for processing and
26
- * storage. Multiple calls create independent streams. Throws if called after
27
- * all resolvers have resolved, or after an error has interrupted the request.
28
- * @kind typedef
29
- * @name FileUploadCreateReadStream
30
- * @type {Function}
31
- * @param {object} [options] [`fs-capacitor`](https://npm.im/fs-capacitor) [`ReadStreamOptions`](https://github.com/mike-marcacci/fs-capacitor#readstreamoptions).
32
- * @param {string} [options.encoding=null] Specify an encoding for the [`data`](https://nodejs.org/api/stream.html#stream_event_data) chunks to be strings (without splitting multi-byte characters across chunks) instead of Node.js [`Buffer`](https://nodejs.org/api/buffer.html#buffer_buffer) instances. Supported values depend on the [`Buffer` implementation](https://github.com/nodejs/node/blob/v13.7.0/lib/buffer.js#L587-L663) and include `utf8`, `ucs2`, `utf16le`, `latin1`, `ascii`, `base64`, or `hex`.
33
- * @param {number} [options.highWaterMark=16384] Maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
34
- * @returns {Readable} [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the file’s contents.
35
- * @see [Node.js `Readable` stream constructor docs](https://nodejs.org/api/stream.html#stream_new_stream_readable_options).
36
- * @see [Node.js stream backpressure guide](https://nodejs.org/en/docs/guides/backpressuring-in-streams).
37
- */
38
-
39
- /**
40
- * A GraphQL operation object in a shape that can be consumed and executed by
41
- * most GraphQL servers.
42
- * @kind typedef
43
- * @name GraphQLOperation
44
- * @type {object}
45
- * @prop {string} query GraphQL document containing queries and fragments.
46
- * @prop {string|null} [operationName] GraphQL document operation name to execute.
47
- * @prop {object|null} [variables] GraphQL document operation variables and values map.
48
- * @see [GraphQL over HTTP spec](https://github.com/graphql/graphql-over-http).
49
- * @see [Apollo Server POST requests](https://www.apollographql.com/docs/apollo-server/requests/#post-requests).
50
- */
51
-
52
- /**
53
- * Processes a
54
- * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
55
- * @kind typedef
56
- * @name ProcessRequestFunction
57
- * @type {Function}
58
- * @param {IncomingMessage} request [Node.js HTTP server request instance](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
59
- * @param {ServerResponse} response [Node.js HTTP server response instance](https://nodejs.org/api/http.html#http_class_http_serverresponse).
60
- * @param {ProcessRequestOptions} [options] Options for processing the request.
61
- * @returns {Promise<GraphQLOperation | Array<GraphQLOperation>>} GraphQL operation or batch of operations for a GraphQL server to consume (usually as the request body).
62
- * @see [`processRequest`]{@link processRequest}.
63
- */
64
-
65
- /**
66
- * Options for processing a
67
- * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec);
68
- * mostly relating to security, performance and limits.
69
- * @kind typedef
70
- * @name ProcessRequestOptions
71
- * @type {object}
72
- * @prop {number} [maxFieldSize=1000000] Maximum allowed non-file multipart form field size in bytes; enough for your queries.
73
- * @prop {number} [maxFileSize=Infinity] Maximum allowed file size in bytes.
74
- * @prop {number} [maxFiles=Infinity] Maximum allowed number of files.
75
- */
package/public/index.mjs DELETED
@@ -1,5 +0,0 @@
1
- export { default as GraphQLUpload } from './GraphQLUpload.js';
2
- export { default as processRequest } from './processRequest.js';
3
- export { default as graphqlUploadKoa } from './graphqlUploadKoa.js';
4
- export { default as graphqlUploadExpress } from './graphqlUploadExpress.js';
5
- export { default as Upload } from './Upload.js';
@@ -1,361 +0,0 @@
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 GRAPHQL_MULTIPART_REQUEST_SPEC_URL = require('../private/GRAPHQL_MULTIPART_REQUEST_SPEC_URL');
9
- const ignoreStream = require('../private/ignoreStream');
10
- const Upload = require('./Upload');
11
-
12
- /**
13
- * Processes a
14
- * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
15
- * It parses the `operations` and `map` fields to create an
16
- * [`Upload`]{@link Upload} instance for each expected file upload, placing
17
- * references wherever the file is expected in the
18
- * [GraphQL operation]{@link GraphQLOperation} for the
19
- * [`Upload`]{@link GraphQLUpload} scalar to derive it’s value. Errors are
20
- * created with [`http-errors`](https://npm.im/http-errors) to assist in sending
21
- * responses with appropriate HTTP status codes. Used in
22
- * [`graphqlUploadExpress`]{@link graphqlUploadExpress} and
23
- * [`graphqlUploadKoa`]{@link graphqlUploadKoa} and can be used to create custom
24
- * middleware.
25
- * @kind function
26
- * @name processRequest
27
- * @type {ProcessRequestFunction}
28
- * @example <caption>Ways to `import`.</caption>
29
- * ```js
30
- * import { processRequest } from 'graphql-upload';
31
- * ```
32
- *
33
- * ```js
34
- * import processRequest from 'graphql-upload/public/processRequest.js';
35
- * ```
36
- * @example <caption>Ways to `require`.</caption>
37
- * ```js
38
- * const { processRequest } = require('graphql-upload');
39
- * ```
40
- *
41
- * ```js
42
- * const processRequest = require('graphql-upload/public/processRequest.js');
43
- * ```
44
- */
45
- module.exports = function processRequest(
46
- request,
47
- response,
48
- {
49
- maxFieldSize = 1000000, // 1 MB
50
- maxFileSize = Infinity,
51
- maxFiles = Infinity,
52
- } = {}
53
- ) {
54
- return new Promise((resolve, reject) => {
55
- let released;
56
- let exitError;
57
- let currentStream;
58
- let operations;
59
- let operationsPath;
60
- let map;
61
-
62
- const parser = new Busboy({
63
- headers: request.headers,
64
- limits: {
65
- fieldSize: maxFieldSize,
66
- fields: 2, // Only operations and map.
67
- fileSize: maxFileSize,
68
- files: maxFiles,
69
- },
70
- });
71
-
72
- /**
73
- * Exits request processing with an error. Successive calls have no effect.
74
- * @kind function
75
- * @name processRequest~exit
76
- * @param {object} error Error instance.
77
- * @ignore
78
- */
79
- const exit = (error) => {
80
- if (exitError) return;
81
- exitError = error;
82
-
83
- reject(exitError);
84
-
85
- parser.destroy();
86
-
87
- if (currentStream) currentStream.destroy(exitError);
88
-
89
- if (map)
90
- for (const upload of map.values())
91
- if (!upload.file) upload.reject(exitError);
92
-
93
- request.unpipe(parser);
94
-
95
- // With a sufficiently large request body, subsequent events in the same
96
- // event frame cause the stream to pause after the parser is destroyed. To
97
- // ensure that the request resumes, the call to .resume() is scheduled for
98
- // later in the event loop.
99
- setImmediate(() => {
100
- request.resume();
101
- });
102
- };
103
-
104
- /**
105
- * Releases resources and cleans up Capacitor temporary files. Successive
106
- * calls have no effect.
107
- * @kind function
108
- * @name processRequest~release
109
- * @ignore
110
- */
111
- const release = () => {
112
- if (released) return;
113
- released = true;
114
-
115
- if (map)
116
- for (const upload of map.values())
117
- if (upload.file) upload.file.capacitor.release();
118
- };
119
-
120
- /**
121
- * Handles when the request is closed before it properly ended.
122
- * @kind function
123
- * @name processRequest~abort
124
- * @ignore
125
- */
126
- const abort = () => {
127
- exit(
128
- createError(
129
- 499,
130
- 'Request disconnected during file upload stream parsing.'
131
- )
132
- );
133
- };
134
-
135
- parser.on(
136
- 'field',
137
- (fieldName, value, fieldNameTruncated, valueTruncated) => {
138
- if (exitError) return;
139
-
140
- if (valueTruncated)
141
- return exit(
142
- createError(
143
- 413,
144
- `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`
145
- )
146
- );
147
-
148
- switch (fieldName) {
149
- case 'operations':
150
- try {
151
- operations = JSON.parse(value);
152
- } catch (error) {
153
- return exit(
154
- createError(
155
- 400,
156
- `Invalid JSON in the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
157
- )
158
- );
159
- }
160
-
161
- if (!isObject(operations) && !Array.isArray(operations))
162
- return exit(
163
- createError(
164
- 400,
165
- `Invalid type for the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
166
- )
167
- );
168
-
169
- operationsPath = objectPath(operations);
170
-
171
- break;
172
- case 'map': {
173
- if (!operations)
174
- return exit(
175
- createError(
176
- 400,
177
- `Misordered multipart fields; ‘map’ should follow ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
178
- )
179
- );
180
-
181
- let parsedMap;
182
- try {
183
- parsedMap = JSON.parse(value);
184
- } catch (error) {
185
- return exit(
186
- createError(
187
- 400,
188
- `Invalid JSON in the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
189
- )
190
- );
191
- }
192
-
193
- if (!isObject(parsedMap))
194
- return exit(
195
- createError(
196
- 400,
197
- `Invalid type for the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
198
- )
199
- );
200
-
201
- const mapEntries = Object.entries(parsedMap);
202
-
203
- // Check max files is not exceeded, even though the number of files
204
- // to parse might not match the map provided by the client.
205
- if (mapEntries.length > maxFiles)
206
- return exit(
207
- createError(413, `${maxFiles} max file uploads exceeded.`)
208
- );
209
-
210
- map = new Map();
211
- for (const [fieldName, paths] of mapEntries) {
212
- if (!Array.isArray(paths))
213
- return exit(
214
- createError(
215
- 400,
216
- `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
217
- )
218
- );
219
-
220
- map.set(fieldName, new Upload());
221
-
222
- for (const [index, path] of paths.entries()) {
223
- if (typeof path !== 'string')
224
- return exit(
225
- createError(
226
- 400,
227
- `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
228
- )
229
- );
230
-
231
- try {
232
- operationsPath.set(path, map.get(fieldName));
233
- } catch (error) {
234
- return exit(
235
- createError(
236
- 400,
237
- `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
238
- )
239
- );
240
- }
241
- }
242
- }
243
-
244
- resolve(operations);
245
- }
246
- }
247
- }
248
- );
249
-
250
- parser.on('file', (fieldName, stream, filename, encoding, mimetype) => {
251
- if (exitError) {
252
- ignoreStream(stream);
253
- return;
254
- }
255
-
256
- if (!map) {
257
- ignoreStream(stream);
258
- return exit(
259
- createError(
260
- 400,
261
- `Misordered multipart fields; files should follow ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
262
- )
263
- );
264
- }
265
-
266
- currentStream = stream;
267
- stream.on('end', () => {
268
- currentStream = null;
269
- });
270
-
271
- const upload = map.get(fieldName);
272
-
273
- if (!upload) {
274
- // The file is extraneous. As the rest can still be processed, just
275
- // ignore it and don’t exit with an error.
276
- ignoreStream(stream);
277
- return;
278
- }
279
-
280
- let fileError;
281
- const capacitor = new WriteStream();
282
-
283
- capacitor.on('error', () => {
284
- stream.unpipe();
285
- stream.resume();
286
- });
287
-
288
- stream.on('limit', () => {
289
- fileError = createError(
290
- 413,
291
- `File truncated as it exceeds the ${maxFileSize} byte size limit.`
292
- );
293
- stream.unpipe();
294
- capacitor.destroy(fileError);
295
- });
296
-
297
- stream.on('error', (error) => {
298
- fileError = error;
299
- stream.unpipe();
300
- capacitor.destroy(exitError);
301
- });
302
-
303
- const file = {
304
- filename,
305
- mimetype,
306
- encoding,
307
- createReadStream(options) {
308
- const error = fileError || (released ? exitError : null);
309
- if (error) throw error;
310
- return capacitor.createReadStream(options);
311
- },
312
- };
313
-
314
- Object.defineProperty(file, 'capacitor', { value: capacitor });
315
-
316
- stream.pipe(capacitor);
317
- upload.resolve(file);
318
- });
319
-
320
- parser.once('filesLimit', () =>
321
- exit(createError(413, `${maxFiles} max file uploads exceeded.`))
322
- );
323
-
324
- parser.once('finish', () => {
325
- request.unpipe(parser);
326
- request.resume();
327
-
328
- if (!operations)
329
- return exit(
330
- createError(
331
- 400,
332
- `Missing multipart field ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
333
- )
334
- );
335
-
336
- if (!map)
337
- return exit(
338
- createError(
339
- 400,
340
- `Missing multipart field ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
341
- )
342
- );
343
-
344
- for (const upload of map.values())
345
- if (!upload.file)
346
- upload.reject(createError(400, 'File missing in the request.'));
347
- });
348
-
349
- parser.once('error', exit);
350
-
351
- response.once('finish', release);
352
- response.once('close', release);
353
-
354
- request.once('close', abort);
355
- request.once('end', () => {
356
- request.removeListener('close', abort);
357
- });
358
-
359
- request.pipe(parser);
360
- });
361
- };