From c8b5fdfc7b8cc79edd1e7f398bc488caa0413bd6 Mon Sep 17 00:00:00 2001 From: Carmine DiMascio Date: Wed, 7 Oct 2020 20:29:32 -0400 Subject: [PATCH] Response body coercion (#392) * (fix) #391 - do not coerce response body value * update README --- README.md | 2 ++ src/middlewares/openapi.response.validator.ts | 16 ++++++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b05e9079..d9283b19 100644 --- a/README.md +++ b/README.md @@ -700,6 +700,8 @@ Specifies the options to passthrough to multer. express-openapi-validator uses m Determines whether the validator should coerce value types to match the type defined in the OpenAPI spec. +_Applies **only** to path params, query string, headers, and cookies. + - `true` (**default**) - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). diff --git a/src/middlewares/openapi.response.validator.ts b/src/middlewares/openapi.response.validator.ts index 9b25cb26..f069b64d 100644 --- a/src/middlewares/openapi.response.validator.ts +++ b/src/middlewares/openapi.response.validator.ts @@ -25,7 +25,7 @@ interface ValidateResult { accepts: string[]; } export class ResponseValidator { - private ajv: ajv.Ajv; + private ajvBody: ajv.Ajv; private spec: OpenAPIV3.Document; private validatorsCache: { [key: string]: { [key: string]: ajv.ValidateFunction }; @@ -33,7 +33,11 @@ export class ResponseValidator { constructor(openApiSpec: OpenAPIV3.Document, options: ajv.Options = {}) { this.spec = openApiSpec; - this.ajv = createResponseAjv(openApiSpec, options); + this.ajvBody = createResponseAjv(openApiSpec, { + ...options, + coerceTypes: false, + }); + (mung).onError = (err, req, res, next) => { return next(err); }; @@ -54,8 +58,8 @@ export class ResponseValidator { const accepts: [string] = contentType ? [contentType] : accept - ? accept.split(',').map((h) => h.trim()) - : []; + ? accept.split(',').map((h) => h.trim()) + : []; return this._validate({ validators, @@ -160,7 +164,7 @@ export class ResponseValidator { if (!valid) { const errors = augmentAjvErrors(validator.errors); - const message = this.ajv.errorsText(errors, { + const message = this.ajvBody.errorsText(errors, { dataVar: '', // responses }); throw new InternalServerError({ @@ -259,7 +263,7 @@ export class ResponseValidator { schema.components = this.spec.components; // add components for resolution w/ multi-file validators[code] = { ...validators[code], - [contentType]: this.ajv.compile(schema), + [contentType]: this.ajvBody.compile(schema), }; } }