Skip to content

Commit feeeaa6

Browse files
authored
fix(http): support for JSON array payloads (#564)
1 parent 8c77a8e commit feeeaa6

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

packages/http/src/request-parser.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,14 @@ function parseBody(
3939
if (err) {
4040
reject(err);
4141
} else {
42-
for (const [name, file] of Object.entries(files) as any) {
42+
const fileEntries = Object.entries(files);
43+
44+
// formidable turns JSON arrays into numerically keyed objects, so we convert them back
45+
if ('0' in fields && fileEntries.length === 0 && Object.keys(fields).every((key, idx) => parseInt(key) === idx)) {
46+
return resolve(Object.values(fields));
47+
}
48+
49+
for (const [name, file] of fileEntries as any) {
4350
if (!file.filepath || 'string' !== typeof file.filepath) continue;
4451
if (!file.size || 'number' !== typeof file.size) continue;
4552
if (file.lastModifiedDate && !(file.lastModifiedDate instanceof Date)) continue;

packages/http/tests/router.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,15 @@ test('BodyValidation', async () => {
945945

946946
throw new HttpBadRequestError('Invalid: ' + user.error.getErrorMessageForPath('username'));
947947
}
948+
949+
@http.POST('/action4')
950+
action4(users: HttpBodyValidation<AddUserDto[]>): User[] {
951+
if (users.valid()) {
952+
return users.value;
953+
}
954+
955+
throw new HttpBadRequestError('Invalid: ' + users.error.getErrorMessageForPath('0.username'));
956+
}
948957
}
949958

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

959968
expect((await httpKernel.request(HttpRequest.POST('/action3').json({ username: 'Peter' }))).json).toEqual({ username: 'Peter' });
960969
expect((await httpKernel.request(HttpRequest.POST('/action3').json({ username: 'Pe' }))).json.message).toEqual('Invalid: username(minLength): Min length is 3 caused by value "Pe"');
970+
971+
expect((await httpKernel.request(HttpRequest.POST('/action4').json([{ username: 'Peter' }]))).json).toEqual([{ username: 'Peter' }]);
972+
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"');
961973
});
962974

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

0 commit comments

Comments
 (0)