route-middleware-mapper
v1.0.8
Published
mapping routes with middlewares
Downloads
7
Maintainers
Readme
router-middleware-mapper
A simple package to map different routes with different middlewares in nodejs project
Getting started
Install
$ npm i -S route-middleware-mapper
or
$ yarn add route-middleware-mapper
Use
After the installation you can require the package to your nodejs project. For example,
const express = require('express');
const app = express();
const routeMiddlewareMapper = require('route-middleware-mapper')
app.use (routeMiddlewareMapper(`${__dirname}/authentication`));
#This path should be a valid absolute path and contains a config.json
#and some middleware js files.
app.use(routes);
...
Policies
Create a folder named "policies" in project root. This "policies" folder contains all middlewares that are used by routes and the mapping configuration file. Other folder can be use too, if it follows the structure. Please remember DO pass the path of this folder when this library is used.(See the example above).
For example,
.
+-- policies
| +-- config.json
| +-- isAuthenticated.js
| +-- isAdmin.js
| +-- fromClient.js
| ...
All the js files are middlewares. You can have one like this
const isAuthenticated = (req, res, next) => {
console.dir('isAuthenticated');
};
module.exports = {
isAuthenticated
}; # an object should be exported.
Configuration
The "config.json" file is used to map routes with middlewares. For example,
{
"/*": ["isAuthenticated"],
"/health": {
"/*": [],
"/test":["isAuthenticated"],
"/admin": ["isAdmin"]
},
"/name": {
"/userinfo": ["isAdmin"],
"/testinfo": {
"/:id": ["fromClient","isAdmin"]
}
}
}
All the keys means the routes.
"/*" means all routes.
"/xxx" means a specific route.
"/:" means dynamic route.
The values should be string array which contains the middlewares that required by the route. So each string here represents the middleware in "policies" folder, and the order of strings matters.
Mapping
The route will be mapped to the key that closest to it. But if the specific route is not defined in the file, more general key will be used.
In previous example,
- All routes need to go through "isAuthenticated".
- route "/hello" will go through "isAuthenticated". Because there is no closer key defined here than "/*".
- route "/health/info" don't have any middlewares. Beacuse its closet route is all routes("/*") under "/health", which its value is "true".
- route "/name/role" will go through "isAuthenticated". Beacuse although its closet route is "/name", but neither "/" nor "/role" is defined under "/name", so it turns to a more general route "/".
- route "/name/testinfo/2" will go through "fromClient" and "isAdmin". Because it matches the "/name/testinfo/:id".
Contribution
- Fork it!
- Create your feature branch:
git checkout -b feature-branch
- Commit your changes:
git commit -am 'Some message to describe the changes'
- Push to the branch:
git push origin feature-branch
- Submit a pull request