Simplify the MVC/api applications routing.
npm install --save magic-router
All the controllers in the controller folder are loaded and the default routes are configured automatically by the magic-router.
index
or get
(default index routing) it have default routing as Hostname/controller
too. if a controller have multiple default index routing
names as action/method name in a file this feature will not work.all
(app.all()
in express) from version 1.1.5 onwards. (before use
method was used)From app.js
import express from 'express';
const app = express();
.... .....
import magicRouter from 'magic-router';
//adding all contollers..
// magicRouter.addAll(express_app_instance, options);
magicRouter.addAll(app, { dirPath: './controllers' });
let options = {
dirPath:'./controllers', // path of controller directory
exclude:[], // optional files path for removing from magic-routering
prefix:'', // global prefix for routing
};
magicRouter.addAll(app, options);
magicRouter.addAll(app, {
dirPath: '../../example/controllers',
// excluding files
exclude: ['../../example/controllers/auth.js'],
});
The developers need to focus only on the controllers.
export default {
// OPTIONAL
// specifying the router is optional for customizing the router path
// default will be action name.
router: {
// route overrides will come here <methodname>:<route>
// a route with specific param will look like the one below
foo1: 'foo/:id',
},
// OPTIONAL
// type is optional for customizing the request type for methods.
// It can be 'get', 'post' or any verb.
// default will be 'all' as in app.all(...
type: {
// type overrides will come here <methodname>:<verb>
foo: 'get',
},
// OPTIONAL
// beforeController is optional for customizing filters or middlewares before request enters
// controller object.
beforeController: [
(req, res, next) => {
console.log('This will be hit before the control is passed to the controller object.');
next();
},
...
// multiple middleware can be configured here in the same way.
// say, authenticate, auditlog etc
],
// OPTIONAL
// beforeAction is optional for customizing filters or middlewares before request enters
// current action corresponding to the route
beforeAction: {
// <methodname>:[middleware1, middleware2, ...]
foo: [print],
},
// foo is an action in this controller
foo(req, res, next) {
res.send('Foo');
},
// foo1 is an action in this controller with a parameter: id
foo1(req, res, next) {
res.send('id :' + req.param('id'));
},
};
Everything except the action methods are optional and you need to write those only if you need to override the default behaviors.
`${host}/${controllerName}`
`${host}/${controllerName}/${index}`
Version | Tag | Published |
---|---|---|
1.1.5 | latest | 4yrs ago |