Skip to content
Closed
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
25 changes: 21 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
Expand All @@ -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]
Expand Down Expand Up @@ -105,7 +123,6 @@ function switchPath(sourcePath, routes) {
}
}
})

return validate({sourcePath, matchedPath, matchedValue, routes})
}

Expand Down
32 changes: 32 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down