graphql-upload 8.0.7 → 8.1.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.
package/changelog.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # graphql-upload changelog
2
2
 
3
+ ## 8.1.0
4
+
5
+ ### Minor
6
+
7
+ - `processRequest` now throws an appropriate error when a multipart field value exceeds the configured size limit, fixing [#159](https://github.com/jaydenseric/graphql-upload/issues/159).
8
+ - When the file size limit is exceeded, mention how many bytes the limit is in the stream error message.
9
+ - Added a new `processRequest` option to the `graphqlUploadExpress` and `graphqlUploadKoa` middleware, for improved testing without mocks or spies which are difficult to achieve with ESM.
10
+
11
+ ### Patch
12
+
13
+ - Updated dependencies.
14
+ - Due to updated dependencies: Lint fixes, removed redundant `eslint-disable-next-line` comments, and regenerated the readme.
15
+ - Documented [`koa-graphql`](https://npm.im/koa-graphql) as known to be compatible, via [#156](https://github.com/jaydenseric/graphql-upload/pull/156).
16
+ - Fixed a readme typo, via [#161](https://github.com/jaydenseric/graphql-upload/pull/161).
17
+ - Use GitHub Actions instead of Travis for CI.
18
+ - Removed `package-lock.json` from `.gitignore` and `.prettierignore`, as it’s disabled in `.npmrc` anyway.
19
+ - New file structure.
20
+ - Explicitly defined main exports (instead of using `export * from`) to prevent accidental public exposure of internal APIs.
21
+ - Moved JSDoc typedefs into the index main entry file, alphabetically sorted.
22
+ - Nicer Browserslist query syntax.
23
+ - Replaced the `isObject` helper with a smarter and tested `isEnumerableObject`.
24
+ - Removed the `isString` helper.
25
+ - Enforced 100% code coverage for tests, and improved `processRequest` internals and tests (including a new test using vanilla Node.js HTTP), fixing [#130](https://github.com/jaydenseric/graphql-upload/issues/130) via [#162](https://github.com/jaydenseric/graphql-upload/pull/162).
26
+ - Removed a workaround from the `startServer` test helper.
27
+ - Added a new `ProcessRequestFunction` JSDoc type, and applied it to `processRequest`.
28
+ - Renamed the `UploadOptions` JSDoc type to `ProcessRequestOptions`.
29
+ - Misc. documentation improvements.
30
+
3
31
  ## 8.0.7
4
32
 
5
33
  ### Patch
@@ -0,0 +1,6 @@
1
+ 'use strict'
2
+
3
+ exports.__esModule = true
4
+ exports.SPEC_URL = void 0
5
+ const SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec'
6
+ exports.SPEC_URL = SPEC_URL
@@ -0,0 +1,2 @@
1
+ export const SPEC_URL =
2
+ 'https://github.com/jaydenseric/graphql-multipart-request-spec'
@@ -5,7 +5,10 @@ exports.graphqlUploadExpress = void 0
5
5
 
6
6
  var _processRequest = require('./processRequest')
7
7
 
8
- const graphqlUploadExpress = options => (request, response, next) => {
8
+ const graphqlUploadExpress = ({
9
+ processRequest = _processRequest.processRequest,
10
+ ...processRequestOptions
11
+ } = {}) => (request, response, next) => {
9
12
  if (!request.is('multipart/form-data')) return next()
10
13
  const finished = new Promise(resolve => request.on('end', resolve))
11
14
  const { send } = response
@@ -17,7 +20,7 @@ const graphqlUploadExpress = options => (request, response, next) => {
17
20
  })
18
21
  }
19
22
 
20
- ;(0, _processRequest.processRequest)(request, response, options)
23
+ processRequest(request, response, processRequestOptions)
21
24
  .then(body => {
22
25
  request.body = body
23
26
  next()
@@ -1,5 +1,8 @@
1
- import { processRequest } from './processRequest'
2
- export const graphqlUploadExpress = options => (request, response, next) => {
1
+ import { processRequest as defaultProcessRequest } from './processRequest'
2
+ export const graphqlUploadExpress = ({
3
+ processRequest = defaultProcessRequest,
4
+ ...processRequestOptions
5
+ } = {}) => (request, response, next) => {
3
6
  if (!request.is('multipart/form-data')) return next()
4
7
  const finished = new Promise(resolve => request.on('end', resolve))
5
8
  const { send } = response
@@ -11,7 +14,7 @@ export const graphqlUploadExpress = options => (request, response, next) => {
11
14
  })
12
15
  }
13
16
 
14
- processRequest(request, response, options)
17
+ processRequest(request, response, processRequestOptions)
15
18
  .then(body => {
16
19
  request.body = body
17
20
  next()
@@ -5,15 +5,18 @@ exports.graphqlUploadKoa = void 0
5
5
 
6
6
  var _processRequest = require('./processRequest')
7
7
 
8
- const graphqlUploadKoa = options => async (ctx, next) => {
8
+ const graphqlUploadKoa = ({
9
+ processRequest = _processRequest.processRequest,
10
+ ...processRequestOptions
11
+ } = {}) => async (ctx, next) => {
9
12
  if (!ctx.request.is('multipart/form-data')) return next()
10
13
  const finished = new Promise(resolve => ctx.req.on('end', resolve))
11
14
 
12
15
  try {
13
- ctx.request.body = await (0, _processRequest.processRequest)(
16
+ ctx.request.body = await processRequest(
14
17
  ctx.req,
15
18
  ctx.res,
16
- options
19
+ processRequestOptions
17
20
  )
18
21
  await next()
19
22
  } finally {
@@ -1,10 +1,17 @@
1
- import { processRequest } from './processRequest'
2
- export const graphqlUploadKoa = options => async (ctx, next) => {
1
+ import { processRequest as defaultProcessRequest } from './processRequest'
2
+ export const graphqlUploadKoa = ({
3
+ processRequest = defaultProcessRequest,
4
+ ...processRequestOptions
5
+ } = {}) => async (ctx, next) => {
3
6
  if (!ctx.request.is('multipart/form-data')) return next()
4
7
  const finished = new Promise(resolve => ctx.req.on('end', resolve))
5
8
 
6
9
  try {
7
- ctx.request.body = await processRequest(ctx.req, ctx.res, options)
10
+ ctx.request.body = await processRequest(
11
+ ctx.req,
12
+ ctx.res,
13
+ processRequestOptions
14
+ )
8
15
  await next()
9
16
  } finally {
10
17
  await finished
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+
3
+ exports.__esModule = true
4
+ exports.ignoreStream = void 0
5
+
6
+ const ignoreStream = stream => {
7
+ stream.on('error', () => {})
8
+ stream.resume()
9
+ }
10
+
11
+ exports.ignoreStream = ignoreStream
@@ -0,0 +1,4 @@
1
+ export const ignoreStream = stream => {
2
+ stream.on('error', () => {})
3
+ stream.resume()
4
+ }
package/lib/index.js CHANGED
@@ -1,31 +1,20 @@
1
1
  'use strict'
2
2
 
3
3
  exports.__esModule = true
4
+ exports.graphqlUploadExpress = exports.graphqlUploadKoa = exports.processRequest = exports.GraphQLUpload = void 0
4
5
 
5
6
  var _GraphQLUpload = require('./GraphQLUpload')
6
7
 
7
- Object.keys(_GraphQLUpload).forEach(function(key) {
8
- if (key === 'default' || key === '__esModule') return
9
- exports[key] = _GraphQLUpload[key]
10
- })
8
+ exports.GraphQLUpload = _GraphQLUpload.GraphQLUpload
11
9
 
12
10
  var _processRequest = require('./processRequest')
13
11
 
14
- Object.keys(_processRequest).forEach(function(key) {
15
- if (key === 'default' || key === '__esModule') return
16
- exports[key] = _processRequest[key]
17
- })
12
+ exports.processRequest = _processRequest.processRequest
18
13
 
19
14
  var _graphqlUploadKoa = require('./graphqlUploadKoa')
20
15
 
21
- Object.keys(_graphqlUploadKoa).forEach(function(key) {
22
- if (key === 'default' || key === '__esModule') return
23
- exports[key] = _graphqlUploadKoa[key]
24
- })
16
+ exports.graphqlUploadKoa = _graphqlUploadKoa.graphqlUploadKoa
25
17
 
26
18
  var _graphqlUploadExpress = require('./graphqlUploadExpress')
27
19
 
28
- Object.keys(_graphqlUploadExpress).forEach(function(key) {
29
- if (key === 'default' || key === '__esModule') return
30
- exports[key] = _graphqlUploadExpress[key]
31
- })
20
+ exports.graphqlUploadExpress = _graphqlUploadExpress.graphqlUploadExpress
package/lib/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export * from './GraphQLUpload'
2
- export * from './processRequest'
3
- export * from './graphqlUploadKoa'
4
- export * from './graphqlUploadExpress'
1
+ export { GraphQLUpload } from './GraphQLUpload'
2
+ export { processRequest } from './processRequest'
3
+ export { graphqlUploadKoa } from './graphqlUploadKoa'
4
+ export { graphqlUploadExpress } from './graphqlUploadExpress'
@@ -0,0 +1,9 @@
1
+ 'use strict'
2
+
3
+ exports.__esModule = true
4
+ exports.isEnumerableObject = void 0
5
+
6
+ const isEnumerableObject = value =>
7
+ typeof value === 'object' && value !== null && !Array.isArray(value)
8
+
9
+ exports.isEnumerableObject = isEnumerableObject
@@ -0,0 +1,2 @@
1
+ export const isEnumerableObject = value =>
2
+ typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -13,19 +13,15 @@ var _httpErrors = _interopRequireDefault(require('http-errors'))
13
13
 
14
14
  var _objectPath = _interopRequireDefault(require('object-path'))
15
15
 
16
- function _interopRequireDefault(obj) {
17
- return obj && obj.__esModule ? obj : { default: obj }
18
- }
19
-
20
- const SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec'
16
+ var _constants = require('./constants')
21
17
 
22
- const isObject = value => value && value.constructor === Object
18
+ var _ignoreStream = require('./ignoreStream')
23
19
 
24
- const isString = value => typeof value === 'string' || value instanceof String
20
+ var _isEnumerableObject = require('./isEnumerableObject')
25
21
 
26
- const ignoreStream = stream => {
27
- stream.on('error', () => {})
28
- stream.resume()
22
+ // istanbul ignore next
23
+ function _interopRequireDefault(obj) {
24
+ return obj && obj.__esModule ? obj : { default: obj }
29
25
  }
30
26
 
31
27
  class Upload {
@@ -48,8 +44,7 @@ const processRequest = (
48
44
  { maxFieldSize = 1000000, maxFileSize = Infinity, maxFiles = Infinity } = {}
49
45
  ) =>
50
46
  new Promise((resolve, reject) => {
51
- let requestEnded = false
52
- let released = false
47
+ let released
53
48
  let exitError
54
49
  let currentStream
55
50
  let operations
@@ -81,6 +76,7 @@ const processRequest = (
81
76
  }
82
77
 
83
78
  const release = () => {
79
+ // istanbul ignore next
84
80
  if (released) return
85
81
  released = true
86
82
  if (map)
@@ -88,130 +84,152 @@ const processRequest = (
88
84
  if (upload.file) upload.file.capacitor.destroy()
89
85
  }
90
86
 
91
- parser.on('field', (fieldName, value) => {
92
- if (exitError) return
87
+ const abort = () => {
88
+ exit(
89
+ (0, _httpErrors.default)(
90
+ 499,
91
+ 'Request disconnected during file upload stream parsing.'
92
+ )
93
+ )
94
+ }
93
95
 
94
- switch (fieldName) {
95
- case 'operations':
96
- try {
97
- operations = JSON.parse(value)
98
- } catch (error) {
99
- return exit(
100
- (0, _httpErrors.default)(
101
- 400,
102
- `Invalid JSON in the ‘operations’ multipart field (${SPEC_URL}).`
103
- )
96
+ parser.on(
97
+ 'field',
98
+ (fieldName, value, fieldNameTruncated, valueTruncated) => {
99
+ if (exitError) return
100
+ if (valueTruncated)
101
+ return exit(
102
+ (0, _httpErrors.default)(
103
+ 413,
104
+ `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`
104
105
  )
105
- }
106
+ )
106
107
 
107
- if (!isObject(operations) && !Array.isArray(operations))
108
- return exit(
109
- (0, _httpErrors.default)(
110
- 400,
111
- `Invalid type for the ‘operations’ multipart field (${SPEC_URL}).`
112
- )
113
- )
114
- operationsPath = (0, _objectPath.default)(operations)
115
- break
116
-
117
- case 'map': {
118
- if (!operations)
119
- return exit(
120
- (0, _httpErrors.default)(
121
- 400,
122
- `Misordered multipart fields; ‘map’ should follow ‘operations’ (${SPEC_URL}).`
108
+ switch (fieldName) {
109
+ case 'operations':
110
+ try {
111
+ operations = JSON.parse(value)
112
+ } catch (error) {
113
+ return exit(
114
+ (0, _httpErrors.default)(
115
+ 400,
116
+ `Invalid JSON in the ‘operations’ multipart field (${_constants.SPEC_URL}).`
117
+ )
123
118
  )
119
+ }
120
+
121
+ if (
122
+ !(0, _isEnumerableObject.isEnumerableObject)(operations) &&
123
+ !Array.isArray(operations)
124
124
  )
125
- let parsedMap
126
-
127
- try {
128
- parsedMap = JSON.parse(value)
129
- } catch (error) {
130
- return exit(
131
- (0, _httpErrors.default)(
132
- 400,
133
- `Invalid JSON in the ‘map’ multipart field (${SPEC_URL}).`
125
+ return exit(
126
+ (0, _httpErrors.default)(
127
+ 400,
128
+ `Invalid type for the ‘operations’ multipart field (${_constants.SPEC_URL}).`
129
+ )
134
130
  )
135
- )
136
- }
131
+ operationsPath = (0, _objectPath.default)(operations)
132
+ break
137
133
 
138
- if (!isObject(parsedMap))
139
- return exit(
140
- (0, _httpErrors.default)(
141
- 400,
142
- `Invalid type for the ‘map’ multipart field (${SPEC_URL}).`
134
+ case 'map': {
135
+ if (!operations)
136
+ return exit(
137
+ (0, _httpErrors.default)(
138
+ 400,
139
+ `Misordered multipart fields; ‘map’ should follow ‘operations’ (${_constants.SPEC_URL}).`
140
+ )
143
141
  )
144
- )
145
- const mapEntries = Object.entries(parsedMap)
146
- if (mapEntries.length > maxFiles)
147
- return exit(
148
- (0, _httpErrors.default)(
149
- 413,
150
- `${maxFiles} max file uploads exceeded.`
142
+ let parsedMap
143
+
144
+ try {
145
+ parsedMap = JSON.parse(value)
146
+ } catch (error) {
147
+ return exit(
148
+ (0, _httpErrors.default)(
149
+ 400,
150
+ `Invalid JSON in the ‘map’ multipart field (${_constants.SPEC_URL}).`
151
+ )
151
152
  )
152
- )
153
- map = new Map()
153
+ }
154
154
 
155
- for (const [fieldName, paths] of mapEntries) {
156
- if (!Array.isArray(paths))
155
+ if (!(0, _isEnumerableObject.isEnumerableObject)(parsedMap))
157
156
  return exit(
158
157
  (0, _httpErrors.default)(
159
158
  400,
160
- `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${SPEC_URL}).`
159
+ `Invalid type for the ‘map’ multipart field (${_constants.SPEC_URL}).`
161
160
  )
162
161
  )
163
- map.set(fieldName, new Upload())
162
+ const mapEntries = Object.entries(parsedMap)
163
+ if (mapEntries.length > maxFiles)
164
+ return exit(
165
+ (0, _httpErrors.default)(
166
+ 413,
167
+ `${maxFiles} max file uploads exceeded.`
168
+ )
169
+ )
170
+ map = new Map()
164
171
 
165
- for (const [index, path] of paths.entries()) {
166
- if (!isString(path))
172
+ for (const [fieldName, paths] of mapEntries) {
173
+ if (!Array.isArray(paths))
167
174
  return exit(
168
175
  (0, _httpErrors.default)(
169
176
  400,
170
- `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${SPEC_URL}).`
177
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${_constants.SPEC_URL}).`
171
178
  )
172
179
  )
180
+ map.set(fieldName, new Upload())
181
+
182
+ for (const [index, path] of paths.entries()) {
183
+ if (typeof path !== 'string')
184
+ return exit(
185
+ (0, _httpErrors.default)(
186
+ 400,
187
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${_constants.SPEC_URL}).`
188
+ )
189
+ )
173
190
 
174
- try {
175
- operationsPath.set(path, map.get(fieldName).promise)
176
- } catch (error) {
177
- return exit(
178
- (0, _httpErrors.default)(
179
- 400,
180
- `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${SPEC_URL}).`
191
+ try {
192
+ operationsPath.set(path, map.get(fieldName).promise)
193
+ } catch (error) {
194
+ return exit(
195
+ (0, _httpErrors.default)(
196
+ 400,
197
+ `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${_constants.SPEC_URL}).`
198
+ )
181
199
  )
182
- )
200
+ }
183
201
  }
184
202
  }
185
- }
186
203
 
187
- resolve(operations)
204
+ resolve(operations)
205
+ }
188
206
  }
189
207
  }
190
- })
208
+ )
191
209
  parser.on('file', (fieldName, stream, filename, encoding, mimetype) => {
192
210
  if (exitError) {
193
- ignoreStream(stream)
211
+ ;(0, _ignoreStream.ignoreStream)(stream)
194
212
  return
195
213
  }
196
214
 
197
215
  if (!map) {
198
- ignoreStream(stream)
216
+ ;(0, _ignoreStream.ignoreStream)(stream)
199
217
  return exit(
200
218
  (0, _httpErrors.default)(
201
219
  400,
202
- `Misordered multipart fields; files should follow ‘map’ (${SPEC_URL}).`
220
+ `Misordered multipart fields; files should follow ‘map’ (${_constants.SPEC_URL}).`
203
221
  )
204
222
  )
205
223
  }
206
224
 
207
225
  currentStream = stream
208
226
  stream.on('end', () => {
209
- if (currentStream === stream) currentStream = null
227
+ currentStream = null
210
228
  })
211
229
  const upload = map.get(fieldName)
212
230
 
213
231
  if (!upload) {
214
- ignoreStream(stream)
232
+ ;(0, _ignoreStream.ignoreStream)(stream)
215
233
  return
216
234
  }
217
235
 
@@ -221,18 +239,17 @@ const processRequest = (
221
239
  stream.resume()
222
240
  })
223
241
  stream.on('limit', () => {
224
- if (currentStream === stream) currentStream = null
225
242
  stream.unpipe()
226
243
  capacitor.destroy(
227
244
  (0, _httpErrors.default)(
228
245
  413,
229
- 'File truncated as it exceeds the size limit.'
246
+ `File truncated as it exceeds the ${maxFileSize} byte size limit.`
230
247
  )
231
248
  )
232
249
  })
233
250
  stream.on('error', error => {
234
- if (currentStream === stream) currentStream = null
235
- stream.unpipe()
251
+ stream.unpipe() // istanbul ignore next
252
+
236
253
  capacitor.destroy(exitError || error)
237
254
  })
238
255
  stream.pipe(capacitor)
@@ -271,14 +288,14 @@ const processRequest = (
271
288
  return exit(
272
289
  (0, _httpErrors.default)(
273
290
  400,
274
- `Missing multipart field ‘operations’ (${SPEC_URL}).`
291
+ `Missing multipart field ‘operations’ (${_constants.SPEC_URL}).`
275
292
  )
276
293
  )
277
294
  if (!map)
278
295
  return exit(
279
296
  (0, _httpErrors.default)(
280
297
  400,
281
- `Missing multipart field ‘map’ (${SPEC_URL}).`
298
+ `Missing multipart field ‘map’ (${_constants.SPEC_URL}).`
282
299
  )
283
300
  )
284
301
 
@@ -291,17 +308,9 @@ const processRequest = (
291
308
  parser.once('error', exit)
292
309
  response.once('finish', release)
293
310
  response.once('close', release)
311
+ request.once('close', abort)
294
312
  request.once('end', () => {
295
- requestEnded = true
296
- })
297
- request.once('close', () => {
298
- if (!requestEnded)
299
- exit(
300
- (0, _httpErrors.default)(
301
- 499,
302
- 'Request disconnected during file upload stream parsing.'
303
- )
304
- )
313
+ request.removeListener('close', abort)
305
314
  })
306
315
  request.pipe(parser)
307
316
  })
@@ -3,16 +3,9 @@ import Busboy from 'busboy'
3
3
  import { WriteStream } from 'fs-capacitor'
4
4
  import createError from 'http-errors'
5
5
  import objectPath from 'object-path'
6
- const SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec'
7
-
8
- const isObject = value => value && value.constructor === Object
9
-
10
- const isString = value => typeof value === 'string' || value instanceof String
11
-
12
- const ignoreStream = stream => {
13
- stream.on('error', () => {})
14
- stream.resume()
15
- }
6
+ import { SPEC_URL } from './constants'
7
+ import { ignoreStream } from './ignoreStream'
8
+ import { isEnumerableObject } from './isEnumerableObject'
16
9
 
17
10
  class Upload {
18
11
  constructor() {
@@ -34,8 +27,7 @@ export const processRequest = (
34
27
  { maxFieldSize = 1000000, maxFileSize = Infinity, maxFiles = Infinity } = {}
35
28
  ) =>
36
29
  new Promise((resolve, reject) => {
37
- let requestEnded = false
38
- let released = false
30
+ let released
39
31
  let exitError
40
32
  let currentStream
41
33
  let operations
@@ -67,6 +59,7 @@ export const processRequest = (
67
59
  }
68
60
 
69
61
  const release = () => {
62
+ // istanbul ignore next
70
63
  if (released) return
71
64
  released = true
72
65
  if (map)
@@ -74,103 +67,122 @@ export const processRequest = (
74
67
  if (upload.file) upload.file.capacitor.destroy()
75
68
  }
76
69
 
77
- parser.on('field', (fieldName, value) => {
78
- if (exitError) return
70
+ const abort = () => {
71
+ exit(
72
+ createError(
73
+ 499,
74
+ 'Request disconnected during file upload stream parsing.'
75
+ )
76
+ )
77
+ }
79
78
 
80
- switch (fieldName) {
81
- case 'operations':
82
- try {
83
- operations = JSON.parse(value)
84
- } catch (error) {
85
- return exit(
86
- createError(
87
- 400,
88
- `Invalid JSON in the ‘operations’ multipart field (${SPEC_URL}).`
89
- )
79
+ parser.on(
80
+ 'field',
81
+ (fieldName, value, fieldNameTruncated, valueTruncated) => {
82
+ if (exitError) return
83
+ if (valueTruncated)
84
+ return exit(
85
+ createError(
86
+ 413,
87
+ `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`
90
88
  )
91
- }
89
+ )
92
90
 
93
- if (!isObject(operations) && !Array.isArray(operations))
94
- return exit(
95
- createError(
96
- 400,
97
- `Invalid type for the ‘operations’ multipart field (${SPEC_URL}).`
91
+ switch (fieldName) {
92
+ case 'operations':
93
+ try {
94
+ operations = JSON.parse(value)
95
+ } catch (error) {
96
+ return exit(
97
+ createError(
98
+ 400,
99
+ `Invalid JSON in the ‘operations’ multipart field (${SPEC_URL}).`
100
+ )
98
101
  )
99
- )
100
- operationsPath = objectPath(operations)
101
- break
102
+ }
102
103
 
103
- case 'map': {
104
- if (!operations)
105
- return exit(
106
- createError(
107
- 400,
108
- `Misordered multipart fields; ‘map’ should follow ‘operations’ (${SPEC_URL}).`
104
+ if (!isEnumerableObject(operations) && !Array.isArray(operations))
105
+ return exit(
106
+ createError(
107
+ 400,
108
+ `Invalid type for the ‘operations’ multipart field (${SPEC_URL}).`
109
+ )
109
110
  )
110
- )
111
- let parsedMap
111
+ operationsPath = objectPath(operations)
112
+ break
112
113
 
113
- try {
114
- parsedMap = JSON.parse(value)
115
- } catch (error) {
116
- return exit(
117
- createError(
118
- 400,
119
- `Invalid JSON in the ‘map’ multipart field (${SPEC_URL}).`
114
+ case 'map': {
115
+ if (!operations)
116
+ return exit(
117
+ createError(
118
+ 400,
119
+ `Misordered multipart fields; ‘map’ should follow ‘operations’ (${SPEC_URL}).`
120
+ )
120
121
  )
121
- )
122
- }
122
+ let parsedMap
123
123
 
124
- if (!isObject(parsedMap))
125
- return exit(
126
- createError(
127
- 400,
128
- `Invalid type for the ‘map’ multipart field (${SPEC_URL}).`
124
+ try {
125
+ parsedMap = JSON.parse(value)
126
+ } catch (error) {
127
+ return exit(
128
+ createError(
129
+ 400,
130
+ `Invalid JSON in the ‘map’ multipart field (${SPEC_URL}).`
131
+ )
129
132
  )
130
- )
131
- const mapEntries = Object.entries(parsedMap)
132
- if (mapEntries.length > maxFiles)
133
- return exit(
134
- createError(413, `${maxFiles} max file uploads exceeded.`)
135
- )
136
- map = new Map()
133
+ }
137
134
 
138
- for (const [fieldName, paths] of mapEntries) {
139
- if (!Array.isArray(paths))
135
+ if (!isEnumerableObject(parsedMap))
140
136
  return exit(
141
137
  createError(
142
138
  400,
143
- `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${SPEC_URL}).`
139
+ `Invalid type for the ‘map’ multipart field (${SPEC_URL}).`
144
140
  )
145
141
  )
146
- map.set(fieldName, new Upload())
142
+ const mapEntries = Object.entries(parsedMap)
143
+ if (mapEntries.length > maxFiles)
144
+ return exit(
145
+ createError(413, `${maxFiles} max file uploads exceeded.`)
146
+ )
147
+ map = new Map()
147
148
 
148
- for (const [index, path] of paths.entries()) {
149
- if (!isString(path))
149
+ for (const [fieldName, paths] of mapEntries) {
150
+ if (!Array.isArray(paths))
150
151
  return exit(
151
152
  createError(
152
153
  400,
153
- `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${SPEC_URL}).`
154
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${SPEC_URL}).`
154
155
  )
155
156
  )
157
+ map.set(fieldName, new Upload())
156
158
 
157
- try {
158
- operationsPath.set(path, map.get(fieldName).promise)
159
- } catch (error) {
160
- return exit(
161
- createError(
162
- 400,
163
- `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${SPEC_URL}).`
159
+ for (const [index, path] of paths.entries()) {
160
+ if (typeof path !== 'string')
161
+ return exit(
162
+ createError(
163
+ 400,
164
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${SPEC_URL}).`
165
+ )
164
166
  )
165
- )
167
+
168
+ try {
169
+ operationsPath.set(path, map.get(fieldName).promise)
170
+ } catch (error) {
171
+ return exit(
172
+ createError(
173
+ 400,
174
+ `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${SPEC_URL}).`
175
+ )
176
+ )
177
+ }
166
178
  }
167
179
  }
168
- }
169
180
 
170
- resolve(operations)
181
+ resolve(operations)
182
+ }
171
183
  }
172
184
  }
173
- })
185
+ )
174
186
  parser.on('file', (fieldName, stream, filename, encoding, mimetype) => {
175
187
  if (exitError) {
176
188
  ignoreStream(stream)
@@ -189,7 +201,7 @@ export const processRequest = (
189
201
 
190
202
  currentStream = stream
191
203
  stream.on('end', () => {
192
- if (currentStream === stream) currentStream = null
204
+ currentStream = null
193
205
  })
194
206
  const upload = map.get(fieldName)
195
207
 
@@ -204,15 +216,17 @@ export const processRequest = (
204
216
  stream.resume()
205
217
  })
206
218
  stream.on('limit', () => {
207
- if (currentStream === stream) currentStream = null
208
219
  stream.unpipe()
209
220
  capacitor.destroy(
210
- createError(413, 'File truncated as it exceeds the size limit.')
221
+ createError(
222
+ 413,
223
+ `File truncated as it exceeds the ${maxFileSize} byte size limit.`
224
+ )
211
225
  )
212
226
  })
213
227
  stream.on('error', error => {
214
- if (currentStream === stream) currentStream = null
215
- stream.unpipe()
228
+ stream.unpipe() // istanbul ignore next
229
+
216
230
  capacitor.destroy(exitError || error)
217
231
  })
218
232
  stream.pipe(capacitor)
@@ -264,17 +278,9 @@ export const processRequest = (
264
278
  parser.once('error', exit)
265
279
  response.once('finish', release)
266
280
  response.once('close', release)
281
+ request.once('close', abort)
267
282
  request.once('end', () => {
268
- requestEnded = true
269
- })
270
- request.once('close', () => {
271
- if (!requestEnded)
272
- exit(
273
- createError(
274
- 499,
275
- 'Request disconnected during file upload stream parsing.'
276
- )
277
- )
283
+ request.removeListener('close', abort)
278
284
  })
279
285
  request.pipe(parser)
280
286
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "graphql-upload",
3
- "version": "8.0.7",
3
+ "version": "8.1.0",
4
4
  "description": "Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -25,45 +25,47 @@
25
25
  ],
26
26
  "files": [
27
27
  "lib",
28
- "!lib/test.*"
28
+ "!*.test.*",
29
+ "!test-helpers"
29
30
  ],
30
31
  "main": "lib",
31
32
  "engines": {
32
33
  "node": ">=8.5"
33
34
  },
34
- "browserslist": "node 8.5",
35
+ "browserslist": "node >= 8.5",
35
36
  "peerDependencies": {
36
37
  "graphql": "0.13.1 - 14"
37
38
  },
38
39
  "dependencies": {
39
40
  "busboy": "^0.3.1",
40
41
  "fs-capacitor": "^2.0.4",
41
- "http-errors": "^1.7.2",
42
+ "http-errors": "^1.7.3",
42
43
  "object-path": "^0.11.4"
43
44
  },
44
45
  "devDependencies": {
45
- "@babel/cli": "^7.4.4",
46
- "@babel/core": "^7.4.5",
47
- "@babel/preset-env": "^7.4.5",
48
- "babel-eslint": "^10.0.1",
49
- "eslint": "^5.16.0",
50
- "eslint-config-env": "^6.0.0",
51
- "eslint-config-prettier": "^4.3.0",
52
- "eslint-plugin-import": "^2.17.3",
53
- "eslint-plugin-import-order-alphabetical": "^0.0.2",
54
- "eslint-plugin-node": "^9.1.0",
55
- "eslint-plugin-prettier": "^3.1.0",
46
+ "@babel/cli": "^7.6.3",
47
+ "@babel/core": "^7.6.3",
48
+ "@babel/preset-env": "^7.6.3",
49
+ "babel-eslint": "^10.0.3",
50
+ "eslint": "^6.5.1",
51
+ "eslint-config-env": "^9.1.0",
52
+ "eslint-config-prettier": "^6.4.0",
53
+ "eslint-plugin-import": "^2.18.2",
54
+ "eslint-plugin-import-order-alphabetical": "^1.0.0",
55
+ "eslint-plugin-jsdoc": "^15.9.10",
56
+ "eslint-plugin-node": "^10.0.0",
57
+ "eslint-plugin-prettier": "^3.1.1",
56
58
  "express": "^4.17.1",
57
59
  "express-async-handler": "^1.1.4",
58
- "form-data": "^2.3.3",
59
- "graphql": "^14.3.1",
60
- "husky": "^2.4.1",
61
- "jsdoc-md": "^3.0.0",
62
- "koa": "^2.7.0",
63
- "lint-staged": "^8.2.0",
60
+ "form-data": "^2.5.1",
61
+ "graphql": "^14.5.8",
62
+ "husky": "^3.0.8",
63
+ "jsdoc-md": "^4.0.1",
64
+ "koa": "^2.8.2",
65
+ "lint-staged": "^9.4.2",
64
66
  "node-fetch": "^2.6.0",
65
67
  "prettier": "^1.18.2",
66
- "tap": "^14.2.2"
68
+ "tap": "^14.6.9"
67
69
  },
68
70
  "scripts": {
69
71
  "prepare": "npm run prepare:clean && npm run prepare:mjs && npm run prepare:js && npm run prepare:jsdoc && npm run prepare:prettier",
@@ -72,11 +74,10 @@
72
74
  "prepare:js": "babel src -d lib",
73
75
  "prepare:jsdoc": "jsdoc-md",
74
76
  "prepare:prettier": "prettier 'lib/**/*.{mjs,js}' readme.md --write",
75
- "test": "npm run test:eslint && npm run test:prettier && npm run test:mjs && npm run test:js",
77
+ "test": "npm run test:eslint && npm run test:prettier && npm run test:tap",
76
78
  "test:eslint": "eslint . --ext mjs,js",
77
79
  "test:prettier": "prettier '**/*.{json,yml,md}' -l",
78
- "test:mjs": "node --experimental-modules --no-warnings lib/test | tap-mocha-reporter classic",
79
- "test:js": "node lib/test | tap-mocha-reporter classic",
80
+ "test:tap": "tap --test-ignore=src --100",
80
81
  "prepublishOnly": "npm test"
81
82
  }
82
83
  }
package/readme.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # graphql-upload
4
4
 
5
- [![npm version](https://badgen.net/npm/v/graphql-upload)](https://npm.im/graphql-upload) [![Build status](https://travis-ci.org/jaydenseric/graphql-upload.svg?branch=master)](https://travis-ci.org/jaydenseric/graphql-upload)
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
7
  Middleware and an [`Upload` scalar](#class-graphqlupload) 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
 
@@ -17,6 +17,7 @@ The following environments are known to be compatible:
17
17
  - Native ESM with [`--experimental-modules`](https://nodejs.org/api/esm.html#esm_enabling)
18
18
  - [Koa](https://koajs.com)
19
19
  - [`graphql-api-koa`](https://npm.im/graphql-api-koa)
20
+ - [`koa-graphql`](https://npm.im/koa-graphql)
20
21
  - [`apollo-server-koa`](https://npm.im/apollo-server-koa) (inbuilt)
21
22
  - [Express](https://expressjs.com)
22
23
  - [`express-graphql`](https://npm.im/express-graphql)
@@ -67,17 +68,13 @@ The [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-mult
67
68
  ### Table of contents
68
69
 
69
70
  - [class GraphQLUpload](#class-graphqlupload)
70
- - [Examples](#examples)
71
71
  - [function graphqlUploadExpress](#function-graphqluploadexpress)
72
- - [Examples](#examples-1)
73
72
  - [function graphqlUploadKoa](#function-graphqluploadkoa)
74
- - [Examples](#examples-2)
75
73
  - [function processRequest](#function-processrequest)
76
- - [Examples](#examples-3)
77
74
  - [type FileUpload](#type-fileupload)
78
75
  - [type GraphQLOperation](#type-graphqloperation)
79
- - [See](#see)
80
- - [type UploadOptions](#type-uploadoptions)
76
+ - [type ProcessRequestFunction](#type-processrequestfunction)
77
+ - [type ProcessRequestOptions](#type-processrequestoptions)
81
78
 
82
79
  ### class GraphQLUpload
83
80
 
@@ -137,13 +134,14 @@ _A manually constructed schema with an image upload mutation._
137
134
 
138
135
  ### function graphqlUploadExpress
139
136
 
140
- Creates [Express](https://expressjs.com) middleware that processes GraphQL multipart requests 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.
137
+ 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.
141
138
 
142
- | Parameter | Type | Description |
143
- | :-------- | :----------------------------------- | :---------------------- |
144
- | `options` | [UploadOptions](#type-uploadoptions) | GraphQL upload options. |
139
+ | Parameter | Type | Description |
140
+ | :-- | :-- | :-- |
141
+ | `options` | [ProcessRequestOptions](#type-processrequestoptions) | Middleware options. Any [`ProcessRequestOptions`](#type-processrequestoptions) can be used. |
142
+ | `options.processRequest` | [ProcessRequestFunction](#type-processrequestfunction)? = [processRequest](#function-processrequest) | Used to process [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec). |
145
143
 
146
- **Returns:** function — Express middleware.
144
+ **Returns:** Function — Express middleware.
147
145
 
148
146
  #### Examples
149
147
 
@@ -168,13 +166,14 @@ _Basic [`express-graphql`](https://npm.im/express-graphql) setup._
168
166
 
169
167
  ### function graphqlUploadKoa
170
168
 
171
- Creates [Koa](https://koajs.com) middleware that processes GraphQL multipart requests 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.
169
+ 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.
172
170
 
173
- | Parameter | Type | Description |
174
- | :-------- | :----------------------------------- | :---------------------- |
175
- | `options` | [UploadOptions](#type-uploadoptions) | GraphQL upload options. |
171
+ | Parameter | Type | Description |
172
+ | :-- | :-- | :-- |
173
+ | `options` | [ProcessRequestOptions](#type-processrequestoptions) | Middleware options. Any [`ProcessRequestOptions`](#type-processrequestoptions) can be used. |
174
+ | `options.processRequest` | [ProcessRequestFunction](#type-processrequestfunction)? = [processRequest](#function-processrequest) | Used to process [GraphQL multipart requests](https://github.com/jaydenseric/graphql-multipart-request-spec). |
176
175
 
177
- **Returns:** function — Koa middleware.
176
+ **Returns:** Function — Koa middleware.
178
177
 
179
178
  #### Examples
180
179
 
@@ -199,15 +198,9 @@ _Basic [`graphql-api-koa`](https://npm.im/graphql-api-koa) setup._
199
198
 
200
199
  ### function processRequest
201
200
 
202
- Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec). Used in [`graphqlUploadKoa`](#function-graphqluploadkoa) and [`graphqlUploadExpress`](#function-graphqluploadexpress) and can be used to create custom middleware.
201
+ Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec). 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.
203
202
 
204
- | Parameter | Type | Description |
205
- | :-- | :-- | :-- |
206
- | `request` | IncomingMessage | [Node.js HTTP server request instance](https://nodejs.org/api/http.html#http_class_http_incomingmessage). |
207
- | `response` | ServerResponse | [Node.js HTTP server response instance](https://nodejs.org/api/http.html#http_class_http_serverresponse). |
208
- | `options` | [UploadOptions](#type-uploadoptions)? | GraphQL upload options. |
209
-
210
- **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).
203
+ **Type:** [ProcessRequestFunction](#type-processrequestfunction)
211
204
 
212
205
  #### Examples
213
206
 
@@ -223,14 +216,14 @@ _How to import._
223
216
 
224
217
  File upload details, resolved from an [`Upload` scalar](#class-graphqlupload) promise.
225
218
 
226
- **Type:** Object
219
+ **Type:** object
227
220
 
228
221
  | Property | Type | Description |
229
222
  | :-- | :-- | :-- |
230
223
  | `filename` | string | File name. |
231
224
  | `mimetype` | string | File MIME type. Provided by the client and can’t be trusted. |
232
225
  | `encoding` | string | File stream transfer encoding. |
233
- | `createReadStream` | function | Returns a Node.js readable stream of the file contents, for processing and storing the file. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request. |
226
+ | `createReadStream` | Function | Returns a Node.js readable stream of the file contents, for processing and storing the file. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request. |
234
227
 
235
228
  ---
236
229
 
@@ -238,13 +231,13 @@ File upload details, resolved from an [`Upload` scalar](#class-graphqlupload) pr
238
231
 
239
232
  A GraphQL operation object in a shape that can be consumed and executed by most GraphQL servers.
240
233
 
241
- **Type:** Object
234
+ **Type:** object
242
235
 
243
236
  | Property | Type | Description |
244
237
  | :-- | :-- | :-- |
245
238
  | `query` | string | GraphQL document containing queries and fragments. |
246
- | `operationName` | string \| null? | GraphQL document operation name to execute. |
247
- | `variables` | object \| null? | GraphQL document operation variables and values map. |
239
+ | `operationName` | string \| `null`? | GraphQL document operation name to execute. |
240
+ | `variables` | object \| `null`? | GraphQL document operation variables and values map. |
248
241
 
249
242
  #### See
250
243
 
@@ -253,14 +246,30 @@ A GraphQL operation object in a shape that can be consumed and executed by most
253
246
 
254
247
  ---
255
248
 
256
- ### type UploadOptions
249
+ ### type ProcessRequestFunction
250
+
251
+ Processes a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
252
+
253
+ **Type:** Function
254
+
255
+ | Parameter | Type | Description |
256
+ | :-- | :-- | :-- |
257
+ | `request` | IncomingMessage | [Node.js HTTP server request instance](https://nodejs.org/api/http.html#http_class_http_incomingmessage). |
258
+ | `response` | ServerResponse | [Node.js HTTP server response instance](https://nodejs.org/api/http.html#http_class_http_serverresponse). |
259
+ | `options` | [ProcessRequestOptions](#type-processrequestoptions)? | Options for processing the request. |
260
+
261
+ **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).
262
+
263
+ ---
264
+
265
+ ### type ProcessRequestOptions
257
266
 
258
- GraphQL upload server options, mostly relating to security, performance and limits.
267
+ Options for processing a [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec); mostly relating to security, performance and limits.
259
268
 
260
- **Type:** Object
269
+ **Type:** object
261
270
 
262
271
  | Property | Type | Description |
263
272
  | :-- | :-- | :-- |
264
273
  | `maxFieldSize` | number? = `1000000` | Maximum allowed non-file multipart form field size in bytes; enough for your queries. |
265
- | `maxFileSize` | number? = `Infinity` | Maximum allowed file size in bytes. |
266
- | `maxFiles` | number? = `Infinity` | Maximum allowed number of files. |
274
+ | `maxFileSize` | number? = Infinity | Maximum allowed file size in bytes. |
275
+ | `maxFiles` | number? = Infinity | Maximum allowed number of files. |