Skip to content

Commit

Permalink
fix(matcher): override records by name when adding
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed May 24, 2020
1 parent 8b0ea66 commit 07100fc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions __tests__/matcher/addingRemoving.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,16 @@ describe('Matcher: adding and removing records', () => {
expect(matcher.getRecordMatcher('child')).toBe(undefined)
})

it('removes existing record when adding with the same name', () => {
const matcher = createRouterMatcher([], {})
matcher.addRoute({ path: '/', component, name: 'home' })
matcher.addRoute({ path: '/home', component, name: 'home' })
expect(matcher.getRoutes()).toHaveLength(1)
expect(matcher.resolve({ path: '/home' }, currentLocation)).toMatchObject({
name: 'home',
})
})

describe('warnings', () => {
mockWarn()

Expand Down
5 changes: 5 additions & 0 deletions src/matcher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export function createRouterMatcher(
parent?: RouteRecordMatcher,
originalRecord?: RouteRecordMatcher
) {
// used later on to remove by name
let isRootAdd = !originalRecord
let mainNormalizedRecord = normalizeRouteRecord(record)
// we might be the child of an alias
mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record
Expand Down Expand Up @@ -134,6 +136,9 @@ export function createRouterMatcher(
// other alias (if any) need to reference this record when adding children
originalRecord = originalRecord || matcher

// remove the route if named and only for the top record (avoid in nested calls)
if (isRootAdd && record.name) removeRoute(record.name)

insertMatcher(matcher)
}

Expand Down
8 changes: 8 additions & 0 deletions src/matcher/pathTokenizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,19 @@ const ROOT_TOKEN: Token = {
}

const VALID_PARAM_RE = /[a-zA-Z0-9_]/
// After some profiling, the cache seems to be unnecessary because tokenizePath
// (the slowest part of adding a route) is very fast

// const tokenCache = new Map<string, Token[][]>()

export function tokenizePath(path: string): Array<Token[]> {
if (!path) return [[]]
if (path === '/') return [[ROOT_TOKEN]]
// remove the leading slash
if (path[0] !== '/') throw new Error('A non-empty path must start with "/"')

// if (tokenCache.has(path)) return tokenCache.get(path)!

function crash(message: string) {
throw new Error(`ERR (${state})/"${buffer}": ${message}`)
}
Expand Down Expand Up @@ -178,5 +184,7 @@ export function tokenizePath(path: string): Array<Token[]> {
consumeBuffer()
finalizeSegment()

// tokenCache.set(path, tokens)

return tokens
}

0 comments on commit 07100fc

Please sign in to comment.