skeemas-body-parser
Body parsing middleware with json-schema validation. This utility is a plugin for the skeemas validation library.
Install
npm install skeemas-body-parser --save
This will install skeemas-body-parser, and also install skeemas as a peerDependency if you haven't already installed it.
Usage
Add the plugin to skeemas
and then generate middleware from your schemas:
var skeemas = skeemasBodyParser = ; skeemas; var fooSchema = type: 'object' properties: name: type:'string' things: type: 'array' minItems: 1 ; app;
Using References
Hard-coding schemas inline is rarely practical and you will usually want to add references for your schemas before generating middleware. In order to do that you will need to create a schema validator instance:
var skeemas = skeemasBodyParser = ; skeemas; var validator = ; // Add a referencevalidator; // Validate against itvalidatorvalid; // true|false // Create middlewareapp;
Invalid Bodies
In the event that an invalid req.body
is found, a failed jsend response will be sent automatically (with statusCode 422) and your route handler will not be called.
Default 422 responses:
"status": "fail" "data": "validation": "array of errors..."
Customizing Failure Responses
If you'd like to change the statusCode or format of the failure responses you can provide options when setting up your middleware:
skeemas;
Schema Defaults
Skeemas will append your schema's default values when non-required object properties are missing in your post bodies. For example, if foo
is not in your body it will be set to 'bar'
using this schema:
To disable setting of defaults, set the addDefaults
option to false
:
skeemas;