NodeJS Express module to simulate URL requests, for internal executing REST API's
ISC License
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);
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);
}
});
See the tests for further examples.