express-requires

    1.2.0 • Public • Published

    express-requires

    version MIT Licence Build Status Coverage Status

    An express middleware for validating request fields and query parameters and returns a nicely formatted informative response. Performs two simple use cases:

    • Prevent unexpected parameters from being accepted
    • Requiring parameters to be passed to continue
    • Or both chained together

    Setup

    npm install express-requires --save
    

    Can be used on your whole app or just a single router

    var requires = require('express-requires')
    app.use(requires());
    // or
     
    var router = express.Router();
    router.use(requires());
     
    //How to use
    router.post('/person/new', function(req, res) {
      var fields = ['firstName', 'lastName'];
      if (req.requires(fields).allows(fields).check()){
        //..Continue if returns true. If not do nothing because a response is formatted and returned.
      }
    })

    A bad request would return error code400

    {
      "message": "Unexpected field: sample"
    }
    {
      "message": "Missing required field: firstName"
    }

    Can change the order to make a certain error condition take precedence.

    req.requires(fields).check()
    req.allows(fields).check()
    req.requires(fields).allows(fields).check()
    req.allows(fields).require(fields).chec()

    Validating Lists

    The above validations can also be done on a list object.

    router.post('/person/bluk-create', function(req, res) {
        var fields = ['firstName', 'lastName'];
        if (req.list().requires(fields).allows(fields).check()){
            //...
        }
    })

    Example Request

    {
      "firstName": "test",
      "lastName": "test2"
    }

    Response

    {
      "message": "Expected JSON array body"
    }

    Example 2

    [
      {
        "firstName": "test",
        "lastName": "test2"
      },
      {
        "firstName": "test3"
      }
    ]

    Response

    {
      "message": "Missing required field: lastName at item 1"
    }

    Extra Options

    Can optionally add the code and success flag to the response body in event of an error.

    app.use(requires({
      includeCode: 'code',
      includeSuccess: 'success'
    }));

    Returns

    {
      "message": "Missing required field: lastName",
      "code": 400,
      "success": false
    }

    Run Tests

    The tests use a mock express server with the middleware in place and a series of mocha chai tests

    npm test
    npm cover
    

    Install

    npm i express-requires

    DownloadsWeekly Downloads

    1

    Version

    1.2.0

    License

    MIT

    Unpacked Size

    23.8 kB

    Total Files

    12

    Last publish

    Collaborators

    • edufresne