NodeJS module to execute your Express endpoints (middlewares) from your code. This module will let you manually launch all your middleware. It is simulating a client calling your rest APIs, without using a network connection (your server does not even need to listen on a port).
Many times, your server and your client, need to execute the same functions. For example here is an endpoint to get user details:
app.get('/get-user/:id', (req, res) => {
mysql.query('select * from users where id=?', [req.params.id], (err, rows) => {
res.send({
user: rows[0]
});
});
});
Now you want to get the user details from your code. What should you do?
app.runMiddleware('/get-user/20', (_, body) => {
console.log(`User details: ${body}`);
});
npm i -S run-middleware
const express = require('express');
const app = express();
const runMiddleware = require('run-middleware');
runMiddleware(app);
- Pull requests, issues, and English proofreading are welcome on Github.
- Question & support on StackOverflow using
run-middleware
tag.
As options you can pass the query
, body
, method
and cookies
parameters.
app.runMiddleware('/handler', {
method: 'post',
query: {
token: 'tk-12345'
},
body: {
"action": "list",
"path": "/"
}
}, (code, data) => {
console.log(code, data);
process.exit(0);
});
When you runMiddleware
from another location, you don't have to pass all the parameters of the current middleware to the handler.
app.get('/middleware1', (req, res) => {
req.runMiddleware( /* ... */ );
})
You can check if the middleware executed will redirect the request by checking the code
and the headers.location
fields.
app.runMiddleware('/this-middleware-will-response-as-redirect', (code, body, headers) => {
if (code === 301 || code === 302) { // Redirect HTTP codes
console.log('Redirect to:', headers.location);
}
});
- v1.0.0 (25 June 2018) -
- v0.6.1 (9 Sep 2016) - Supports response.redirect
- v0.6.2 (10 Sep 2016) - Supports passing cookies and other variables to runMiddleware
- v0.6.3 (11 Sep 2016) - Supports running middleware from others middleware, for automatically passing cookies and headers between middlewares.
- v0.6.4 (13 Sep 2016) - Better documentation and examples
See the tests for further examples.