express_controller v1.0.1
express controller
Easy way to do controllers using express
With support to Async/Await and Generator based control flow
Steps to setup a controller
Create a new file to be a controller;
Import the library
const Controller = require( 'express_controller' );
- Instantiate the controller with its base path
const ctrl = new Controller( '/' );
- Append any filters you want
ctrl.restrict( AuthFilter );
A filter is an abstraction for any route middleware used by the express, so it is a function with this signature:
filter( req, res, next ) {
// ...
next();
}
Check out Express.js docs for more info.
- Define the routes (again, like plain express.js):
ctrl.get( '/clients', ( req, res ) => {
res.render('clients/index');
} );
- Export the routes at the end of the files
module.exports = ctrl.routes;
- Import this controller in your main app.js
const app = express();
app.use('/', require('your_controller_1.js') );
app.use('/', require('your_controller_2.js') );
// ...
app.use('/', require('your_controller_N.js') );
// OR, if those are in a path:
walk(path.join(__dirname, '/app/controllers')).forEach(file => app.use('/', require(file)));
In the example, walk
is a library to get all files from a path, you can find here.
Wait there is more!
- Async/await
If you want to have async
methods inside one route logic, just do it:
ctrl.get( '/client', async ( req, res ) => {
const clients = await Clients.find( {} );
res.render( 'clients/index', { clients } );
});
- Generator based control flow
If you want to yield your code, with promises, inside a generator, this is supported too
ctrl.get( '/client', function *( req, res ) => {
const clients = yield Clients.find( {} );
res.render( 'clients/index', { clients } );
});
This is done using simplerunner
library info here.
- Errors! Errors! and more Errors!
Once more, the error treatment is express-ish, just append this after your routes:
// errors
app.use( function (err, req, res, next) {
// here your have the errors
});
More info here.
This errors include exceptions and rejections threw by the yield/awaited functions as well.