Skip to content

Commit

Permalink
Throw error if spec specifies no content but actual response includes…
Browse files Browse the repository at this point in the history
… content/body (#591)

Co-authored-by: Lyndon Howie <lyndon.howie@minfos.com.au>
  • Loading branch information
lyndoh and Lyndon Howie committed May 3, 2021
1 parent e983108 commit 98de680
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/middlewares/openapi.response.validator.ts
Expand Up @@ -144,6 +144,19 @@ export class ResponseValidator {
findResponseContent(accepts, validatorContentTypes) ||
validatorContentTypes[0]; // take first contentType, if none found

if (validatorContentTypes.length === 0) {
// spec specifies no content for this response
if (body !== undefined) {
// response contains content/body
throw new InternalServerError({
path: '.response',
message: 'response should NOT have a body',
});
}
// response contains no content/body so OK
return;
}

if (!contentType) {
// not contentType inferred, assume valid
console.warn('no contentType found');
Expand Down Expand Up @@ -275,6 +288,9 @@ export class ResponseValidator {

const validators = {};
for (const [code, contentTypeSchemas] of Object.entries(responseSchemas)) {
if (Object.keys(contentTypeSchemas).length === 0) {
validators[code] = {};
}
for (const contentType of Object.keys(contentTypeSchemas)) {
const schema = contentTypeSchemas[contentType];
schema.paths = this.spec.paths; // add paths for resolution with multi-file
Expand Down
14 changes: 13 additions & 1 deletion test/response.validation.spec.ts
Expand Up @@ -29,7 +29,10 @@ describe(packageJson.name, () => {
return res.json({ id: 213, name: 'name', kids: [] });
});
app.get(`${app.basePath}/empty_response`, (req, res) => {
return res.status(204).send();
if (req.query.mode === 'non_empty_response') {
return res.status(204).json({});
}
return res.status(204).json();
});
app.get(`${app.basePath}/boolean`, (req, res) => {
return res.json(req.query.value);
Expand Down Expand Up @@ -175,6 +178,15 @@ describe(packageJson.name, () => {
expect(r.body).to.be.empty;
}));

it('should fail if response is not empty and an empty response is expected', async () =>
request(app)
.get(`${app.basePath}/empty_response?mode=non_empty_response`)
.expect(500)
.then((r) => {
expect(r.body.message).to.contain('response should NOT have a body');
expect(r.body).to.have.property('code').that.equals(500);
}));

it('should fail if additional properties are provided when set false', async () =>
request(app)
.post(`${app.basePath}/no_additional_props`)
Expand Down

0 comments on commit 98de680

Please sign in to comment.