Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure JSON in form-data field is parsed IFF it is an object or array #730

Merged
merged 1 commit into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/middlewares/openapi.request.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ export class RequestValidator {
body: req.body,
};
const schemaBody = <any>validator?.schemaBody;

if (contentType.mediaType === 'multipart/form-data') {
this.multipartNested(req, schemaBody);
}

const discriminator = schemaBody?.properties?.body?._discriminator;
const discriminatorValidator = this.discriminatorValidator(
req,
Expand Down Expand Up @@ -182,6 +187,21 @@ export class RequestValidator {
};
}

private multipartNested(req, schemaBody) {
Object.keys(req.body).forEach((key) => {
const value = req.body[key];
const type = schemaBody?.properties?.body?.properties[key]?.type;
if (['array', 'object'].includes(type)) {
try {
req.body[key] = JSON.parse(value);
} catch (e) {
// NOOP
}
}
})
return null;
}

private discriminatorValidator(req, discriminator) {
if (discriminator) {
const { options, property, validators } = discriminator;
Expand Down
7 changes: 7 additions & 0 deletions test/common/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,13 @@ paths:
description: The photo
type: string
format: binary
array_with_objects:
type: array
items:
type: object
properties:
foo:
type: string
required: true
responses:
201:
Expand Down
7 changes: 7 additions & 0 deletions test/multipart.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,18 @@ describe('a multipart request', () => {
});

it('should validate multipart file and metadata', async () => {
const array_with_objects = JSON.stringify([
{
foo: 'bar'
}
]);

await request(app)
.post(`${app.basePath}/sample_2`)
.set('Content-Type', 'multipart/form-data')
.set('Accept', 'application/json')
.attach('file', 'package.json')
.field('array_with_objects', array_with_objects)
.field('metadata', 'some-metadata')
.expect(200)
.then((r) => {
Expand Down