Skip to content

Commit

Permalink
fix(http): support for JSON array payloads (#564)
Browse files Browse the repository at this point in the history
  • Loading branch information
fergusean authored May 2, 2024
1 parent 8c77a8e commit feeeaa6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/http/src/request-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ function parseBody(
if (err) {
reject(err);
} else {
for (const [name, file] of Object.entries(files) as any) {
const fileEntries = Object.entries(files);

// formidable turns JSON arrays into numerically keyed objects, so we convert them back
if ('0' in fields && fileEntries.length === 0 && Object.keys(fields).every((key, idx) => parseInt(key) === idx)) {
return resolve(Object.values(fields));
}

for (const [name, file] of fileEntries as any) {
if (!file.filepath || 'string' !== typeof file.filepath) continue;
if (!file.size || 'number' !== typeof file.size) continue;
if (file.lastModifiedDate && !(file.lastModifiedDate instanceof Date)) continue;
Expand Down
12 changes: 12 additions & 0 deletions packages/http/tests/router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,15 @@ test('BodyValidation', async () => {

throw new HttpBadRequestError('Invalid: ' + user.error.getErrorMessageForPath('username'));
}

@http.POST('/action4')
action4(users: HttpBodyValidation<AddUserDto[]>): User[] {
if (users.valid()) {
return users.value;
}

throw new HttpBadRequestError('Invalid: ' + users.error.getErrorMessageForPath('0.username'));
}
}

const httpKernel = createHttpKernel([Controller]);
Expand All @@ -958,6 +967,9 @@ test('BodyValidation', async () => {

expect((await httpKernel.request(HttpRequest.POST('/action3').json({ username: 'Peter' }))).json).toEqual({ username: 'Peter' });
expect((await httpKernel.request(HttpRequest.POST('/action3').json({ username: 'Pe' }))).json.message).toEqual('Invalid: username(minLength): Min length is 3 caused by value "Pe"');

expect((await httpKernel.request(HttpRequest.POST('/action4').json([{ username: 'Peter' }]))).json).toEqual([{ username: 'Peter' }]);
expect((await httpKernel.request(HttpRequest.POST('/action4').json([{ username: 'Pe' }]))).json.message).toEqual('Invalid: 0.username(minLength): Min length is 3 caused by value "Pe"');
});

test('unpopulated entity without type information', async () => {
Expand Down

0 comments on commit feeeaa6

Please sign in to comment.