mulesoft-labs / osprey-method-handler

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

Osprey Method Handler

NPM version NPM Downloads Build status Test coverage Greenkeeper badge

Middleware for validating requests and responses based on a RAML method object.

Installation

npm install osprey-method-handler --save

Features

Please note: Due to the build time of libxmljs, it does not come bundled. If you need XML validation, please install libxmljs as a dependency of your own project.

Usage

const express = require('express')
const handler = require('osprey-method-handler')
const utils = require('./utils')

const app = express()

// webapi-parser.Operation
const methodObj = utils.getMethodObj()
const options = {}

app.post(
  '/users',
  handler(methodObj, '/users', 'POST', options),
  function (req, res) {
    res.send('success')
  }
)

Accepts webapi-parser Operation object as first argument, path string as second argument, method name as third and options object as final argument.

Options

Adding JSON schemas

If you are using external JSON schemas with $ref, you can add them to the module before you compile the middleware. Use handler.addJsonSchema(schema, key) to compile automatically when used.

handler.addJsonSchema() accepts a third (optional) options argument. Supported options are:

Validation Errors

The library intercepts incoming requests and does validation. It will respond with 400, 406 or 415 error instances from http-errors. Validation errors are attached to 400 instances and noted using ramlValidation = true and requestErrors = [] (an array of errors that were found, compatible with request-error-handler).

See the code for a complete list of errors formats.

Please note: XML validation does not have a way to get the keyword, dataPath, data or schema. Instead, it has a meta object that contains information from libxmljs (domain, code, level, column, line).

To render the error messages for your application, look into error handling for Express, Connect, Router or any other middleware error handler. If you want a pre-built error handler, try using request-error-handler, which provides a pre-defined error formatter.

License

MIT license