Giter VIP home page Giter VIP logo

celebrate's Introduction

Celebrate

Logo design by [email protected]

Current Version Build Status

belly-button-style

celebrate is an Express middleware function that wraps the joi validation library. This allows you to use this middleware in any single route, or globally, and ensure that all of your inputs are correct before any handler function. The middleware allows you to validate req.params, req.headers, req.query and req.body (provided you are using body-parser).

celebrate uses "peerDependencies" to manage the required version of joi it will use. This means that if you're using npm@3, you must install a compatible version of joi (currently 9.x.x) as a top level dependency for celebrate to work correctly. celebrate does not install its own copy of joi when using npm@3. This is to maximize compatibility and to keep the number of joi version mismatch bugs to a minimum.

Wondering why another joi middleware library for Express? Full blog post here.

Usage

Example of using celebrate on a single POST route to validate req.body.

const express = require('express');
const BodyParser = require('body-parser');
const Joi = require('joi');
const Celebrate = require('celebrate');

const app = express();
app.use(BodyParser.json());

app.post('/signup', Celebrate({
  body: Joi.object().keys({
    name: Joi.string().required(),
    age: Joi.number().integer(),
    role: Joi.string().default('admin')
  }),
  query: {
    token: Joi.string().token().required()
  }
}), (req, res) => {
  // At this point, req.body has been validated and 
  // req.body.name is equal to req.body.name if provided in the POST or set to 'admin' by joi
});
app.use(Celebrate.errors()));

Example of using celebrate to validate all incoming requests to ensure the token header is present and mathes the supplied regular expression.

const express = require('express');
const Joi = require('joi');
const Celebrate = require('celebrate');
const app = express();

// valide all incoming request headers for the token header
// if missing or not the correct format, respond with an error
app.use(Celebrate({
 headers: Joi.object({
   token: Joi.string().required().regex(/abc\d{3}/)
 }).unknown()
}));
app.get('/', (req, res) => { res.send('hello world'); });
app.get('/foo', (req, res) => { res.send('a foo request'); });
app.use(Celebrate.errors()));

API

Celebrate(schema, [options])

Returns a function with the middleware signature ((req, res, next)).

  • schema - a object where key can be one of 'params', 'headers', 'query', and 'body' and the value is a joi validation schema. Only the keys specified will be validated against the incomming req object. If you omit a key, that part of the req object will not be validated. A schema must contain at least one of the valid keys.
  • [options] - joi options that are passed directly into the validate function.

Celebrate.errors()

Returns a function with the error handler signature ((err, req, res, next)). This should be placed with any other error handling middleware to catch Joi validation errors. If the incomming err object is a Joi error, errors() will respond with a 400 status code and the Joi validation message. Otherwise, it will call next(err) and will pass the error along and need to be processed by another error handler.

If the error format does not suite your needs, you an encouraged to write your own error handler and check err.isJoi to format joi errors to your liking. The full joi error object will be available in your own error handler.

Order

celebrate validates req values in the following order:

  1. req.headers
  2. req.params
  3. req.query
  4. req.body

If any of the configured validation rules fail, the entire request will be considered invalid and the rest of the validation will be short-circuited and the validation error will be passed into next.

Issues

Before opening issues on this repo, make sure your joi schema is correct and working as you intended. The bulk of this code is just exposing the joi API as Express middleware. All of the heavy lifting still happens inside joi.

celebrate's People

Contributors

arb avatar cjihrig avatar justin-calleja avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.