-
Notifications
You must be signed in to change notification settings - Fork 135
/
router.js
437 lines (400 loc) · 12.8 KB
/
router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/**
* Module dependencies.
*/
var lingo = require('lingo')
, util = require('util')
, utils = require('./utils')
, Namespace = require('./namespace')
, Route = require('./route')
, RouterError = require('./errors').RouterError;
/**
* `Router` constructor.
*
* @api private
*/
function Router(app) {
this._app = app;
this._routes = {};
this._ns = [];
this._ns.push(new Namespace());
}
/**
* Initialize `Router`.
*
* Options:
* - `handle` override default handler function factory
*
* @param {express} http
* @param {Object} options
* @api protected
*/
Router.prototype.init = function(http, options) {
options = options || {};
// Save instance of low-level Express HTTP server. Routes drawn through
// Locomotive's router will be compiled into Express routes.
this._http = http;
this._handle = options.handle || handle;
}
/**
* Draw routes.
*
* Executes `fn` in the context of the `Router` instance.
*
* @param {Function} fn
* @api protected
*/
Router.prototype.draw = function(fn) {
fn.apply(this);
}
/**
* Create a route to the root path ('/').
*
* For options, see `match()`, as `root()` invokes it internally.
*
* The root route should be placed at the top of `config/routes.js` in order to
* match against it first. As this route is typically the most popular route of
* a web application, this is an optimization.
*
* Examples:
*
* this.root('pages#main');
*
* @param {String|Object} shorthand
* @param {Object} options
* @api public
*/
Router.prototype.root = function(shorthand, options) {
this.match('', shorthand, options);
}
/**
* Create a route matching `pattern`.
*
* A route that will be handled by `SongsController.show()` can be specified
* using shorthand notation:
*
* this.match('songs/:title', 'songs#show');
*
* which is equivalent to using `controller` and `action` options.
*
* this.match('songs/:title', { controller: 'songs', action: 'show' });
*
*
* If an `as` option is specified, path and URL routing helper functions will be
* dynamically declared. For example, given the following route:
*
* this.match('bands/:id', 'bands#show', { as: 'bands' });
*
* the following routing helpers will be available to views:
*
* bandsPath(101)
* // => "/bands/101"
* bandsPath('counting-crows')
* // => "/bands/counting-crows"
* bandsPath({ id: 'ABC123' })
* // => "/bands/ABC123"
*
* bandsURL(101)
* // => "http://www.example.com/bands/101"
* bandsPath('counting-crows')
* // => "http://www.example.com/bands/counting-crows"
* bandsPath({ id: 'ABC123' })
* // => "http://www.example.com/bands/ABC123"
*
*
* Options:
*
* - 'controller' the route's controller
* - 'action' the route's action
* - `as` name used to declare routing helpers
* - `via` allowed HTTP method(s) for route
*
* Examples:
*
* this.match('songs/:title', 'songs#show');
*
* this.match('songs/:title', { controller: 'songs', action: 'show' });
*
* this.match('bands', 'bands#create', { via: 'post' });
*
* @param {String} pattern
* @param {String|Object} shorthand
* @param {Object} options
* @api public
*/
Router.prototype.match = function(pattern, shorthand, options) {
if (!options && typeof shorthand === 'object') {
options = shorthand;
}
options = options || {};
if (typeof shorthand === 'string') {
var split = shorthand.split('#');
options.controller = split[0];
options.action = split[1];
}
var ns = this._ns[this._ns.length - 1]
, method = options.via || 'get'
, path = ns.qpath(pattern)
, controller = ns.qcontroller(options.controller)
, action = utils.actionize(options.action)
, helper = utils.helperize(options.as);
// TODO: Support specifying an array of methods in the `via` option.
if (typeof shorthand === 'function' || Array.isArray(shorthand)) {
// TODO: Implement unit test coverage for this functionality.
// Mount functions or arrays of functions directly as Express route
// handlers/middleware.
this._http[method](path, shorthand);
return;
}
this._route(method.toLowerCase(), path, controller, action, { helper: helper });
}
/**
* Create resourceful routes for singleton resource `name`.
*
* A resourceful route provides a mapping between HTTP URLs and methods and
* corresponding controller actions. A single entry in the route configuration,
* such as:
*
* this.resource('profile');
*
* creates six different routes in the application, all handled by
* `ProfileController` (note that the controller is singular).
*
* GET /profile/new -> new()
* POST /profile -> create()
* GET /profile -> show()
* GET /profile/edit -> edit()
* PUT /profile -> update()
* DELETE /profile -> destroy()
*
* Additionally, path and URL routing helpers will be dynamically declared.
*
* profilePath()
* // => "/profile"
* newProfilePath()
* // => "/profile/new"
* editAccountPath()
* // => "/profile/edit"
*
* profileURL()
* // => "http://www.example.com/profile"
* newProfileURL()
* // => "http://www.example.com/profile/new"
* editAccountURL()
* // => "http://www.example.com/profile/edit"
*
* The singleton variation of a resourceful route is useful for resources which
* are referenced without an ID, such as /profile, which always shows the
* profile of the currently logged in user. In this case, a singular resource
* maps /profile (rather than /profile/:id) to the show action.
*
* Examples:
*
* this.resource('profile');
*
* @param {String} name
* @api public
*/
Router.prototype.resource = function(name, options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
options = options || {}
var ns = this._ns[this._ns.length - 1]
, path = ns.qpath(name)
, controller = ns.qcontroller(name)
, helper = ns.qhelper(name);
// TODO: Ensure that optional format placeholders are available and handled
// correctly.
// TODO: Implement support for dasherized names.
this._route('get' , path + '/new' , controller, 'new' , { helper: utils.helperize('new', helper) });
this._route('post', path , controller, 'create' );
this._route('get' , path + '.:format?', controller, 'show' , { helper: helper });
this._route('get' , path + '/edit' , controller, 'edit' , { helper: utils.helperize('edit', helper) });
this._route('put' , path , controller, 'update' );
this._route('del' , path , controller, 'destroy');
this.namespace(name, { module: options.namespace ? name : null, helper: name }, function() {
fn && fn.call(this);
});
}
/**
* Create resourceful routes for collection resource `name`.
*
* A resourceful route provides a mapping between HTTP URLs and methods and
* corresponding controller functions. A single entry in the route
* configuration, such as:
*
* this.resources('photos');
*
* creates seven different routes in the application, executed by
* `PhotosController`.
*
* GET /photos -> index()
* GET /photos/new -> new()
* POST /photos -> create()
* GET /photos/:id -> show()
* GET /photos/:id/edit -> edit()
* PUT /photos/:id -> update()
* DELETE /photos/:id -> destroy()
*
* Additionally, path and URL routing helpers will be dynamically declared.
*
* photosPath()
* // => "/photos"
* photoPath('abc123')
* // => "/photos/abc123"
* newPhotoPath()
* // => "/photos/new"
* editPhotoPath('abc123')
* // => "/photos/abc123/edit"
*
* Resources can also be nested infinately using callback syntax:
*
* router.resources('bands', function() {
* this.resources('albums');
* });
*
* Examples:
*
* this.resources('photos');
*
* @param {String} name
* @api public
*/
Router.prototype.resources = function(name, options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
options = options || {}
var ns = this._ns[this._ns.length - 1]
, singular = lingo.en.singularize(name)
, path = ns.qpath(name)
, controller = ns.qcontroller(name)
, helper = ns.qhelper(singular)
, collectionHelper = ns.qhelper(name)
, placeholder;
// TODO: Ensure that optional format placeholders are available and handled
// correctly.
this._route('get' , path , controller, 'index' , { helper: collectionHelper });
this._route('get' , path + '/new' , controller, 'new' , { helper: utils.helperize('new', helper) });
this._route('post', path , controller, 'create' );
this._route('get' , path + '/:id.:format?' , controller, 'show' , { helper: helper });
this._route('get' , path + '/:id/edit' , controller, 'edit' , { helper: utils.helperize('edit', helper) });
this._route('put' , path + '/:id' , controller, 'update' );
this._route('del' , path + '/:id' , controller, 'destroy');
// TODO: I think placeholder should be underscored. Test for this.
// TODO: Implement support for dasherized names.
placeholder = ':' + utils.helperize(singular) + '_id';
this.namespace(name + '/' + placeholder, { module: options.namespace ? name : null, helper: singular }, function() {
fn && fn.call(this);
});
}
/**
* Create namespace in which to organize routes.
*
* Typically, you might want to group administrative routes under an `admin`
* namespace. Controllers for these routes would be placed in the `app/controllers/admin`
* directory.
*
* A namespace with resourceful routes, such as:
*
* this.namespace('admin', function() {
* this.resources('posts');
* });
*
* creates namespaced routes handled by `Admin::PostsController`:
*
* GET /admin/posts
* GET /admin/posts/new
* POST /admin/posts
* GET /admin/posts/:id
* GET /admin/posts/:id/edit
* PUT /admin/posts/:id
* DELETE /admin/posts/:id
*
* @param {String} name
* @param {Function} fn
* @api public
*/
Router.prototype.namespace = function(name, options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
options = options || {};
var ns = this._ns[this._ns.length - 1];
this._ns.push(new Namespace(name, options, ns));
fn.call(this);
this._ns.pop();
}
/**
* Create route from `method` and `pattern` to `controller` and `action`.
*
* @param {String} method
* @param {String} pattern
* @param {String} controller
* @param {String} action
* @api private
*/
Router.prototype._route = function(method, pattern, controller, action, options) {
options = options || {};
// Mount the route handler in the underlying Express HTTP framework. This
// handler will service incoming requests that match the route.
this._http[method](pattern, this._handle(controller, action).bind(this._app));
// Add the route to the reverse routing table. The reverse routing table is
// used by routing helper functions to construct URLs to a specific controller
// and action. When building paths and URLs, routes declared first take
// priority. Therefore, if there is already an entry for this controller and
// action in the table, don't overwrite it.
var route = new Route(method, pattern, controller, action);
var key = route.reverseKey();
if (!this._routes[key]) {
this._routes[key] = route;
}
// Declare path and URL routing helper functions.
if (options.helper) {
var helper = options.helper;
this._app.helper(helper + 'Path', route.helper());
this._app.dynamicHelper(helper + 'URL', route.helper(true));
}
}
/**
* Find route to `controller` and `action`.
*
* @param {String} controller
* @param {String} action
* @return {Route}
* @api protected
*/
Router.prototype.find = function(controller, action) {
var key = controller + '#' + action;
return this._routes[key];
}
/**
* Builds a function to handle a route with given `controller` and `action`.
*
* @param {String} controller
* @param {String} action
* @return {Function}
* @api private
*/
function handle(controller, action) {
return function(req, res, next){
var prototype = this.controller(controller);
if (!prototype) {
return next(new RouterError('No controller for ' + controller + '#' + action));
}
// Create a new instance of the controller from the prototype. The
// prototype acts as a "factory" from which an instance is created for each
// request. This allows request-specific properties to be assigned to each
// instance, without causing conflicts due to concurrency.
var instance = Object.create(prototype);
instance._init(req, res, next);
instance._invoke(action);
}
}
/**
* Expose `Router`.
*/
exports = module.exports = Router;