From 73ffa1b7721415f541c0d503c9e6460d70175a3f Mon Sep 17 00:00:00 2001 From: Carmine DiMascio Date: Fri, 19 Jul 2019 15:46:05 -0400 Subject: [PATCH] add content type to key for middleware cache --- src/middlewares/openapi.request.validator.2.ts | 15 +++++++++++++-- test/routes.spec.ts | 6 +++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/middlewares/openapi.request.validator.2.ts b/src/middlewares/openapi.request.validator.2.ts index 5fb3d07f..53b9ee3b 100644 --- a/src/middlewares/openapi.request.validator.2.ts +++ b/src/middlewares/openapi.request.validator.2.ts @@ -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( @@ -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; diff --git a/test/routes.spec.ts b/test/routes.spec.ts index 0b6f9894..5830de82 100644 --- a/test/routes.spec.ts +++ b/test/routes.spec.ts @@ -105,7 +105,7 @@ const basePath = (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') @@ -148,7 +148,7 @@ const basePath = (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() @@ -198,7 +198,7 @@ const basePath = (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', ); }));