mulesoft-labs / osprey-method-handler

Middleware for validating requests and responses based on a RAML method object
Other
16 stars 16 forks source link

Unexpected error if schema field of request body declaration refers to schema declared in root section #30

Open berntmelba opened 6 years ago

berntmelba commented 6 years ago

In cases where the schema field of a request body declaration for application/json type refers to a named schema declared in the root section of the RAML content as in the following example, I have observed that an unexpected error is thrown when creating the ospreyMethodHandler for the associated RAML.

Example RAML snippet

schemas:
  - newBooking: !include schemas/createEventBooking.json
/createEventBooking:
  post:
    body:
      application/json:
        schema: newBooking

Problem This results in the following unexpected error when attempting to create the associated ospreyMethodHandler.

Error: Unable to compile JSON schema for post /pps/v3/core/createEventBooking: Unexpected token e in JSON at position 1

Root Cause Here is the offending code I found in the jsonBodyHandler() function that causes this error.

  var schema = body && (body.properties || body.type) || undefined
  var isRAMLType = schema ? schema.constructor === {}.constructor : false

  // This is most likely a JSON schema
  if (!schema) {
    schema = body.schema

The body.schema in the example RAML shown above is "newBooking" while the actual JSON schema content is in body.schemaContent. The value "newBooking" assigned to the schema variable is then passed as input to jsonBodyValidationHandler() which then attempts to perform JSON.parse() on this value resulting in the observed error. In cases where the schema field in the RAML definition of a request/response body for a given media type is an inline JSON schema or refers to an external schema via an include statement, the logic above works fine because the schema content in these cases is populated in both body.schema and body.schemaContent by the raml-1-parser that is being used to parse the RAML.

Suggested Fix Change the assignment statement from schema = body.schema to schema = body.schemaContent || body.schema

jstoiko commented 6 years ago

@berntmelba: sorry for the late response. I had to update this library for another issue so I took a quick look at your issue and it seems to be a legitimate scenario. Unfortunately, I did not have time to work on a fix.

Like you said, it shouldn't be too complicated to fix. Update the schema assignment in jsonBodyHandler(), add tests cases, etc. Feel free to make a PR if you have time.