Skip to content

Commit

Permalink
Merge pull request #342 from superfaceai/fix/formdata_with_undefined_…
Browse files Browse the repository at this point in the history
…as_field_value

Handle undefined and null in form-data field value
  • Loading branch information
freaz authored Apr 17, 2023
2 parents 8b09aaf + 95d2b7e commit e67227a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
32 changes: 32 additions & 0 deletions src/node/fetch/fetch.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/node/fetch/fetch.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down

0 comments on commit e67227a

Please sign in to comment.