Middlewares
The middleware is a function, which is called before the route handler. Middleware functions have access to the request and response objects, and thenext
middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable namednext
.
Example
For example middleware which output request body to the terminal look like:
const loggerMiddleware = (req, res, next) => {
console.log(req.body);
next();
};
module.exports = loggerMiddleware;
Injecting middleware
You need to add middleware to the ROUTER store in your module fileindex.js
.
const simpleMiddleware = (req, res) => {
console.log(req.headers);
next();
};
ROUTER.set('middlewares', { simpleMiddleware });
Also, you can pin ACTIONS just add a little wrapper to your middleware initialization.
const simpleMiddleware = (ACTIONS) => {
return (req, res) => {
ACTIONS.send('event')
.then((info) => console.log(info));
.catch((warning) => console.log(warning));
next();
}
};
ROUTER.set('middlewares', { simpleMiddleware(ACTIONS) });
Middleware layers
Sometime you wanna change order to starting your middlewares. For doing that you need add extra argument to ROUTER "set" method.
ROUTER.set('middlewares', { someMiddleware }, n);
Where n - it's a number of middleware layer. It works like a "z-index" html attribute and just put your middleware to layer who will execute in numeric order.
By default all middlewares are placed to "zero layer".
Pin middleware to route
Sometime you wanna call some middleware only before some routes. You can do it just add to routes inside config.json
special key "middleware" and value must contain name of the middleware:
"routes": {
"users_auth": { "path": "users/auth", "method": "get", "middleware": "authMiddleware" }
},
After that you need to add middleware to ROUTER with the special string parameter 'routes'.
ROUTER.set('middlewares', {
authMiddleware: authMiddleware(ACTIONS),
}, 'routes');