Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate no-content responses #591

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/middlewares/openapi.response.validator.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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