express-controllers
This is the step needed to transform expressjs into a complete MVC framework, by adding Controller-support. No more hassling with code in your route. express-controllers automatically set up routing based on your controllers.
Contributors
Julian Duniec http://github.com/julianduniec
Installation
$ npm install express-controller
Usage
var expressControllers = ; //Your express-appvar app = ; //Tell expressControllers to use the controllers-directory, and use bind() to set up routing.expressControllers ;
Express 4 Usage
var expressControllers = ; var app = ; var router = express; app; //Tell expressControllers to use the controllers-directory, and use bind() to set up routing.expressControllers ;
Controllers & Paths
The paths will be generated by a convention of naming controllers and functions.
A basic example: PeopleController.js
moduleexports = /* Will be translated to get("/people") (first level is generated by controller name) */ { res; } /* Will be translated to get("/people") (HTTP-method is extracted by first item in function name) */ { res; } /* Will be translated to get("/people/finest") (subsections automatically appended) */ { res; } /* You may want to have your route passed through an express middleware (i.e. for authentication/authorization checks etc.) before your controller function is called. To do that just pass an array of middleware functions along with the controller function. For example you have a middleware function defined in your middleware: exports = function (req, res, next) { if(req.session.user) next(); else res.send('Please login to access this page'); } Now you can use this in your controller actions like the example below. Note that you can use any number of middleware functions as you want. To know more about express middleware callback functions in routes, visit this link: http://expressjs.com/guide/routing.html#route-handlers */ get_secured : middlewareisAuthenticated { res; } /* Will be translated to get("/people/:id") (parameters automatically extracted from function parameters) */ { res; } /* Will be translated to get("/people/:id/friends") (if parameter is included in function-name, it will be be included in the same position) */ { res; } /* Will be translated to get("/people/:userName/friend-requests") (non parameter parts that use camelCase will be separated by hyphens in the url) */ { res; }
If you have controllers in nested directories then the directory name will automatically be appended in the route. So if you have a controller inside a nested directory like controllers/api/v1/UserController.js
then the generated route will be /api/v1/user
.