diff --git a/src/index.js b/src/index.js index 358076c..fdcfcb6 100644 --- a/src/index.js +++ b/src/index.js @@ -65,8 +65,13 @@ function validate({sourcePath, matchedPath, matchedValue, routes}) { let path = matchedPath ? validatePath(sourcePath, matchedPath) : null let value = matchedValue if (!path) { - path = routes[`*`] ? sourcePath : null - value = path ? routes[`*`] : null + if (sourcePath === `/`) { + path = routes[`*`] ? sourcePath : null + value = path ? routes[`/$`] : null + } else { + path = routes[`*`] ? sourcePath : null + value = path ? routes[`*`] : null + } } return {path, value} } @@ -76,7 +81,20 @@ function switchPath(sourcePath, routes) { let matchedPath = null let matchedValue = null - traverseRoutes(routes, function matchPattern(pattern) { + traverseRoutes(routes, function matchPattern(pattern) { // eslint-disable-line complexity, max-len + if (pattern[pattern.length - 1] === `$`) { + const realPattern = pattern.split(`/$`).join(``) + if (sourcePath.search(realPattern) === 0 && + betterMatch(pattern, matchedPath) || + sourcePath.search(realPattern + `/`) && + betterMatch(pattern, matchedPath)) + { + matchedPath = realPattern + matchedValue = routes[pattern] + } + return + } + if (sourcePath.search(pattern) === 0 && betterMatch(pattern, matchedPath)) { matchedPath = pattern matchedValue = routes[pattern] @@ -105,7 +123,6 @@ function switchPath(sourcePath, routes) { } } }) - return validate({sourcePath, matchedPath, matchedValue, routes}) } diff --git a/test/index.js b/test/index.js index 7c81e71..46c4a11 100644 --- a/test/index.js +++ b/test/index.js @@ -175,6 +175,38 @@ describe('switchPath basic usage', () => { expect(path).to.be.equal('/1736'); expect(value).to.be.equal('id is 1736'); }); + + it('should match routes explicitly using `$`', () => { + const {path, value} = switchPath('/', { + '/$': 123, + '/other': 456, + '*': 'not found route' + }) + + expect(path).to.be.equal('/'); + expect(value).to.be.equal(123); + }) + + it('should match routes explicitly using `$`', () => { + const {path, value} = switchPath('/other', { + '/': 123, + '/other/$': 456 + }) + + expect(path).to.be.equal('/other'); + expect(value).to.be.equal(456); + }) + + it('should allow opting out of partial matching for routes using `$`', () => { + const {path, value} = switchPath('/random', { + '/$': 123, + '/other': 456, + '*': 'not found route' + }); + + expect(path).to.be.equal('/random'); + expect(value).to.be.equal('not found route'); + }); }); describe('switchPath corner cases', () => {