MasterController
Routing
Map URLs to controller actions — one at a time, or a full REST resource.
Routes live in app/routes.js, loaded once at startup by startMVC(). Each route maps a URL + HTTP method to a controller#action.
Defining routes#
app/routes.js
import master from 'mastercontroller';
const router = master.router.start();
// Basic route
router.route('/health', 'health#index', 'get');
// Route parameters (casing preserved!)
router.route('/period/:periodId/items/:itemId', 'period#show', 'get');
// RESTful resource — generates the full set of routes
router.resources('posts');router.route(path, toPath, method, constraint?)#
path— URL, with:paramsegments.toPath—'controller#action'.method—'get','post','put','patch','delete'.constraint— optional guard function (see below).
RESTful resources#
router.resources('posts') generates the conventional routes:
generated routes
GET /posts -> posts#index
GET /posts/new -> posts#new
POST /posts -> posts#create
GET /posts/:id -> posts#show
GET /posts/:id/edit -> posts#edit
PUT /posts/:id -> posts#update
DELETE /posts/:id -> posts#destroy Tip
For a JSON API you typically register the five data routes explicitly (index/show/create/update/destroy) — which is exactly what
master generate scaffold does.Reading route parameters#
Parameter casing is preserved, so :periodId is available as obj.params.periodId:
javascript
show(obj) {
const periodId = obj.params.periodId; // not "periodid"
this.returnJson({ periodId });
}Route constraints#
Add a guard that runs before the controller — e.g. authentication:
constraint
router.route('/admin', 'admin#index', 'get', function (requestObject) {
if (!isAuthenticated(requestObject)) {
requestObject.response.statusCode = 401;
requestObject.response.end('Unauthorized');
return;
}
this.next(); // continue to the controller
});