Skip to content

Commit cce5437

Browse files
authored
Support optional params on root (#367)
Signed-off-by: Matteo Collina <hello@matteocollina.com>
1 parent 984ff20 commit cce5437

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ Router.prototype.on = function on (method, path, opts, handler, store) {
115115
assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path')
116116

117117
const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2')
118-
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2')
118+
const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2') || '/'
119119

120120
this.on(method, pathFull, opts, handler, store)
121121
this.on(method, pathOptional, opts, handler, store)

test/optional-params.test.js

+20
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,23 @@ test('deregister a route with optional param', (t) => {
195195
t.notOk(findMyWay.find('GET', '/a/:param/b'))
196196
t.notOk(findMyWay.find('GET', '/a/:param/b/:optional'))
197197
})
198+
199+
test('optional parameter on root', (t) => {
200+
t.plan(2)
201+
const findMyWay = FindMyWay({
202+
defaultRoute: (req, res) => {
203+
t.fail('Should not be defaultRoute')
204+
}
205+
})
206+
207+
findMyWay.on('GET', '/:optional?', (req, res, params) => {
208+
if (params.optional) {
209+
t.equal(params.optional, 'foo')
210+
} else {
211+
t.equal(params.optional, undefined)
212+
}
213+
})
214+
215+
findMyWay.lookup({ method: 'GET', url: '/', headers: {} }, null)
216+
findMyWay.lookup({ method: 'GET', url: '/foo', headers: {} }, null)
217+
})

0 commit comments

Comments
 (0)