1.0.3 • Published 6 years ago

bodychecker v1.0.3

Weekly downloads
3
License
MIT
Repository
github
Last release
6 years ago

Bodychecker

npm version travis-ci

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 (optional isRequired) any type, e.g 'abc',123,undefind

  • array (optional isRequired) array type, e.g [1,2,3...]

  • object (optional isRequired) object type, e.g {a:1}

  • bool (optional isRequired) boolean type, e.g true, false

  • number (optional isRequired) number type, e.g 3.14159265

  • string (optional isRequired) string type, e.g Hello world!

  • oneof (optional isRequired) array argument required, e.g oneof(['a', 'b'])

  • oneoftype (optional isRequired) array of function argument required, e.g oneoftype([bodychecker.string,bodychecker.number])

  • arrayof (optional isRequired) function argument required, e.g arrayof(bodychecker.string)

  • objectof (optional isRequired) function argument required, e.g objectof(bodychecker.string)

  • shapeof (optional isRequired) obeject of function argument required, e.g shapeof({ 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

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.9.3

6 years ago

0.9.2

6 years ago

0.9.1

6 years ago

0.9.0

6 years ago

0.1.1

7 years ago

0.1.0

7 years ago

0.0.9

7 years ago

0.0.8

7 years ago

0.0.7

7 years ago

0.0.6

7 years ago

0.0.5

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago