Skip to content

Commit

Permalink
fix: handle errors from the request body stream
Browse files Browse the repository at this point in the history
  • Loading branch information
mdmitry01 committed Nov 18, 2021
1 parent 0284826 commit 5241cec
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
9 changes: 5 additions & 4 deletions src/body.js
Expand Up @@ -6,7 +6,7 @@
*/

import Stream, {PassThrough} from 'node:stream';
import {types, deprecate} from 'node:util';
import {types, deprecate, promisify} from 'node:util';

import Blob from 'fetch-blob';
import {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js';
Expand All @@ -15,6 +15,7 @@ import {FetchError} from './errors/fetch-error.js';
import {FetchBaseError} from './errors/base.js';
import {isBlob, isURLSearchParameters} from './utils/is.js';

const pipeline = promisify(Stream.pipeline);
const INTERNALS = Symbol('Body internals');

/**
Expand Down Expand Up @@ -379,14 +380,14 @@ export const getTotalBytes = request => {
*
* @param {Stream.Writable} dest The stream to write to.
* @param obj.body Body object from the Body instance.
* @returns {void}
* @returns {Promise<void>}
*/
export const writeToStream = (dest, {body}) => {
export const writeToStream = async (dest, {body}) => {
if (body === null) {
// Body is null
dest.end();
} else {
// Body is stream
body.pipe(dest);
await pipeline(body, dest);
}
};
2 changes: 1 addition & 1 deletion src/index.js
Expand Up @@ -291,7 +291,7 @@ export default async function fetch(url, options_) {
resolve(response);
});

writeToStream(request_, request);
writeToStream(request_, request).catch(reject);
});
}

Expand Down
16 changes: 16 additions & 0 deletions test/main.js
Expand Up @@ -1456,6 +1456,22 @@ describe('node-fetch', () => {
});
});

it('should reject if the request body stream emits an error', () => {
const url = `${base}inspect`;
const requestBody = new stream.PassThrough();
const options = {
method: 'POST',
body: requestBody
};
const expectedError = new Error('an error');
setImmediate(() => {
requestBody.emit('error', expectedError);
});
return fetch(url, options).catch(error => {
expect(error).to.equal(expectedError);
});
});

it('should allow POST request with form-data as body', () => {
const form = new FormData();
form.append('a', '1');
Expand Down

0 comments on commit 5241cec

Please sign in to comment.