Skip to content

Commit

Permalink
fix(fetch): respect filesLimit even with fieldsFirst
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Sep 7, 2022
1 parent 7d4b344 commit 7f37b6d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 18 deletions.
5 changes: 5 additions & 0 deletions .changeset/tasty-seahorses-grin.md
@@ -0,0 +1,5 @@
---
'@whatwg-node/fetch': patch
---

fix(fetch): respect filesLimit even with fieldsFirst
44 changes: 26 additions & 18 deletions packages/fetch/dist/getFormDataMethod.js
Expand Up @@ -10,9 +10,6 @@ module.exports = function getFormDataMethod(File, limits) {
fileStream,
formData,
}) {
if (fileStream._consumedAsFile) {
return Promise.resolve(formData.get(name));
}
return new Promise((resolve, reject) => {
const chunks = [];
fileStream.on('limit', () => {
Expand All @@ -22,9 +19,11 @@ module.exports = function getFormDataMethod(File, limits) {
chunks.push(chunk);
})
fileStream.on('close', () => {
if (fileStream.truncated) {
reject(new Error(`File size limit exceeded: ${limits.fileSize} bytes`));
}
const file = new File(chunks, filename, { type: mimeType });
formData.set(name, file);
fileStream._consumedAsFile = true;
resolve(file);
});
})
Expand Down Expand Up @@ -58,6 +57,7 @@ module.exports = function getFormDataMethod(File, limits) {
reject(new Error(`Fields limit exceeded: ${limits.fields}`));
})
bb.on('file', (name, fileStream, { filename, mimeType }) => {
let file$;
if (limits && limits.fieldsFirst) {
resolve(formData);
const fakeFileObj = {
Expand All @@ -80,24 +80,32 @@ module.exports = function getFormDataMethod(File, limits) {
throw new Error(`Cannot slice file before consuming the stream.`);
case 'text':
case 'arrayBuffer':
return () => consumeStreamAsFile({
name,
filename,
mimeType,
fileStream,
formData,
}).then(file => file[prop]())
return () => {
if (!file$) {
file$ = consumeStreamAsFile({
name,
filename,
mimeType,
fileStream,
formData,
})
}
return file$.then(file => file[prop]());
}
}
},
}))
} else {
consumeStreamAsFile({
name,
filename,
mimeType,
fileStream,
formData,
}).catch(err => reject(err));
if (!file$) {
file$ = consumeStreamAsFile({
name,
filename,
mimeType,
fileStream,
formData,
})
}
file$.catch(reject);
}
})
bb.on('filesLimit', () => {
Expand Down

0 comments on commit 7f37b6d

Please sign in to comment.