Skip to content

Commit

Permalink
Response body coercion (#392)
Browse files Browse the repository at this point in the history
* (fix) #391 - do not coerce response body value

* update README
  • Loading branch information
cdimascio committed Oct 8, 2020
1 parent e615c57 commit c8b5fdf
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -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).

Expand Down
16 changes: 10 additions & 6 deletions src/middlewares/openapi.response.validator.ts
Expand Up @@ -25,15 +25,19 @@ 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 };
} = {};

constructor(openApiSpec: OpenAPIV3.Document, options: ajv.Options = {}) {
this.spec = openApiSpec;
this.ajv = createResponseAjv(openApiSpec, options);
this.ajvBody = createResponseAjv(openApiSpec, {
...options,
coerceTypes: false,
});

(<any>mung).onError = (err, req, res, next) => {
return next(err);
};
Expand All @@ -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,
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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(<object>schema),
[contentType]: this.ajvBody.compile(<object>schema),
};
}
}
Expand Down

0 comments on commit c8b5fdf

Please sign in to comment.