Skip to content

Commit 961190e

Browse files
committed
chore: ignore trailing for optional/zero-or-more params
1 parent 23ea6e8 commit 961190e

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

src/index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,27 @@ function matchTokens(
273273
}
274274
}
275275

276+
// If this literal ends with '/' and the only remaining token is
277+
// an optional/zero-or-more param, try matching without the trailing
278+
// slash. This allows `/users` to match pattern `/users/:id?`.
279+
if (
280+
token.value.charCodeAt(token.value.length - 1) === SLASH &&
281+
i + 1 === tokens.length - 1
282+
) {
283+
const nextToken = tokens[i + 1]
284+
if (
285+
nextToken.type === TokenType.Param &&
286+
(nextToken.modifier === '?' || nextToken.modifier === '*')
287+
) {
288+
const trimmed = token.value.slice(0, -1)
289+
if (inputString.startsWith(trimmed, position)) {
290+
position += trimmed.length
291+
i++
292+
continue
293+
}
294+
}
295+
}
296+
276297
return NO_MATCH
277298
}
278299

tests/index.test.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,11 @@ it.each<
175175
'http://localhost/:param?/settings',
176176
MATCHES_WITHOUT_PARAMS,
177177
],
178+
[
179+
'http://localhost/user',
180+
'http://localhost/user/:id?',
181+
MATCHES_WITHOUT_PARAMS,
182+
],
178183

179184
/* One or more path parameter (+) */
180185
[
@@ -313,7 +318,11 @@ it.each<
313318
[new URL('http://localhost'), 'http://localhost/', MATCHES_WITHOUT_PARAMS],
314319
[new URL('http://localhost/'), 'http://localhost', MATCHES_WITHOUT_PARAMS],
315320
[new URL('http://localhost/'), 'http://localhost/', MATCHES_WITHOUT_PARAMS],
316-
[new URL('http://localhost/user/'), 'http://localhost/user', MATCHES_WITHOUT_PARAMS],
321+
[
322+
new URL('http://localhost/user/'),
323+
'http://localhost/user',
324+
MATCHES_WITHOUT_PARAMS,
325+
],
317326
[
318327
new URL('http://localhost/user/'),
319328
'http://localhost/user/',

0 commit comments

Comments
 (0)