Skip to content

Commit

Permalink
fix: objects in form-data (#730)
Browse files Browse the repository at this point in the history
Co-authored-by: dj <>
  • Loading branch information
ownagedj authored Jan 10, 2023
1 parent de0708b commit e5cb5d6
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/middlewares/openapi.request.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,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 @@ -196,6 +201,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

0 comments on commit e5cb5d6

Please sign in to comment.