Skip to content

Commit

Permalink
add content type to key for middleware cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Carmine DiMascio committed Jul 19, 2019
1 parent 3b220e8 commit 73ffa1b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
15 changes: 13 additions & 2 deletions src/middlewares/openapi.request.validator.2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,9 @@ export class RequestValidator {
throw ono(err, message);
}

const contentType = req.headers['content-type'];
const key = `${req.method}-${req.path}-${req.headers['content-type']}`;
// cache middleware by combining method, path, and contentType
const contentType = this.extractContentType(req);
const key = `${req.method}-${req.path}-${contentType}`;

if (!this._middlewareCache[key]) {
this._middlewareCache[key] = this.buildMiddleware(
Expand All @@ -143,6 +144,16 @@ export class RequestValidator {
return this._middlewareCache[key](req, res, next);
}

private extractContentType(req) {
let contentType = req.headers['content-type'] || 'not_provided';
let end = contentType.indexOf(';')
end = end === -1 ? contentType.length : end;
if (contentType) {
return contentType.substring(0, end);
}
return contentType;
}

private buildMiddleware(path, pathSchema, contentType) {
const parameters = this.parametersToSchema(path, pathSchema.parameters);
const requestBody = pathSchema.requestBody;
Expand Down
6 changes: 3 additions & 3 deletions test/routes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const basePath = (<any>app).basePath;
}));
});

describe('when a route is not defined in express or not documented in openapi, it', () => {
describe('when a route defined either in express or openapi, but not both', () => {
it('should not validate a route defined in express, but not under an openapi basepath', async () =>
request(app)
.get('/not_under_an_openapi_basepath')
Expand Down Expand Up @@ -148,7 +148,7 @@ const basePath = (<any>app).basePath;
expect(e.path).to.equal(`${basePath}/router_1/10`);
}));

it('should return 405 if route is defined in swagger but not express and media type is invalid', async () =>
it('should return 405 if route is defined in swagger but not express and the method is invalid', async () =>
request(app)
.post(`${basePath}/route_not_defined_within_express`)
.send()
Expand Down Expand Up @@ -198,7 +198,7 @@ const basePath = (<any>app).basePath;
.then(r => {
const e = r.body.errors;
expect(e[0].message).to.equal(
'Unsupported Content-Type application/xml',
'unsupported media type application/xml',
);
}));

Expand Down

0 comments on commit 73ffa1b

Please sign in to comment.