Skip to content

Commit 5c8cd6e

Browse files
committed
feat(warn): warn multiple params with same name
1 parent 2086a59 commit 5c8cd6e

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

__tests__/warnings.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,4 +146,21 @@ describe('warnings', () => {
146146
await expect(router.push({ path: '//not-valid' })).resolves.toBe(undefined)
147147
expect('cannot start with multiple slashes').toHaveBeenWarned()
148148
})
149+
150+
it('warns if path contains the same param multiple times', () => {
151+
const history = createMemoryHistory()
152+
createRouter({
153+
history,
154+
routes: [
155+
{
156+
path: '/:id',
157+
component,
158+
children: [{ path: ':id', component }],
159+
},
160+
],
161+
})
162+
expect(
163+
'duplicated params with name "id" for path "/:id/:id"'
164+
).toHaveBeenWarned()
165+
})
149166
})

src/matcher/pathMatcher.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
PathParserOptions,
66
} from './pathParserRanker'
77
import { tokenizePath } from './pathTokenizer'
8+
import { warn } from '../warning'
89

910
export interface RouteRecordMatcher extends PathParser {
1011
record: RouteRecord
@@ -20,6 +21,19 @@ export function createRouteRecordMatcher(
2021
options?: PathParserOptions
2122
): RouteRecordMatcher {
2223
const parser = tokensToParser(tokenizePath(record.path), options)
24+
25+
// warn against params with the same name
26+
if (__DEV__) {
27+
const existingKeys = new Set<string>()
28+
for (const key of parser.keys) {
29+
if (existingKeys.has(key.name))
30+
warn(
31+
`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`
32+
)
33+
existingKeys.add(key.name)
34+
}
35+
}
36+
2337
const matcher: RouteRecordMatcher = {
2438
...parser,
2539
record,

0 commit comments

Comments
 (0)