Skip to content

Commit

Permalink
fix(Webhook Node): Backward compatible form-data parsing for non-arra…
Browse files Browse the repository at this point in the history
  • Loading branch information
netroy committed Oct 10, 2023
1 parent 7ed466d commit 6479eb1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
16 changes: 11 additions & 5 deletions packages/cli/src/WebhookHelpers.ts
Expand Up @@ -190,6 +190,15 @@ export function encodeWebhookResponse(
return response;
}

const normalizeFormData = <T>(values: Record<string, T | T[]>) => {
for (const key in values) {
const value = values[key];
if (Array.isArray(value) && value.length === 1) {
values[key] = value[0];
}
}
};

/**
* Executes a webhook
*/
Expand Down Expand Up @@ -310,11 +319,8 @@ export async function executeWebhook(
});
req.body = await new Promise((resolve) => {
form.parse(req, async (err, data, files) => {
for (const key in data) {
if (Array.isArray(data[key]) && data[key].length === 1) {
data[key] = data[key][0];
}
}
normalizeFormData(data);
normalizeFormData(files);
resolve({ data, files });
});
});
Expand Down
19 changes: 10 additions & 9 deletions packages/cli/test/integration/webhooks.api.test.ts
Expand Up @@ -116,20 +116,21 @@ describe('Webhook API', () => {
.field('field1', 'value1')
.field('field2', 'value2')
.field('field2', 'value3')
.attach('file', Buffer.from('random-text'))
.attach('file1', Buffer.from('random-text'))
.attach('file2', Buffer.from('random-text'))
.attach('file2', Buffer.from('random-text'))
.set('content-type', 'multipart/form-data');

expect(response.statusCode).toEqual(200);
expect(response.body.type).toEqual('multipart/form-data');
const {
data,
files: {
file: [file],
},
} = response.body.body;
const { data, files } = response.body.body;
expect(data).toEqual({ field1: 'value1', field2: ['value2', 'value3'] });
expect(file.mimetype).toEqual('application/octet-stream');
expect(readFileSync(file.filepath, 'utf-8')).toEqual('random-text');

expect(files.file1).not.toBeInstanceOf(Array);
expect(files.file1.mimetype).toEqual('application/octet-stream');
expect(readFileSync(files.file1.filepath, 'utf-8')).toEqual('random-text');
expect(files.file2).toBeInstanceOf(Array);
expect(files.file2.length).toEqual(2);
});
});

Expand Down

0 comments on commit 6479eb1

Please sign in to comment.