Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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