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

Support optional params on root #367

Merged
merged 1 commit into from
Apr 30, 2024
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
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Router.prototype.on = function on (method, path, opts, handler, store) {
assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path')

const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2')
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2')
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2') || '/'

this.on(method, pathFull, opts, handler, store)
this.on(method, pathOptional, opts, handler, store)
Expand Down
20 changes: 20 additions & 0 deletions test/optional-params.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,23 @@ test('deregister a route with optional param', (t) => {
t.notOk(findMyWay.find('GET', '/a/:param/b'))
t.notOk(findMyWay.find('GET', '/a/:param/b/:optional'))
})

test('optional parameter on root', (t) => {
t.plan(2)
const findMyWay = FindMyWay({
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})

findMyWay.on('GET', '/:optional?', (req, res, params) => {
if (params.optional) {
t.equal(params.optional, 'foo')
} else {
t.equal(params.optional, undefined)
}
})

findMyWay.lookup({ method: 'GET', url: '/', headers: {} }, null)
findMyWay.lookup({ method: 'GET', url: '/foo', headers: {} }, null)
})