graphql-upload 13.0.0 → 14.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,47 +1,32 @@
1
+ // @ts-check
2
+
1
3
  "use strict";
2
4
 
3
5
  const Busboy = require("busboy");
4
6
  const { WriteStream } = require("fs-capacitor");
5
7
  const createError = require("http-errors");
6
8
  const objectPath = require("object-path");
7
- const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = require("../private/GRAPHQL_MULTIPART_REQUEST_SPEC_URL");
8
- const ignoreStream = require("../private/ignoreStream");
9
- const Upload = require("./Upload");
9
+ const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = require("./GRAPHQL_MULTIPART_REQUEST_SPEC_URL.js");
10
+ const ignoreStream = require("./ignoreStream.js");
11
+ const Upload = require("./Upload.js");
12
+
13
+ /** @typedef {import("./GraphQLUpload.js")} GraphQLUpload */
14
+ /** @typedef {import("./graphqlUploadExpress.js")} graphqlUploadExpress */
15
+ /** @typedef {import("./graphqlUploadKoa.js")} graphqlUploadKoa */
10
16
 
11
17
  /**
12
- * Processes a
18
+ * Processes an incoming
13
19
  * [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`]{@link GraphQLUpload} scalar to derive it’s value. Errors are
19
- * created with [`http-errors`](https://npm.im/http-errors) to assist in sending
20
- * responses with appropriate HTTP status codes. Used in
21
- * [`graphqlUploadExpress`]{@link graphqlUploadExpress} and
22
- * [`graphqlUploadKoa`]{@link graphqlUploadKoa} and can be used to create custom
23
- * middleware.
24
- * @kind function
25
- * @name processRequest
20
+ * It parses the `operations` and `map` fields to create an {@linkcode Upload}
21
+ * instance for each expected file upload, placing references wherever the file
22
+ * is expected in the GraphQL operation for the {@linkcode GraphQLUpload} scalar
23
+ * to derive it’s value. Errors are created with
24
+ * [`http-errors`](https://npm.im/http-errors) to assist in sending responses
25
+ * with appropriate HTTP status codes. Used to create custom middleware and is
26
+ * used by {@linkcode graphqlUploadExpress} and {@linkcode graphqlUploadKoa}.
26
27
  * @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.js");
42
- * ```
43
28
  */
44
- module.exports = function processRequest(
29
+ function processRequest(
45
30
  request,
46
31
  response,
47
32
  {
@@ -51,14 +36,34 @@ module.exports = function processRequest(
51
36
  } = {}
52
37
  ) {
53
38
  return new Promise((resolve, reject) => {
39
+ /** @type {boolean} */
54
40
  let released;
41
+
42
+ /** @type {Error} */
55
43
  let exitError;
44
+
45
+ /** @type {import("stream").Readable} */
56
46
  let lastFileStream;
47
+
48
+ /**
49
+ * @type {{ [key: string]: unknown } | Array<
50
+ * { [key: string]: unknown }
51
+ * >}
52
+ */
57
53
  let operations;
54
+
55
+ /**
56
+ * @type {import("object-path").ObjectPathBound<
57
+ * { [key: string]: unknown } | Array<{ [key: string]: unknown }>
58
+ * >}
59
+ */
58
60
  let operationsPath;
61
+
62
+ /** @type {Map<string, Upload>} */
59
63
  let map;
60
64
 
61
65
  const parser = new Busboy({
66
+ // @ts-ignore This is about to change with `busboy` v1 types.
62
67
  headers: request.headers,
63
68
  limits: {
64
69
  fieldSize: maxFieldSize,
@@ -70,14 +75,11 @@ module.exports = function processRequest(
70
75
 
71
76
  /**
72
77
  * 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
78
+ * @param {Error} error Error instance.
77
79
  */
78
80
  const exit = (error) => {
79
81
  // None of the tested scenarios cause multiple calls of this function, but
80
- // it’t still good to guard against it happening in case it’s possible now
82
+ // it’s still good to guard against it happening in case it’s possible now
81
83
  // or in the future.
82
84
  // coverage ignore next line
83
85
  if (exitError) return;
@@ -252,7 +254,9 @@ module.exports = function processRequest(
252
254
  return;
253
255
  }
254
256
 
257
+ /** @type {Error} */
255
258
  let fileError;
259
+
256
260
  const capacitor = new WriteStream();
257
261
 
258
262
  capacitor.on("error", () => {
@@ -275,6 +279,7 @@ module.exports = function processRequest(
275
279
  capacitor.destroy(fileError);
276
280
  });
277
281
 
282
+ /** @type {FileUpload} */
278
283
  const file = {
279
284
  filename,
280
285
  mimetype,
@@ -284,9 +289,14 @@ module.exports = function processRequest(
284
289
  if (error) throw error;
285
290
  return capacitor.createReadStream(options);
286
291
  },
292
+ capacitor,
287
293
  };
288
294
 
289
- Object.defineProperty(file, "capacitor", { value: capacitor });
295
+ Object.defineProperty(file, "capacitor", {
296
+ enumerable: false,
297
+ configurable: false,
298
+ writable: false,
299
+ });
290
300
 
291
301
  stream.pipe(capacitor);
292
302
  upload.resolve(file);
@@ -345,4 +355,81 @@ module.exports = function processRequest(
345
355
 
346
356
  request.pipe(parser);
347
357
  });
348
- };
358
+ }
359
+
360
+ module.exports = processRequest;
361
+
362
+ /**
363
+ * File upload details that are only available after the file’s field in the
364
+ * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec)
365
+ * has begun streaming in.
366
+ * @typedef {object} FileUpload
367
+ * @prop {string} filename File name.
368
+ * @prop {string} mimetype File MIME type. Provided by the client and can’t be
369
+ * trusted.
370
+ * @prop {string} encoding File stream transfer encoding.
371
+ * @prop {import("fs-capacitor").WriteStream} capacitor A private implementation
372
+ * detail that shouldn’t be used outside
373
+ * [`graphql-upload`](https://npm.im/graphql-upload).
374
+ * @prop {FileUploadCreateReadStream} createReadStream Creates a
375
+ * [Node.js readable stream](https://nodejs.org/api/stream.html#readable-streams)
376
+ * of the file’s contents, for processing and storage.
377
+ */
378
+
379
+ /**
380
+ * Creates a
381
+ * [Node.js readable stream](https://nodejs.org/api/stream.html#readable-streams)
382
+ * of an {@link FileUpload uploading file’s} contents, for processing and
383
+ * storage. Multiple calls create independent streams. Throws if called after
384
+ * all resolvers have resolved, or after an error has interrupted the request.
385
+ * @callback FileUploadCreateReadStream
386
+ * @param {FileUploadCreateReadStreamOptions} [options] Options.
387
+ * @returns {import("stream").Readable}
388
+ * [Node.js readable stream](https://nodejs.org/api/stream.html#readable-streams)
389
+ * of the file’s contents.
390
+ * @see [Node.js `Readable` stream constructor docs](https://nodejs.org/api/stream.html#new-streamreadableoptions).
391
+ * @see [Node.js stream backpressure guide](https://nodejs.org/en/docs/guides/backpressuring-in-streams).
392
+ */
393
+
394
+ /**
395
+ * {@linkcode FileUploadCreateReadStream} options.
396
+ * @typedef {object} FileUploadCreateReadStreamOptions
397
+ * @prop {string} [options.encoding] Specify an encoding for the
398
+ * [`data`](https://nodejs.org/api/stream.html#event-data) chunks to be
399
+ * strings (without splitting multi-byte characters across chunks) instead of
400
+ * Node.js [`Buffer`](https://nodejs.org/api/buffer.html#buffer) instances.
401
+ * Supported values depend on the
402
+ * [`Buffer` implementation](https://github.com/nodejs/node/blob/v18.1.0/lib/buffer.js#L590-L680)
403
+ * and include `utf8`, `ucs2`, `utf16le`, `latin1`, `ascii`, `base64`,
404
+ * `base64url`, or `hex`. Defaults to `utf8`.
405
+ * @prop {number} [options.highWaterMark] Maximum number of bytes to store in
406
+ * the internal buffer before ceasing to read from the underlying resource.
407
+ * Defaults to `16384`.
408
+ */
409
+
410
+ /**
411
+ * Processes an incoming
412
+ * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
413
+ * @callback ProcessRequestFunction
414
+ * @param {import("http").IncomingMessage} request
415
+ * [Node.js HTTP server request instance](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
416
+ * @param {import("http").ServerResponse} response
417
+ * [Node.js HTTP server response instance](https://nodejs.org/api/http.html#http_class_http_serverresponse).
418
+ * @param {ProcessRequestOptions} [options] Options.
419
+ * @returns {Promise<
420
+ * { [key: string]: unknown } | Array<{ [key: string]: unknown }>
421
+ * >} GraphQL operation or batch of operations for a GraphQL server to consume
422
+ * (usually as the request body). A GraphQL operation typically has the
423
+ * properties `query` and `variables`.
424
+ */
425
+
426
+ /**
427
+ * {@linkcode ProcessRequestFunction} options.
428
+ * @typedef {object} ProcessRequestOptions
429
+ * @prop {number} [maxFieldSize] Maximum allowed non file multipart form field
430
+ * size in bytes; enough for your queries. Defaults to `1000000` (1 MB).
431
+ * @prop {number} [maxFileSize] Maximum allowed file size in bytes. Defaults to
432
+ * `Infinity`.
433
+ * @prop {number} [maxFiles] Maximum allowed number of files. Defaults to
434
+ * `Infinity`.
435
+ */
package/readme.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  [![npm version](https://badgen.net/npm/v/graphql-upload)](https://npm.im/graphql-upload) [![CI status](https://github.com/jaydenseric/graphql-upload/workflows/CI/badge.svg)](https://github.com/jaydenseric/graphql-upload/actions)
6
6
 
7
- Middleware and an [`Upload`](#class-graphqlupload) scalar to add support for [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec) (file uploads via queries and mutations) to various Node.js GraphQL servers.
7
+ Middleware and an [`Upload`](./GraphQLUpload.js) scalar to add support for [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec) (file uploads via queries and mutations) to various Node.js GraphQL servers.
8
8
 
9
9
  ## Installation
10
10
 
@@ -16,407 +16,44 @@ To install [`graphql-upload`](https://npm.im/graphql-upload) and the [`graphql`]
16
16
  npm install graphql-upload graphql
17
17
  ```
18
18
 
19
- Use the [`graphqlUploadKoa`](#function-graphqluploadkoa) or [`graphqlUploadExpress`](#function-graphqluploadexpress) middleware just before GraphQL middleware. Alternatively, use [`processRequest`](#function-processrequest) to create custom middleware.
19
+ Use the [`graphqlUploadKoa`](./graphqlUploadKoa.js) or [`graphqlUploadExpress`](./graphqlUploadExpress.js) middleware just before GraphQL middleware. Alternatively, use [`processRequest`](./processRequest.js) to create custom middleware.
20
20
 
21
- A schema built with separate SDL and resolvers (e.g. using [`makeExecutableSchema`](https://www.graphql-tools.com/docs/api/modules/schema#makeexecutableschema) from [`@graphql-tools/schema`](https://npm.im/@graphql-tools/schema)) requires the [`Upload`](#class-graphqlupload) scalar to be setup.
21
+ A schema built with separate SDL and resolvers (e.g. using [`makeExecutableSchema`](https://www.graphql-tools.com/docs/api/modules/schema_src#makeexecutableschema) from [`@graphql-tools/schema`](https://npm.im/@graphql-tools/schema)) requires the [`Upload`](./GraphQLUpload.js) scalar to be setup.
22
22
 
23
23
  ## Usage
24
24
 
25
- [Clients implementing the GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec#client) upload files as [`Upload`](#class-graphqlupload) scalar query or mutation variables. Their resolver values are promises that resolve [file upload details](#type-fileupload) for processing and storage. Files are typically streamed into cloud storage but may also be stored in the filesystem.
25
+ [Clients implementing the GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec#client) upload files as [`Upload`](./GraphQLUpload.js) scalar query or mutation variables. Their resolver values are promises that resolve file upload details for processing and storage. Files are typically streamed into cloud storage but may also be stored in the filesystem.
26
26
 
27
27
  See the [example API and client](https://github.com/jaydenseric/apollo-upload-examples).
28
28
 
29
29
  ### Tips
30
30
 
31
- - The process must have both read and write access to the directory identified by [`os.tmpdir()`](https://nodejs.org/api/os.html#os_os_tmpdir).
31
+ - The process must have both read and write access to the directory identified by [`os.tmpdir()`](https://nodejs.org/api/os.html#ostmpdir).
32
32
  - The device requires sufficient disk space to buffer the expected number of concurrent upload requests.
33
33
  - Promisify and await file upload streams in resolvers or the server will send a response to the client before uploads are complete, causing a disconnect.
34
34
  - Handle file upload promise rejection and stream errors; uploads sometimes fail due to network connectivity issues or impatient users disconnecting.
35
- - Process multiple uploads asynchronously with [`Promise.all`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/promise/all) or a more flexible solution such as [`Promise.allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) where an error in one does not reject them all.
36
- - Only use [`createReadStream()`](#type-fileupload) _before_ the resolver returns; late calls (e.g. in an unawaited async function or callback) throw an error. Existing streams can still be used after a response is sent, although there are few valid reasons for not awaiting their completion.
37
- - Use [`stream.destroy()`](https://nodejs.org/api/stream.html#stream_readable_destroy_error) when an incomplete stream is no longer needed, or temporary files may not get cleaned up.
35
+ - Process multiple uploads asynchronously with [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) or a more flexible solution such as [`Promise.allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) where an error in one does not reject them all.
36
+ - Only use the function `createReadStream` _before_ the resolver returns; late calls (e.g. in an unawaited async function or callback) throw an error. Existing streams can still be used after a response is sent, although there are few valid reasons for not awaiting their completion.
37
+ - Use [`stream.destroy()`](https://nodejs.org/api/stream.html#readabledestroyerror) when an incomplete stream is no longer needed, or temporary files may not get cleaned up.
38
38
 
39
39
  ## Architecture
40
40
 
41
41
  The [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec) allows a file to be used for multiple query or mutation variables (file deduplication), and for variables to be used in multiple places. GraphQL resolvers need to be able to manage independent file streams. As resolvers are executed asynchronously, it’s possible they will try to process files in a different order than received in the multipart request.
42
42
 
43
- [`busboy`](https://npm.im/busboy) parses multipart request streams. Once the `operations` and `map` fields have been parsed, [`Upload`](#class-graphqlupload) scalar values in the GraphQL operations are populated with promises, and the operations are passed down the middleware chain to GraphQL resolvers.
43
+ [`busboy`](https://npm.im/busboy) parses multipart request streams. Once the `operations` and `map` fields have been parsed, [`Upload`](./GraphQLUpload.js) scalar values in the GraphQL operations are populated with promises, and the operations are passed down the middleware chain to GraphQL resolvers.
44
44
 
45
- [`fs-capacitor`](https://npm.im/fs-capacitor) is used to buffer file uploads to the filesystem and coordinate simultaneous reading and writing. As soon as a file upload’s contents begins streaming, its data begins buffering to the filesystem and its associated promise resolves. GraphQL resolvers can then create new streams from the buffer by calling [`createReadStream()`](#type-fileupload). The buffer is destroyed once all streams have ended or closed and the server has responded to the request. Any remaining buffer files will be cleaned when the process exits.
45
+ [`fs-capacitor`](https://npm.im/fs-capacitor) is used to buffer file uploads to the filesystem and coordinate simultaneous reading and writing. As soon as a file upload’s contents begins streaming, its data begins buffering to the filesystem and its associated promise resolves. GraphQL resolvers can then create new streams from the buffer by calling the function `createReadStream`. The buffer is destroyed once all streams have ended or closed and the server has responded to the request. Any remaining buffer files will be cleaned when the process exits.
46
46
 
47
47
  ## Requirements
48
48
 
49
- - [Node.js](https://nodejs.org): `^12.22.0 || ^14.17.0 || >= 16.0.0`
49
+ - [Node.js](https://nodejs.org): `^14.17.0 || ^16.0.0 || >= 18.0.0`
50
50
 
51
- ## API
51
+ ## Exports
52
52
 
53
- - [class GraphQLUpload](#class-graphqlupload)
54
- - [class Upload](#class-upload)
55
- - [Upload instance method reject](#upload-instance-method-reject)
56
- - [Upload instance method resolve](#upload-instance-method-resolve)
57
- - [Upload instance property file](#upload-instance-property-file)
58
- - [Upload instance property promise](#upload-instance-property-promise)
59
- - [function graphqlUploadExpress](#function-graphqluploadexpress)
60
- - [function graphqlUploadKoa](#function-graphqluploadkoa)
61
- - [function processRequest](#function-processrequest)
62
- - [type FileUpload](#type-fileupload)
63
- - [type FileUploadCreateReadStream](#type-fileuploadcreatereadstream)
64
- - [type GraphQLOperation](#type-graphqloperation)
65
- - [type ProcessRequestFunction](#type-processrequestfunction)
66
- - [type ProcessRequestOptions](#type-processrequestoptions)
53
+ These CommonJS modules are published to [npm](https://npmjs.com) and exported via the [`package.json`](./package.json) `exports` field:
67
54
 
68
- ### class GraphQLUpload
69
-
70
- A GraphQL `Upload` scalar that can be used in a [`GraphQLSchema`](https://graphql.org/graphql-js/type/#graphqlschema). It’s value in resolvers is a promise that resolves [file upload details](#type-fileupload) for processing and storage.
71
-
72
- #### Examples
73
-
74
- _Ways to `import`._
75
-
76
- > ```js
77
- > import { GraphQLUpload } from "graphql-upload";
78
- > ```
79
- >
80
- > ```js
81
- > import GraphQLUpload from "graphql-upload/public/GraphQLUpload.js";
82
- > ```
83
-
84
- _Ways to `require`._
85
-
86
- > ```js
87
- > const { GraphQLUpload } = require("graphql-upload");
88
- > ```
89
- >
90
- > ```js
91
- > const GraphQLUpload = require("graphql-upload/public/GraphQLUpload.js");
92
- > ```
93
-
94
- _A schema built using [`makeExecutableSchema`](https://www.graphql-tools.com/docs/api/modules/schema#makeexecutableschema) from [`@graphql-tools/schema`](https://npm.im/@graphql-tools/schema)._
95
-
96
- > ```js
97
- > const { makeExecutableSchema } = require("@graphql-tools/schema");
98
- > const { GraphQLUpload } = require("graphql-upload");
99
- >
100
- > const schema = makeExecutableSchema({
101
- > typeDefs: /* GraphQL */ `
102
- > scalar Upload
103
- > `,
104
- > resolvers: {
105
- > Upload: GraphQLUpload,
106
- > },
107
- > });
108
- > ```
109
-
110
- _A manually constructed schema with an image upload mutation._
111
-
112
- > ```js
113
- > const {
114
- > GraphQLSchema,
115
- > GraphQLObjectType,
116
- > GraphQLBoolean,
117
- > } = require("graphql");
118
- > const { GraphQLUpload } = require("graphql-upload");
119
- >
120
- > const schema = new GraphQLSchema({
121
- > mutation: new GraphQLObjectType({
122
- > name: "Mutation",
123
- > fields: {
124
- > uploadImage: {
125
- > description: "Uploads an image.",
126
- > type: GraphQLBoolean,
127
- > args: {
128
- > image: {
129
- > description: "Image file.",
130
- > type: GraphQLUpload,
131
- > },
132
- > },
133
- > async resolve(parent, { image }) {
134
- > const { filename, mimetype, createReadStream } = await image;
135
- > const stream = createReadStream();
136
- > // Promisify the stream and store the file, then…
137
- > return true;
138
- > },
139
- > },
140
- > },
141
- > }),
142
- > });
143
- > ```
144
-
145
- ---
146
-
147
- ### class Upload
148
-
149
- A file expected to be uploaded as it has been declared in the `map` field of a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec). The [`processRequest`](#function-processrequest) function places references to an instance of this class wherever the file is expected in the [GraphQL operation](#type-graphqloperation). The [`Upload`](#class-graphqlupload) scalar derives it’s value from the [`promise`](#upload-instance-property-promise) property.
150
-
151
- #### Examples
152
-
153
- _Ways to `import`._
154
-
155
- > ```js
156
- > import { Upload } from "graphql-upload";
157
- > ```
158
- >
159
- > ```js
160
- > import Upload from "graphql-upload/public/Upload.js";
161
- > ```
162
-
163
- _Ways to `require`._
164
-
165
- > ```js
166
- > const { Upload } = require("graphql-upload");
167
- > ```
168
- >
169
- > ```js
170
- > const Upload = require("graphql-upload/public/Upload.js");
171
- > ```
172
-
173
- #### Upload instance method reject
174
-
175
- Rejects the upload promise with an error. This should only be utilized by [`processRequest`](#function-processrequest).
176
-
177
- | Parameter | Type | Description |
178
- | :-------- | :----- | :-------------- |
179
- | `error` | object | Error instance. |
180
-
181
- #### Upload instance method resolve
182
-
183
- Resolves the upload promise with the file upload details. This should only be utilized by [`processRequest`](#function-processrequest).
184
-
185
- | Parameter | Type | Description |
186
- | :-------- | :----------------------------- | :------------------- |
187
- | `file` | [FileUpload](#type-fileupload) | File upload details. |
188
-
189
- #### Upload instance property file
190
-
191
- The file upload details, available when the [upload promise](#upload-instance-property-promise) resolves. This should only be utilized by [`processRequest`](#function-processrequest).
192
-
193
- **Type:** `undefined` | [FileUpload](#type-fileupload)
194
-
195
- #### Upload instance property promise
196
-
197
- Promise that resolves file upload details. This should only be utilized by [`GraphQLUpload`](#class-graphqlupload).
198
-
199
- **Type:** Promise<[FileUpload](#type-fileupload)>
200
-
201
- ---
202
-
203
- ### function graphqlUploadExpress
204
-
205
- Creates [Express](https://expressjs.com) middleware that processes [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec) using [`processRequest`](#function-processrequest), ignoring non-multipart requests. It sets the request body to be [similar to a conventional GraphQL POST request](#type-graphqloperation) for following GraphQL middleware to consume.
206
-
207
- | Parameter | Type | Description |
208
- | :-- | :-- | :-- |
209
- | `options` | [ProcessRequestOptions](#type-processrequestoptions) | Middleware options. Any [`ProcessRequestOptions`](#type-processrequestoptions) can be used. |
210
- | `options.processRequest` | [ProcessRequestFunction](#type-processrequestfunction)? = [processRequest](#function-processrequest) | Used to process [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec). |
211
-
212
- **Returns:** Function — Express middleware.
213
-
214
- #### Examples
215
-
216
- _Ways to `import`._
217
-
218
- > ```js
219
- > import { graphqlUploadExpress } from "graphql-upload";
220
- > ```
221
- >
222
- > ```js
223
- > import graphqlUploadExpress from "graphql-upload/public/graphqlUploadExpress.js";
224
- > ```
225
-
226
- _Ways to `require`._
227
-
228
- > ```js
229
- > const { graphqlUploadExpress } = require("graphql-upload");
230
- > ```
231
- >
232
- > ```js
233
- > const graphqlUploadExpress = require("graphql-upload/public/graphqlUploadExpress.js");
234
- > ```
235
-
236
- _Basic [`express-graphql`](https://npm.im/express-graphql) setup._
237
-
238
- > ```js
239
- > const express = require("express");
240
- > const graphqlHTTP = require("express-graphql");
241
- > const { graphqlUploadExpress } = require("graphql-upload");
242
- > const schema = require("./schema");
243
- >
244
- > express()
245
- > .use(
246
- > "/graphql",
247
- > graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
248
- > graphqlHTTP({ schema })
249
- > )
250
- > .listen(3000);
251
- > ```
252
-
253
- ---
254
-
255
- ### function graphqlUploadKoa
256
-
257
- Creates [Koa](https://koajs.com) middleware that processes [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec) using [`processRequest`](#function-processrequest), ignoring non-multipart requests. It sets the request body to be [similar to a conventional GraphQL POST request](#type-graphqloperation) for following GraphQL middleware to consume.
258
-
259
- | Parameter | Type | Description |
260
- | :-- | :-- | :-- |
261
- | `options` | [ProcessRequestOptions](#type-processrequestoptions) | Middleware options. Any [`ProcessRequestOptions`](#type-processrequestoptions) can be used. |
262
- | `options.processRequest` | [ProcessRequestFunction](#type-processrequestfunction)? = [processRequest](#function-processrequest) | Used to process [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec). |
263
-
264
- **Returns:** Function — Koa middleware.
265
-
266
- #### Examples
267
-
268
- _Ways to `import`._
269
-
270
- > ```js
271
- > import { graphqlUploadKoa } from "graphql-upload";
272
- > ```
273
- >
274
- > ```js
275
- > import graphqlUploadKoa from "graphql-upload/public/graphqlUploadKoa.js";
276
- > ```
277
-
278
- _Ways to `require`._
279
-
280
- > ```js
281
- > const { graphqlUploadKoa } = require("graphql-upload");
282
- > ```
283
- >
284
- > ```js
285
- > const graphqlUploadKoa = require("graphql-upload/public/graphqlUploadKoa.js");
286
- > ```
287
-
288
- _Basic [`graphql-api-koa`](https://npm.im/graphql-api-koa) setup._
289
-
290
- > ```js
291
- > const Koa = require("koa");
292
- > const bodyParser = require("koa-bodyparser");
293
- > const { errorHandler, execute } = require("graphql-api-koa");
294
- > const { graphqlUploadKoa } = require("graphql-upload");
295
- > const schema = require("./schema");
296
- >
297
- > new Koa()
298
- > .use(errorHandler())
299
- > .use(bodyParser())
300
- > .use(graphqlUploadKoa({ maxFileSize: 10000000, maxFiles: 10 }))
301
- > .use(execute({ schema }))
302
- > .listen(3000);
303
- > ```
304
-
305
- ---
306
-
307
- ### function processRequest
308
-
309
- Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec). It parses the `operations` and `map` fields to create an [`Upload`](#class-upload) instance for each expected file upload, placing references wherever the file is expected in the [GraphQL operation](#type-graphqloperation) for the [`Upload`](#class-graphqlupload) scalar 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`](#function-graphqluploadexpress) and [`graphqlUploadKoa`](#function-graphqluploadkoa) and can be used to create custom middleware.
310
-
311
- **Type:** [ProcessRequestFunction](#type-processrequestfunction)
312
-
313
- #### Examples
314
-
315
- _Ways to `import`._
316
-
317
- > ```js
318
- > import { processRequest } from "graphql-upload";
319
- > ```
320
- >
321
- > ```js
322
- > import processRequest from "graphql-upload/public/processRequest.js";
323
- > ```
324
-
325
- _Ways to `require`._
326
-
327
- > ```js
328
- > const { processRequest } = require("graphql-upload");
329
- > ```
330
- >
331
- > ```js
332
- > const processRequest = require("graphql-upload/public/processRequest.js");
333
- > ```
334
-
335
- ---
336
-
337
- ### type FileUpload
338
-
339
- File upload details that are only available after the file’s field in the [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec) has begun streaming in.
340
-
341
- **Type:** object
342
-
343
- | Property | Type | Description |
344
- | :-- | :-- | :-- |
345
- | `filename` | string | File name. |
346
- | `mimetype` | string | File MIME type. Provided by the client and can’t be trusted. |
347
- | `encoding` | string | File stream transfer encoding. |
348
- | `createReadStream` | [FileUploadCreateReadStream](#type-fileuploadcreatereadstream) | Creates a [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the file’s contents, for processing and storage. |
349
-
350
- ---
351
-
352
- ### type FileUploadCreateReadStream
353
-
354
- Creates a [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of an [uploading file’s](#type-fileupload) contents, for processing and storage. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request.
355
-
356
- **Type:** Function
357
-
358
- | Parameter | Type | Description |
359
- | :-- | :-- | :-- |
360
- | `options` | object? | [`fs-capacitor`](https://npm.im/fs-capacitor) [`ReadStreamOptions`](https://github.com/mike-marcacci/fs-capacitor#readstreamoptions). |
361
- | `options.encoding` | string? = `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`. |
362
- | `options.highWaterMark` | number? = `16384` | Maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. |
363
-
364
- **Returns:** Readable — [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the file’s contents.
365
-
366
- #### See
367
-
368
- - [Node.js `Readable` stream constructor docs](https://nodejs.org/api/stream.html#stream_new_stream_readable_options).
369
- - [Node.js stream backpressure guide](https://nodejs.org/en/docs/guides/backpressuring-in-streams).
370
-
371
- ---
372
-
373
- ### type GraphQLOperation
374
-
375
- A GraphQL operation object in a shape that can be consumed and executed by most GraphQL servers.
376
-
377
- **Type:** object
378
-
379
- | Property | Type | Description |
380
- | :-- | :-- | :-- |
381
- | `query` | string | GraphQL document containing queries and fragments. |
382
- | `operationName` | string \| `null`? | GraphQL document operation name to execute. |
383
- | `variables` | object \| `null`? | GraphQL document operation variables and values map. |
384
-
385
- #### See
386
-
387
- - [GraphQL over HTTP spec](https://github.com/graphql/graphql-over-http).
388
- - [Apollo Server POST requests](https://www.apollographql.com/docs/apollo-server/requests/#post-requests).
389
-
390
- ---
391
-
392
- ### type ProcessRequestFunction
393
-
394
- Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
395
-
396
- **Type:** Function
397
-
398
- | Parameter | Type | Description |
399
- | :-- | :-- | :-- |
400
- | `request` | IncomingMessage | [Node.js HTTP server request instance](https://nodejs.org/api/http.html#http_class_http_incomingmessage). |
401
- | `response` | ServerResponse | [Node.js HTTP server response instance](https://nodejs.org/api/http.html#http_class_http_serverresponse). |
402
- | `options` | [ProcessRequestOptions](#type-processrequestoptions)? | Options for processing the request. |
403
-
404
- **Returns:** Promise<[GraphQLOperation](#type-graphqloperation) | Array<[GraphQLOperation](#type-graphqloperation)>> — GraphQL operation or batch of operations for a GraphQL server to consume (usually as the request body).
405
-
406
- #### See
407
-
408
- - [`processRequest`](#function-processrequest).
409
-
410
- ---
411
-
412
- ### type ProcessRequestOptions
413
-
414
- Options for processing a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec); mostly relating to security, performance and limits.
415
-
416
- **Type:** object
417
-
418
- | Property | Type | Description |
419
- | :-- | :-- | :-- |
420
- | `maxFieldSize` | number? = `1000000` | Maximum allowed non-file multipart form field size in bytes; enough for your queries. |
421
- | `maxFileSize` | number? = Infinity | Maximum allowed file size in bytes. |
422
- | `maxFiles` | number? = Infinity | Maximum allowed number of files. |
55
+ - [`GraphQLUpload.js`](./GraphQLUpload.js)
56
+ - [`graphqlUploadExpress.js`](./graphqlUploadExpress.js)
57
+ - [`graphqlUploadKoa.js`](./graphqlUploadKoa.js)
58
+ - [`processRequest.js`](./processRequest.js)
59
+ - [`Upload.js`](./Upload.js)