Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to pass name/options as third argument in standalone mode #26

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,8 @@ information, see https://github.com/alubbe/named-routes/issues/13.
var Router = require('named-routes')();
var router = new Router();

router.add('get', '/admin/user/:id', function(req, res, next) {
router.add('get', '/admin/user/:id', 'admin.user.edit', function(req, res, next) {
var url = router.build('admin.user.edit', {id: 2}); // /admin/user/2
}, {
name: 'admin.user.edit'
});

//... in a request handler
Expand Down Expand Up @@ -110,8 +108,8 @@ app.namedRoutes.build('todo.user.list.id', {user: 'foo', list: 93}) // Throws er
As a standalone:

```js
router.add('get', '/about', function(req, res, next) {...}, {name:'about'})
router.add('get', '/todo/:user/:list/:id', function(req, res, next) {...}, {name:'todo.user.list.id'})
router.add('get', '/about', 'about', function(req, res, next) {...})
router.add('get', '/todo/:user/:list/:id', 'todo.user.list.id', function(req, res, next) {...})

router.build('about') // '/about'
router.build('todo.user.list.id', {user: 'foo', list: 93, id: 1337}) // '/todo/foo/93/1337'
Expand Down Expand Up @@ -195,10 +193,8 @@ url('admin.user.edit', {id:2, _masked: ['any','thing']})

### Converting the trailing `*` anonymous parameter to multiple `name:value` parameters
```js
router.add('get', '/admin/*/user/*/:id/albums/*', 'admin.user.edit', function(req, res, next) {
router.add('get', '/admin/*/user/*/:id/albums/*', {name: 'admin.user.edit', wildcardInPairs: true}, function(req, res, next) {
console.log(req.params)
}, {
wildcardInPairs: true
});
```
Requesting: `/admin/any/user/thing/2/albums/sort/name/order/desc` will output:
Expand Down
45 changes: 27 additions & 18 deletions router.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,30 +57,39 @@ Router.prototype.match = function (req) {
return false;
}

var flatten = function (arr, ret) {
var ret = ret || [];
for (var i = 0, len = arr.length; i < len; ++i) {
if (Array.isArray(arr[i])) {
flatten(arr[i], ret);
} else {
ret.push(arr[i]);
}
}
return ret;
}

/**
* Registers new route
* @param method
* @param path
* @param callbacks
* @param options
* @param callback
*/
Router.prototype.add = function (method, path, callbacks, options) {
function flatten(arr, ret) {
var ret = ret || []
, len = arr.length;
for (var i = 0; i < len; ++i) {
if (Array.isArray(arr[i])) {
flatten(arr[i], ret);
} else {
ret.push(arr[i]);
}
}
return ret;
}
Router.prototype.add = function (method, path, callback) {
var hasOptions = (typeof callback !== 'function' && !Array.isArray(callback));
var callbacks = [].slice.call(arguments, 2);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slicing arguments prevents the whole function from being optimized by v8. I think that instead we should change the function to expect four arguments (method, path, options, callbacks) and, if options is a function or an array, set callbacks to options (or [options]) and then set options to an empty object.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I know and my first version was using Bluebird workaround, but even then function was marked as not optimized. Instead, I've used what was in the code:
https://github.com/visualfanatic/named-routes/blob/d24b2538213279cca0437224e8afbc30d36c1338/router.js#L312

var options = {};

callbacks = [callbacks]
method = method.toLowerCase();
options = options || {};

if (hasOptions) {
if (typeof callback === 'string') {
options['name'] = callback;
} else {
options = callback;
}
callbacks.shift();
}

this.routesByMethodAndPath[method] = this.routesByMethodAndPath[method] || {};
options.caseSensitive = options.caseSensitive == undefined ? this.caseSensitive : options.caseSensitive;
Expand Down Expand Up @@ -311,7 +320,7 @@ Router.prototype.extendExpress = function (app) {
next();
};
}
this.namedRoutes.add(method, path, [], {name: name});
this.namedRoutes.add(method, path, name, []);
return originalMethod.apply(this, args);
}
});
Expand Down
25 changes: 6 additions & 19 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,7 @@ module.exports = {
params: {}
};

self.router.add('get', '/admin/user/:id', routeSpy, {
name: 'admin.user.edit'
});
self.router.add('get', '/admin/user/:id', 'admin.user.edit', routeSpy);

self.router.dispatch(req, {}, function(){ });

Expand Down Expand Up @@ -151,9 +149,7 @@ module.exports = {
this.router.build('invalid route Name');
}).to.throwError();

self.router.add('post', '(/:controller(/:action(/:id)))', spy, {
'name': 'reversed'
});
self.router.add('post', '(/:controller(/:action(/:id)))', 'reversed', spy);

expect(self.router.build('reversed', {
'controller': 'Home',
Expand All @@ -167,19 +163,15 @@ module.exports = {

expect(spy.called).to.equal(true);

self.router.add('post', '/todo/:user/:list/:id', spy, {
'name': 'ajax'
});
self.router.add('post', '/todo/:user/:list/:id', 'ajax', spy);

expect(self.router.build('ajax', {
'user': 'foo',
'list': null,
'id': null
})).to.equal('/todo/foo');

self.router.add('get', '/admin/(user/(edit/:id/)(album/:albumId/):session/)test', spy, {
name: 'optionals'
});
self.router.add('get', '/admin/(user/(edit/:id/)(album/:albumId/):session/)test', 'optionals', spy);

expect(self.router.build('optionals', {
id: 4,
Expand Down Expand Up @@ -211,9 +203,7 @@ module.exports = {
next = sinon.spy(),
spy = sinon.spy();

self.router.add('get', '/admin/*/user/*/:id', spy, {
name: 'admin.user.edit'
});
self.router.add('get', '/admin/*/user/*/:id', 'admin.user.edit', spy);

req = {
method: 'get',
Expand All @@ -228,10 +218,7 @@ module.exports = {
id:2, _masked: ['any','thing']
})).to.equal('/admin/any/user/thing/2');

self.router.add('get', '/admin/*/user/*/:id/albums/*', spy, {
wildcardInPairs: true,
name: 'admin.user.edit2'
});
self.router.add('get', '/admin/*/user/*/:id/albums/*', {wildcardInPairs: true, name: 'admin.user.edit2'}, spy);

req = {
method: 'get',
Expand Down