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

[ft. request] openapi-response-validator - allow access to response param in errorTransformer #875

Open
webketje opened this issue May 25, 2023 · 1 comment

Comments

@webketje
Copy link

Context

  • openapi-response-validator version: 12.1.3
  • Node version: 18.12.1
  • Package type: module (native node ESM ending in .js)

Feature

Allow access to response param in errorTransformer so the error can be more informative. As a work-around I overwrite the validateResponse method to 'cache' the last response on validator.lastTarget, so I can log the erroneous value together with the rest of the error:

const validator = new OpenAPIResponseValidator({
  components,
  responses: { '200': components.responses.Data },
  definitions: components.schemas,
  errorTransformer: function(openapiError, ajvError) {
    const keypath = openapiError.path.replace(/\//g, '.')
    const pathparts = keypath.split('.')
    let value = validator.lastTarget
      for (let i = 0; i < pathparts.length; i++) {
        if (!value) break
        value = value[pathparts[i]]
      }
    return `Error: Target ${keypath} ${openapiError.message}. Target ${keypath} value is: ${JSON.stringify(value, null, 2)}`
  }
})

// overwrite and store last validated target for error reporting
validator.validateResponse = function(statusCode, context) {
  validator.lastTarget = context
  return OpenAPIResponseValidator.default.prototype.validateResponse.call(this, statusCode, context)
}

console.log(validator.validateResponse(invalidData))
// {
//  message: 'The response was not valid.',
//  errors: [
//    'Error: Target data.items.2.instance must be object. Target data.items.2.instance value is: true'
//  ]
// }
@jsdevel
Copy link
Contributor

jsdevel commented May 25, 2023

plz submit a pr

webketje added a commit to webketje/open-api that referenced this issue May 26, 2023
webketje added a commit to webketje/open-api that referenced this issue May 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants