express-use-request
This is a small library for the nodejs express
server, based on the async-hooks
mechanism.
It allows you to receive the current processed request from anywhere.
Installation
npm i express-use-request
API
middleware
First you need to connect middleware
. It is recommended to connect it one of the first.
// index.js
let { middleware } = require('express-use-request');
let anyLib = require('./any-lib.js');
...
const app = express();
app.use(middleware);
app.get('/', (req, res) => {
/**
* There is no need passing req to anyMetod and to any nested deeper.
*/
let result = anyLib.anyMetod({foo: 'bar'});
res.status(200).send(result);
});
app.listen(3000);
useRequest
With the useRequest
function, you can get the request to be processed anywhere.
It may contain supporting information related to a specific request, which now does not need to be passed through the entire callstack.
// ./any-lib.js
const { useRequest } = require('express-use-request);
module.exports = {
anyMethod: (params) => {
// With the useRequest function, you can access a request from anywhere.
let request = useRequest();
...
}
};