Skip to content

Commit

Permalink
Support optional params on root (#367)
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Collina <hello@matteocollina.com>
  • Loading branch information
mcollina committed Apr 30, 2024
1 parent 984ff20 commit cce5437
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
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)
})

0 comments on commit cce5437

Please sign in to comment.