Skip to content

Commit e5cb5d6

Browse files
authored
fix: objects in form-data (#730)
Co-authored-by: dj <>
1 parent de0708b commit e5cb5d6

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/middlewares/openapi.request.validator.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,11 @@ export class RequestValidator {
164164
body: req.body,
165165
};
166166
const schemaBody = <any>validator?.schemaBody;
167+
168+
if (contentType.mediaType === 'multipart/form-data') {
169+
this.multipartNested(req, schemaBody);
170+
}
171+
167172
const discriminator = schemaBody?.properties?.body?._discriminator;
168173
const discriminatorValidator = this.discriminatorValidator(
169174
req,
@@ -196,6 +201,21 @@ export class RequestValidator {
196201
};
197202
}
198203

204+
private multipartNested(req, schemaBody) {
205+
Object.keys(req.body).forEach((key) => {
206+
const value = req.body[key];
207+
const type = schemaBody?.properties?.body?.properties[key]?.type;
208+
if (['array', 'object'].includes(type)) {
209+
try {
210+
req.body[key] = JSON.parse(value);
211+
} catch (e) {
212+
// NOOP
213+
}
214+
}
215+
})
216+
return null;
217+
}
218+
199219
private discriminatorValidator(req, discriminator) {
200220
if (discriminator) {
201221
const { options, property, validators } = discriminator;

test/common/test.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,13 @@ paths:
160160
description: The photo
161161
type: string
162162
format: binary
163+
array_with_objects:
164+
type: array
165+
items:
166+
type: object
167+
properties:
168+
foo:
169+
type: string
163170
required: true
164171
responses:
165172
201:

test/multipart.spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,18 @@ describe('a multipart request', () => {
127127
});
128128

129129
it('should validate multipart file and metadata', async () => {
130+
const array_with_objects = JSON.stringify([
131+
{
132+
foo: 'bar'
133+
}
134+
]);
135+
130136
await request(app)
131137
.post(`${app.basePath}/sample_2`)
132138
.set('Content-Type', 'multipart/form-data')
133139
.set('Accept', 'application/json')
134140
.attach('file', 'package.json')
141+
.field('array_with_objects', array_with_objects)
135142
.field('metadata', 'some-metadata')
136143
.expect(200)
137144
.then((r) => {

0 commit comments

Comments
 (0)