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

Add routes in order of depth in 'on' method #39

Merged
merged 4 commits into from
Sep 13, 2016
Merged
Show file tree
Hide file tree
Changes from all 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
52 changes: 34 additions & 18 deletions lib/navigo.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/navigo.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/navigo.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/navigo.min.js.map

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ function replaceDynamicURLParts(route) {
return { regexp, paramNames };
}

function getUrlDepth(url) {
return url.replace(/\/$/, '').split('/').length;
}

function compareUrlDepth(urlA, urlB) {
return getUrlDepth(urlA) < getUrlDepth(urlB);
}

function findMatchedRoutes(url, routes = []) {
return routes
.map(route => {
Expand Down Expand Up @@ -122,9 +130,11 @@ Navigo.prototype = {
if (args.length >= 2) {
this._add(args[0], args[1]);
} else if (typeof args[0] === 'object') {
for (let route in args[0]) {
let orderedRoutes = Object.keys(args[0]).sort(compareUrlDepth);

orderedRoutes.forEach(route => {
this._add(route, args[0][route]);
}
});
} else if (typeof args[0] === 'function') {
this._defaultHandler = args[0];
}
Expand Down
14 changes: 14 additions & 0 deletions test/Navigo.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,20 @@ describe('Given an instance of Navigo', function () {
.to.be.calledOnce
.and.to.be.calledWith({ tripId: '42' });
});
it('should set the routes in order of depth', function () {
var handler = sinon.spy();

router = new Navigo('http://site.com/', true);
router.on({
'products': { as: 'products', uses: handler },
'products/:productId': { as: 'products.id', uses: handler}
});
router.resolve('products/42');

expect(handler)
.to.be.calledOnce
.and.to.be.calledWith({ productId: '42' })
});
});
});

Expand Down