ajv-request-validator
Validates the request
object of popular Node.js web frameworks with Ajv.
Installation
npm install ajv-request-validator --save# or yarn add ajv-request-validator
Usage
Example with Express:
const RequestValidator = ;const express = ; const app = ;const reqValidator = ; app;
Example with Medley (works exactly the same with Fastify):
const RequestValidator = ;const medley = ; const app = ;const reqValidator = ; app;
API
new RequestValidator([options])
The ajv-request-validator
module exports a class. The class constructor can optionally
be passed either an Ajv options object or
an existing ajv
instance.
const RequestValidator = ; // No options (use Ajv defaults)const reqValidator = ; // With Ajv optionsconst reqValidator = removeAdditional: true useDefaults: true coerceTypes: true; // With an existing AjV instanceconst Ajv = ;const ajv = ; const reqValidator = ajv; console; // true
reqValidator.ajv
The ajv
instance that the reqValidator
will use to compile validation functions.
reqValidatorajv; reqValidatorajv;
reqValidator.compile(schema[, options])
schema
- AndObject
mappingrequest
properties to an Ajv schema.options
- Optional optionsObject
.options.middleware
- Iffalse
, a function that directly validates therequest
object will be returned. Defaults totrue
.
Compiles a middleware function that validates the req
object and then calls next()
with the
result (either a validation error or null
on success). The keys of the schema
object correspond with
the names of the properties on the req
object to validate (usually body
or query
).
const middleware = reqValidator; // Use in Expressapp;
The middleware
function is an Express-style middleware function with the signature:
{ }
When the middleware
option is false
, .compile()
returns a function that directly validates
the request
object.
{ } // Returns `null` or an Error
const validate = reqValidator; app;
This is useful when using this module with frameworks that do not have Express-like middleware (see below for more info).
Usage with other frameworks
Since the .compile()
method returns an Express-style middleware
function, it is not initially compatible with frameworks that have a different
middleware signature.
If a different form of middleware is needed, the RequestValidator
class can be subclassed to override the .compile()
method to return
a function compatible with a specific framework.
Here's an example of extending RequestValidator
to work with Koa:
const RequestValidator = ; { const validate = super; return { const err = ; if err !== null throw err; await ; }; } const reqValidator = ;