middleware-params
An easy mechanism for passing data to express middleware
Installation
$ npm install middleware-params
API
const {getData, setData} = require('middleware-params');
The middleware-params module exports two functions.
setData() can be applied as router or application middleware to set values that can be used by later middleware in the chain.
getData() is a convenience function for getting the set data from the request object.
mwParams.setData(data, [options])
Sets data in the request object that can be read from middleware further down the chain.
data
The data to be set. This call will create or replace any data using the the same name (see the options object).
options
An optional options object. Populate the options object if you want to control the key that holds the data. If not defined, this defaults to
Using the default options argument, stores the data in
req.locals["__PARAM"]
mwParams.getData([options])
Returns the stored data set in earlier middleware or undefined if none is found.
options
Same as the options object in the setData function. You should either default both or provide the same options object to both setData() and getData().
Examples
Usage in application middleware
const express = ;const getData setData = ; const app = ;let myData = "somekey": "someval"; // Set some data that will available for all subsequent middlewareapp; // Define more application middlewareapp; // Get the data from a routeapp;
Usage in routes
const express = ;const getData setData = ; const app = ;let myData = "somekey": "someval"; // Set the data in middleware of a routeapp;
Using custom key names
const express = ;const getData setData = ; const app = ;let myData = "somekey": "someval"; // Set the data in middleware of a routeapp;
Test cases and code coverage
npm testnpm run coverage
License
MIT