question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

validateResponse fails even though response is valid

See original GitHub issue

I am using the vanilla validateAllResponses from express-openapi and it seems to always throw an error on me when using a response that returns a JSON. Why could that be happening?

Example YAML (OpenAPI 3.0) for that specific path:

/HealthCheck:
    get:
      operationId: healthCheck
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    enum:
                      - OK

validateAllResponses on response “{“status”: “OK”}” (without the outer quotation marks, of course) says: “Invalid response for status code 200: should be object”. What am I missing? Isn’t this a valid object?

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
aperkazcommented, Mar 30, 2021

In case someone stumbles on this later on, here is the working version for Json responses:

 function validateAllResponses(req: any, res: any, next: any) {
    const strictValidation = req.apiDoc['x-express-openapi-validation-strict']
      ? true
      : false;
    if (typeof res.validateResponse === 'function') {
      const send = res.json;
      res.json = function expressOpenAPISend(...args: any[]) {
        const onlyWarn = !strictValidation;
        if (res.get('x-express-openapi-validation-error-for') !== undefined) {
          return send.apply(res, args);
        }
        const body = args[0];
        let validation = res.validateResponse(res.statusCode, body);
        let validationMessage;
        if (validation === undefined) {
          validation = { message: undefined, errors: undefined };
        }
        if (validation.errors) {
          const errorList = Array.from(validation.errors)
            .map((_) => _.message)
            .join(',');
          validationMessage = `Invalid response for status code ${res.statusCode}: ${errorList}`;
          // Set to avoid a loop, and to provide the original status code
          res.set(
            'x-express-openapi-validation-error-for',
            res.statusCode.toString()
          );
        }
        if (onlyWarn || !validation.errors) {
          return send.apply(res, args);
        } else {
          res.status(500);
          return res.json({ error: validationMessage });
        }
      };
    }
    next();
  }
2reactions
malnorcommented, Dec 18, 2020

@JasonSome This was asked quite some time ago. But also had this problem and it is because it overwrites the res.send but not the res.json. So if you would change all the send to json it will work for all json responses but probably not any send responses. I changed mine to json, because I just respond with json.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Validate Response Status using Rest Assured?
Every HTTP Response received as a result of an HTTP request sent by the client to the server has a status code. This...
Read more >
Response validation - Ktor
By default, Ktor doesn't validate a response depending on its status code. If required, you can use the following validation strategies:.
Read more >
[Bug] 422 Response Not Being Used For Validation ... - GitHub
I have an Open API spec that is valid when I used Spectral I can ... When I send an invalid request it...
Read more >
validate-response - npm
Start using validate-response in your project by running `npm i ... checkJSON - boolean, if true error will throws on response that has ......
Read more >
Getting and Verifying Response Data with REST-assured
The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found