npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xpress-req-validator

v1.0.2

Published

hassle free request validation middleware

Downloads

27

Readme

[LOGO] Request Validator

Hassle free middleware to validate all type of requests in a single place while respecting the principle of separation of concerns

npm version Build Status Coverage Status Code Climate Known Vulnerabilities

Introduction

xpress-req-validator allows developers to handle all request validation tasks in a single place as a middleware while respecting the principle of separation of concerns. It can be used at app level or router level. xpress-req-validator relies on Joi (the awsome JSON Schema validator), which is used to define the request validation specs

Table of Contents

Why xpress-req-validator

Request validation is a must when developing an API. Express allows following means to achieve this.

  1. Handling validation logic in each route handler (method-1)
router.post('/device/data', (req, res) => {
        const {deviceID, serialNo} = req.body;
        if(!deviceID || !serialNo) {
            const err = new Error('invalid parameters')
            res.status(400).json({err})
        }

        controller(req.body) // controller section
}
  1. writing a separate middleware in each route handler (method-2)
router.post('/device/data', deviceDataValidationMiddleware, (req, res) => {
        controller(req.body) // controller section
}

Method-1 is an ugly and painful way of achieving request validation. Method-2 is comparatively better, but still requires you to write a ton of middleware. Both methods demand a significant effort to unit test the route handler.

There has to be a better way of validating requests with less unit testing effort and of course by separating the concerns. xpress-req-validator is the solution. It allows developers to define all their request validation specs in a single place, make route handling code snippets much cleaner and finally reducing the unit test effort

Installation

yarn add xpress-req-validator

or

npm install xpress-req-validator

Basic Usage

Assume that we need to validate the request body of deviceRouter.post('/device', ()=> {})

first we must define the validation spec for request body using Joi

spec.js

import Joi from 'joi';

export const DEVICE_SPEC = Joi.object().keys({
    serialNo: Joi.string()
        .alphanum()
        .min(3)
        .max(25)
        .required(),
    manufacturedYear: Joi.number()
        .integer()
        .min(1900)
        .required(),
    type: Joi.string()
        .valid(['TYPE-A','TYPE-B'])
        .required(),
});

next we must define the xpress-req-validator configurations

config.js

import {DEVICE_SPEC} from './spec';

export default {
    specs: {
        POST: {
            '/device': {
                body: DEVICE_SPEC,
            },
        },
    },
};

now we can apply the xpress-req-validator to deviceRouter

deviceRouter.js

import express from 'express';
import Validator from 'xpress-req-validator';

import config from './config';

const validator = new Validator(config);
const deviceRouter = express.Router();
deviceRouter.use(validator.init());

deviceRouter.post('/device', ()=> {});

That's how easy and clean xpress-req-validator does the job for you. Similarly we can validate the header, path & query of GET, PUT & DELETE requests

Extended Documentation

For more detailed examples please visit GitBook

Changelog

License

MIT