express-json-validator

1.0.1 • Public • Published

Express JSON Validator

This project is a simple and application forward express.js validation middleware generator that uses JSON Schemas as the source of configuration.

WHY: basically, i want the point and shoot type of development experience. plus consistency of the error messages and ease of custom integrations.

Installation & Usage

npm install express-json-validator --save
const express = require('express');
const { validate, ValidationError } = require('express-json-validator');
const schema = {
  properties: {
    username: { type: 'string' },
    password: { type: 'string' }
  },
  required: [ 'username', 'password' ]
};
 
const app = express();
 
app.post('/signin', validate(schema), (req, res) => {
  // HOORAY, validated data!
  const { username, password } = req.body;
 
  // do useful stuff here
});
 
// HOORAY consistent errors handling!
app.use((err, req, res, next) => {
  if (err instanceof ValidationError) {
    res.status(422).send(err.message);
  } else {
    next();
  }
});

Data Envelopes Support

If you're using rails-ish data envelopes for your params, meaning, user[username] and user[password] instead of plain username and password. This package allows you to specify the envelope option.

app.post('/signup', validate(schema, envelope: 'user')), (req, res) => {
  const { user: {username, password} } = req.body;
 
  User.create({username, password}).save().then(user => {
    res.send(user);
  });
});

Copyright & License

All code in this repository is released under the terms of the ISC license.

Copyright (C) 2016 Nikolay Nemshilov

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.1
    7
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.1
    7
  • 1.0.0
    0

Package Sidebar

Install

npm i express-json-validator

Weekly Downloads

7

Version

1.0.1

License

ISC

Last publish

Collaborators

  • nikolay_nemshilov