osprey-method-handler
osprey-method-handler copied to clipboard
Unexpected error if schema field of request body declaration refers to schema declared in root section
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