Skip to content
Open
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
35 changes: 35 additions & 0 deletions src/validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,7 @@ describe.each([{}, { lazyCompileValidators: true }])('OpenAPIValidator with opts
operationId: 'createPet',
responses: { 200: { description: 'ok' } },
requestBody: {
required: true,
content: {
'application/json': {
schema: petSchema,
Expand All @@ -519,6 +520,19 @@ describe.each([{}, { lazyCompileValidators: true }])('OpenAPIValidator with opts
},
},
},
'/optional-pets': {
post: {
operationId: 'createOptionalPet',
responses: { 200: { description: 'ok' } },
requestBody: {
content: {
'application/json': {
schema: petSchema,
},
},
},
},
},
'/pets/schedule': {
post: {
operationId: 'createPetSchedule',
Expand Down Expand Up @@ -642,6 +656,27 @@ describe.each([{}, { lazyCompileValidators: true }])('OpenAPIValidator with opts
expect(valid.errors && valid.errors[0].keyword).toBe('parse');
});

test('passes validation when optional requestBody with one media type is omitted', async () => {
const valid = validator.validateRequest({
path: '/optional-pets',
method: 'post',
headers,
});
expect(valid.errors).toBeFalsy();
});

test('fails validation when optional requestBody with one media type is provided but invalid', async () => {
const valid = validator.validateRequest({
path: '/optional-pets',
method: 'post',
headers,
body: {
age: 40,
},
});
expect(valid.errors).toHaveLength(1);
});

test('allows non-json data when application/json is not the only allowed media type', async () => {
const valid = validator.validateRequest({
path: '/pets',
Expand Down
3 changes: 1 addition & 2 deletions src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,8 +578,7 @@ export class OpenAPIValidator<D extends Document = Document> {
},
};
requestBodySchema.required = [];
if (_.keys(requestBody.content).length === 1) {
// if application/json is the only specified format, it's required
if (requestBody.required) {
requestBodySchema.required.push('requestBody');
}

Expand Down
Loading