bodychecker
v1.0.3
Published
A middleware for express.js to check the request body.
Downloads
6
Readme
Bodychecker
Bodychecker is a express middleware for handling req.body
, which is used to validate the value in the body like the React Proptypes way.
Installation
npm install --save bodychecker
Usage
Bodychecker add result "req.$bcResult
" to the express RequestHandler.
example:
var express = require('express')
var bodychecker = require('bodychecker')
var app = express()
app.post('/post/new', bodychecker({
title: bodychecker.string.isRequired,
author: bodychecker.string,
time: bodychecker.number,
content: bodychecker.string.isRequired
}), function (req, res, next) {
// req.$bcResult is the result of the bodycheck, which will be null if all the fields are valid
// place your awesome code
})
API
All supported types:
any
(optionalisRequired
) any type, e.g'abc',123,undefind
array
(optionalisRequired
) array type, e.g[1,2,3...]
object
(optionalisRequired
) object type, e.g{a:1}
bool
(optionalisRequired
) boolean type, e.gtrue, false
number
(optionalisRequired
) number type, e.g3.14159265
string
(optionalisRequired
) string type, e.gHello world!
oneof
(optionalisRequired
)array
argument required, e.goneof(['a', 'b'])
oneoftype
(optionalisRequired
)array
offunction
argument required, e.goneoftype([bodychecker.string,bodychecker.number])
arrayof
(optionalisRequired
)function
argument required, e.garrayof(bodychecker.string)
objectof
(optionalisRequired
)function
argument required, e.gobjectof(bodychecker.string)
shapeof
(optionalisRequired
)obeject
offunction
argument required, e.gshapeof({ title: bodychecker.string })
Object "req.$bcResult"
{
message: 'message', // the default error message generated by bodychecker
type: 'invalid', // the error type 'empty', 'invalid'
fieldpath: fieldpath, // the path of the error fieldvalue, e.g 'people.0.name'
fieldvalue: fieldvalue // the error fieldvalue
}
Custom checker
Otherwise, You can also add custom checker.
/**
* customChecker
* @param {object} body - the req.body object
* @param {string} fieldname - the field name
* @return {object|null} - the result
*/
function customChecker(body, fieldname) {
// make sure this function can return with result or null
}
LICENSE
MIT