From 5c8cd6e8ae1223e9871252cc617b19424f01c5c2 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Sun, 24 May 2020 11:27:38 +0200 Subject: [PATCH] feat(warn): warn multiple params with same name --- __tests__/warnings.spec.ts | 17 +++++++++++++++++ src/matcher/pathMatcher.ts | 14 ++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/__tests__/warnings.spec.ts b/__tests__/warnings.spec.ts index ec25c745..26255078 100644 --- a/__tests__/warnings.spec.ts +++ b/__tests__/warnings.spec.ts @@ -146,4 +146,21 @@ describe('warnings', () => { await expect(router.push({ path: '//not-valid' })).resolves.toBe(undefined) expect('cannot start with multiple slashes').toHaveBeenWarned() }) + + it('warns if path contains the same param multiple times', () => { + const history = createMemoryHistory() + createRouter({ + history, + routes: [ + { + path: '/:id', + component, + children: [{ path: ':id', component }], + }, + ], + }) + expect( + 'duplicated params with name "id" for path "/:id/:id"' + ).toHaveBeenWarned() + }) }) diff --git a/src/matcher/pathMatcher.ts b/src/matcher/pathMatcher.ts index fd4745dc..f9bfcf6e 100644 --- a/src/matcher/pathMatcher.ts +++ b/src/matcher/pathMatcher.ts @@ -5,6 +5,7 @@ import { PathParserOptions, } from './pathParserRanker' import { tokenizePath } from './pathTokenizer' +import { warn } from '../warning' export interface RouteRecordMatcher extends PathParser { record: RouteRecord @@ -20,6 +21,19 @@ export function createRouteRecordMatcher( options?: PathParserOptions ): RouteRecordMatcher { const parser = tokensToParser(tokenizePath(record.path), options) + + // warn against params with the same name + if (__DEV__) { + const existingKeys = new Set() + for (const key of parser.keys) { + if (existingKeys.has(key.name)) + warn( + `Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".` + ) + existingKeys.add(key.name) + } + } + const matcher: RouteRecordMatcher = { ...parser, record, -- 2.47.3