From 95d2b7e33267ffda89ced48b37c053de0fb97edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Musil?= Date: Fri, 14 Apr 2023 10:18:42 +0200 Subject: [PATCH] fix: handle undefined and null in form-data field value --- CHANGELOG.md | 3 +++ src/node/fetch/fetch.node.test.ts | 32 +++++++++++++++++++++++++++++++ src/node/fetch/fetch.node.ts | 4 +++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ffd635f..64984225 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Fixed +- Do not set form-data field if value is `null` or `undefined` - [#342](https://github.com/superfaceai/one-sdk-js/pull/342) + ### Changed - Updated vm2 to 3.9.16 - [#341](https://github.com/superfaceai/one-sdk-js/pull/341) diff --git a/src/node/fetch/fetch.node.test.ts b/src/node/fetch/fetch.node.test.ts index bc8477bd..d16e7419 100644 --- a/src/node/fetch/fetch.node.test.ts +++ b/src/node/fetch/fetch.node.test.ts @@ -399,6 +399,38 @@ describe('NodeFetch', () => { ).toBe(2); }); }); + + describe('field value is undefined', () => { + it('does not add field to FormData', async () => { + await fetchInstance.fetch(`${mockServer.url}/test`, { + method: 'POST', + body: { _type: 'formdata', data: { undefinedField: undefined } }, + }); + + expect( + (jest.mocked(fetch).mock.calls[0][1]?.body as unknown as FormData) + .getBuffer() + .toString() + .match(/undefinedField/g) + ).toBeNull(); + }); + }); + + describe('field value is null', () => { + it('does not add field to FormData', async () => { + await fetchInstance.fetch(`${mockServer.url}/test`, { + method: 'POST', + body: { _type: 'formdata', data: { nullField: null } }, + }); + + expect( + (jest.mocked(fetch).mock.calls[0][1]?.body as unknown as FormData) + .getBuffer() + .toString() + .match(/nullField/g) + ).toBeNull(); + }); + }); }); // this test works under the assumption that node-fetch returns multi-valued headers as arrays diff --git a/src/node/fetch/fetch.node.ts b/src/node/fetch/fetch.node.ts index 18646dc4..7843181e 100644 --- a/src/node/fetch/fetch.node.ts +++ b/src/node/fetch/fetch.node.ts @@ -268,7 +268,9 @@ export class NodeFetch implements IFetch, Interceptable, AuthCache { if (data) { Object.entries(data).forEach(([key, value]) => { - if (Array.isArray(value)) { + if (value === undefined || value === null) { + return; + } else if (Array.isArray(value)) { value.forEach(item => formData.append(key, item)); } else if (isBinaryData(value)) { if (isBinaryDataMeta(value)) {