2way-router
Advanced tools
Comparing version 1.2.0 to 1.2.1
26
index.js
@@ -59,2 +59,3 @@ var Promise = require('promise'); | ||
this.params = {}; | ||
this.urlResolvers = {}; | ||
@@ -205,2 +206,12 @@ this.registerType(require('./lib/param/NumberParam'), ['int', 'number']); | ||
/** | ||
* @param {string} name | ||
* @param {function} resolver | ||
* @returns {Router} | ||
*/ | ||
Router.prototype.urlResolver = function (name, resolver) { | ||
this.urlResolvers[name] = resolver; | ||
return this; | ||
}; | ||
/** | ||
* @param {string} typeName | ||
@@ -242,8 +253,17 @@ * @param {string} name | ||
Router.prototype.url = function (routeName, params) { | ||
if (this.namedRoutes.hasOwnProperty(routeName)) { | ||
return this.namedRoutes[routeName].url(params); | ||
var _this = this; | ||
function getUrl(routeName, params) { | ||
if (_this.namedRoutes.hasOwnProperty(routeName)) { | ||
return _this.namedRoutes[routeName].url(params); | ||
} | ||
return Promise.reject(Error('no route with name "' + routeName + '"')); | ||
} | ||
return Promise.reject(Error('no route with name "' + routeName + '"')); | ||
if (this.urlResolvers.hasOwnProperty(routeName)) { | ||
return this.urlResolvers[routeName](params || {}, getUrl); | ||
} | ||
return getUrl(routeName, params); | ||
}; | ||
module.exports = Router; |
{ | ||
"name": "2way-router", | ||
"version": "1.2.0", | ||
"version": "1.2.1", | ||
"description": "2-way router", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -252,2 +252,31 @@ /*global describe, xdescribe, it, expect*/ | ||
}); | ||
describe("supports url resolvers:", function () { | ||
var router = new Router(); | ||
router.route("/news/") | ||
.name("news"); | ||
router.route("/news/archive/{year:int}-{month:int}-{day:int}/") | ||
.name("news.archive"); | ||
router.urlResolver("news", function (params, url) { | ||
if (params.date) { | ||
return url("news.archive", { | ||
year: params.date.getFullYear(), | ||
month: params.date.getMonth() + 1, | ||
day: params.date.getDate() | ||
}); | ||
} | ||
return url("news"); | ||
}); | ||
var date = new Date(); | ||
router.url("news").then(function (url) { | ||
expect(url) | ||
.toBe("/news/"); | ||
}); | ||
router.url("news", { date: date }).then(function (url) { | ||
expect(url) | ||
.toBe("/news/archive/" + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "/"); | ||
}); | ||
}); | ||
}); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
36575
928