Skip to content

Commit

Permalink
feat(warn): warn missing params in alias
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed May 1, 2020
1 parent 3fe9812 commit 186e275
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
30 changes: 30 additions & 0 deletions __tests__/warnings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,34 @@ describe('warnings', () => {
router.resolve({ path: '/p', name: 'p', params: { p: 'p' } })
expect('Path "/" was passed with params').not.toHaveBeenWarned()
})

it('warns if an alias is missing params', async () => {
createRouter({
history: createMemoryHistory(),
routes: [{ path: '/:p/:c', alias: ['/:p/c'], component }],
})
expect(
'Alias "/:p/c" and the original record: "/:p/:c" should have the exact same param named "c"'
).toHaveBeenWarned()
})

it('warns if an alias has a param with the same name but different', async () => {
createRouter({
history: createMemoryHistory(),
routes: [{ path: '/:p/:c', alias: ['/:p/:c+'], component }],
})
expect(
'Alias "/:p/:c+" and the original record: "/:p/:c" should have the exact same param named "c"'
).toHaveBeenWarned()
})

it('warns if an alias has extra params', async () => {
createRouter({
history: createMemoryHistory(),
routes: [{ path: '/:p/c', alias: ['/:p/:c'], component }],
})
expect(
'Alias "/:p/:c" and the original record: "/:p/c" should have the exact same param named "c"'
).toHaveBeenWarned()
})
})
28 changes: 28 additions & 0 deletions src/matcher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ export function createRouterMatcher(
// so we can be removed
if (originalRecord) {
originalRecord.alias.push(matcher)
if (__DEV__) {
checkSameParams(originalRecord, matcher)
}
} else {
// otherwise, the first record is the original and others are aliases
originalMatcher = originalMatcher || matcher
Expand Down Expand Up @@ -362,4 +365,29 @@ function mergeOptions<T>(defaults: T, partialOptions: Partial<T>): T {
return options
}

type ParamKey = RouteRecordMatcher['keys'][number]

function isSameParam(a: ParamKey, b: ParamKey): boolean {
return (
a.name === b.name &&
a.optional === b.optional &&
a.repeatable === b.repeatable
)
}

function checkSameParams(a: RouteRecordMatcher, b: RouteRecordMatcher) {
for (let key of a.keys) {
if (!b.keys.find(isSameParam.bind(null, key)))
return warn(
`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`
)
}
for (let key of b.keys) {
if (!a.keys.find(isSameParam.bind(null, key)))
return warn(
`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`
)
}
}

export { PathParserOptions, _PathParserOptions }

0 comments on commit 186e275

Please sign in to comment.