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

express-request-parameters

v0.2.2

Published

Middleware for processing request data (setting default values, filtering, validation)

Downloads

16

Readme

express-request-parameters

Middleware for processing request data (setting default values, filtering, validation). It's useful in HTTP API when you want to process client input. The processing itself is performed by transformer-chain module.

NPM version Build status

Note: This module works in Node.js >= 4.0.

Installation

npm install express-request-parameters

Usage

expressRequestParameters(schema, [options])

Parameters

  • schema (Function | Object) - Schema which defines how to process request data (req.query, req.body and req.params are merged and processed as one object)
  • [options] (Object)
    • [name=parameters] (String) - Specifies where to set processed data in req object
    • [rawName=rawParameters] (String) - Specifies where to set raw data (before processing) in req object
    • [errorFactory] (Function) - Factory for error creation on validation error
    • [errorMessage=Bad Request] (String | Function) - Error message

Return value

(Function) - (req, res, next) middleware

Overview

Imagine you want to allow users to create books in your REST API. And book looks like this:

const book = {
    name: 'The Adventures of Tom Sawyer', // required field
    author: {
        name: 'Mark Twain' // required
    },
    reviews: [
        {
            author: 'Leo Tolstoy',
            text: 'Great novel',
            visible: true
        },
        {
            author: 'Fyodor Dostoyevsky',
            text: 'Very interesting'
        }
    ]
};

And before creating book you may want to check that client sent valid data. You can do it by defining schema (take a look at transformer-chain to see all features).

const bookSchema = {
    name: {
        $filter: 'trim', // trims only strings
        $validate: {
            required: true, // mark as required field
            string: true
        }
    },
    author: {
        $validate: { // you can omit check that "author" value is object, it will be done internally 
            required: true
        },
        
        name: {
            $filter: 'trim',
            $validate: {
                required: true,
                string: true
            }
        }
    },
    reviews: [{ // define schema for array items
        author: {
            $filter: 'trim',
            $validate: {
                required: true,
                string: true
            }
        },
        text: {
            $filter: 'trim',
            $validate: {
                required: true,
                string: true
            }
        },
        visible: {
            $default: true, // default value will be set when actual value of property is undefined
            $filter: 'toBoolean' // always returns boolean
        }
    }]
};

Then you need just pass this schema to express-request-parameters:

const express    = require('express');
const parameters = require('express-request-parameters');
const bookSchema = require('./bookSchema');

const app = express();

app.post('/books', parameters(bookSchema), function(req, res, next) {
  // req.parameters is processed input data
});

If you want to use another from parameters name just use name option:

app.post('/books', parameters(bookSchema, { name: 'book' }), function(req, res, next) {
  // use req.book instead of req.parameters
});

You can specify default options:

// config.js
const parameters = require('express-request-parameters');
parameters.options = { 
    name: '$params'
};

// app.js
app.post('/books', parameters(bookSchema), function(req, res, next) {
  // use req.$params instead of req.parameters
});

When you have validation error middleware will call next with error object which looks like this:

const err = new Error('Bad Request'); 
err.status = 400;
err.errors = errors; // validation errors

You can change error message (Bad Request) by using errorMessage option:

// config.js
const parameters = require('express-request-parameters');
parameters.options = { 
    errorMessage: 'Validation Error' 
};

// or it can be a function
parameters.options = { 
    errorMessage: function(req) { // you can use req object if needed
        return 'Validation Error';
    } 
};

Or you can even specify your custom errorFactory:

// config.js
const parameters = require('express-request-parameters');
parameters.options = { 
    errorFactory: function(message, validationErrors) {
        const err = new Error(message);
        err.status = 400;
        err.validationErrors = validationErrors;
        return err;
    }
};

If you need to do something with validators/filters (add new for example), you can use transformer:

const parameters = require('express-request-parameters');

parameters.transformer.plugins.validate.validators.newValidator = function(value, options) {
    /* validator implementation */
};

Tests

npm install
npm test

License

MIT