guidance v0.3.0
Guidance
A Rails like middleware for routes loading on expressjs applications. (heavily inspired from http://guides.rubyonrails.org/routing.html)
Purposes & use
This module provide a Rails like approach for defining routes.
It also add helpers for the views appending it to the res.locals object.
Required configuration:
First of all define your controllers.
They are simple exported objects where the filename is the controller name, object keys are the controller's actions, and the object values are the route handlers.
Default location of the controllers is process.cwd() + '/controllers'
// controllers/welcomeController.js
module.exports = {
index: function(req, res) {
return res.json({ hello: 'welcome' });
},
about: function(req, res) {
return res.json({ hi: 'this is guidance' });
}
};Routes should be defined as a module that exports a function accepting the router object as parameter. Use the router object to define your routes.
Define your routes like this (usually in a separated routes.js file):
// routes.js
module.exports = function(router) {
router.get('/', { to: 'welcome#index' });
router.get('/about', { to: 'welcome#about' });
};This snippets indicate that on GET / the express app respond with welcome controller's index action, and GET /about is mapped to the welcome controller's about action.
Finally use the middleware like this:
const express = require('express');
const guidance = require('guidance');
const routes = require('routes'); // the module defined above (routes.js)
const app = express();
app.use(guidance.initialize(routes));
...Naming conventions
Some conventions are adopted for the correct mapping of the routes.
controllers
When referring to a controller name, the controller file is resolved to <controllersPath>/<controllerName>.js
where:
- controllersPath is default to
process.cwd() + '/controllers'(overridable withguidance.initializeoptions). - controllerName resolves to the controller name without an eventual
Controllersuffix (welcomeController and welcome both becomes welcome)
actions
When referring to an action name, the action handler is mapped to the relative controller's property with the same name.
An eventual Action suffix is removed from the name (indexAction and index both becomes index)
The controller's property should be obviously a callable.
Reference
Guidance
guidance.initialize(routes, options)
guidance middleware.
Accepted parameters:
- routes the defined routes module
- options.controllersDir the absolute path where to locate the controller modules. Defaults to
process.cwd() + '/controllers'
Router
Basic routing
Connect URLs to code in the following way (using the to key)
router.get('/home', { to: 'welcome#index' })
router.post('/login', { to: 'session#create' })When the express app receive a GET /home request, the index action handler of the welcome controller is used; the express app responds also on POST /login with the session controller's create action.
Any express supported method (router.METHOD) can be used.
Root
You can specify how to route GET / with the root method:
router.root({ to: 'welcome#index' })
router.root('welcome#index') // shortcut for the aboveNamed parameters
Named parameters are also supported:
router.get('/patients/:id', { to: 'patients#show' })the id parameter is available to the req.params object of the action.
Named routes (views helpers)
A name can be assigned to the route (using the as key):
router.get('/hp', { to: 'welcome#homepage', as: 'homepage' });
router.get('/patients/:id', { to: 'patients#show', as 'patient' })This helpers are available to the views:
homepage() // returns '/hp'
patient(42) // returns '/patients/42'Resources
Resources can also be defined:
router.resources('photos')This statement creates the following routes:
GET /photosto photos#indexGET /photos/newto photos#newPOST /photosto photos#createGET /photos/:idto photos#show with id as parameterGET /photos/:id/editto photos#edit with _id as parameterPATCH /photos/:idto photos#update with _id as parameterPUT /photos/:idto photos#update with _id as parameterDELETE /photos/:idto photos#delete with _id as parameter
It also creates the following helpers:
photosPath()returns/photosnewPhotoPath()returns/photos/neweditPhotoPath(42)returns/photos/42/editphotoPath(42)returns/photos/42
Multiple resources can be defined at the same time:
router.resources(['photos', 'books']);Single resource
Single resource can be defined:
router.resource('geocoder');This statement creates the following routes:
GET /geocoder/newto geocoder#newPOST /geocoderto photos#createGET /geocoderto geocoder#showGET /geocoder/editto _geocoder#editPATCH /geocoderto _geocoder#updatePUT /geocoderto _geocoder#updateDELETE /geocoderto _geocoder#delete
It also creates the following helpers:
geocoderPath()returns/geocodernewGeocoderPath()returns/geocoder/neweditGeocoderPath(42)returns/geocoder/42/edit
Multiple single resources can be defined at the same time:
router.resource(['geocoder', 'profile']);Nesting resources
Resources can be nested:
router.resources('magazines', function() {
router.resources('ads');
});In this case for example the express app can respond to GET /magazines/42/ads/7 path.
It adds to req.params the following attributes:
magazineId(in this case: 42)id(in this case: 7)
Namespace
Routes can be namespaced. In this case the controller should exists in a directory with the same name of the namespace.
router.namespace('admin', function() {
router.resources('articles');
});In this case the article resource's actions are mapped to the following paths:
GET /admin/articlesGET /admin/articles/newPOST /admin/articlesGET /admin/articles/:idGET /admin/articles/:id/editPATCH /admin/articles/:idPUT /admin/articles/:idDELETE /admin/articles/:id
Scopes
Routes can be also scoped. In this case the controller should exists in a directory with the same name of the scope.
router.scope('admin', function() {
router.resources('articles');
});The difference with the namespace is that the routes paths don't have a prefix, but the controller lives inside a directory with the same name of the scope.
Fluent interface
Guidance router have a fluent interface, so it can be used in this way:
router
.get('/geocoder', { to: 'geocoder#show' })
.namespace('admin', function() {})
.resources('books')
.resource('geocoder')
.scope('admin', function() {})
.root('welcome#index')
.post('/photos', { to: 'photos#create' })
;Notes
A modern version of node is required (due to harmony syntax). Actually tested with node v4.4.1 LTS.