Skip to content

Commit

Permalink
feat: add a clearRoutes method
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jun 19, 2024
1 parent f7f78f0 commit abe223d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
15 changes: 15 additions & 0 deletions packages/router/__tests__/matcher/addingRemoving.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@ describe('Matcher: adding and removing records', () => {
})
})

it('can remove all records', () => {
const matcher = createRouterMatcher([], {})
matcher.addRoute({ path: '/', component })
matcher.addRoute({ path: '/about', component, name: 'about' })
matcher.addRoute({
path: '/with-children',
component,
children: [{ path: 'child', component }],
})
expect(matcher.getRoutes()).not.toHaveLength(0)
matcher.clearRoutes()
expect(matcher.getRoutes()).toHaveLength(0)
expect(matcher.getRecordMatcher('about')).toBeFalsy()
})

it('throws when adding *', () => {
const matcher = createRouterMatcher([], {})
expect(() => {
Expand Down
17 changes: 14 additions & 3 deletions packages/router/src/matcher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@ import type { RouteRecordNameGeneric, _RouteRecordProps } from '../typed-routes'
*/
export interface RouterMatcher {
addRoute: (record: RouteRecordRaw, parent?: RouteRecordMatcher) => () => void

removeRoute(matcher: RouteRecordMatcher): void
removeRoute(name: NonNullable<RouteRecordNameGeneric>): void

clearRoutes: () => void
getRoutes: () => RouteRecordMatcher[]
getRecordMatcher: (
name: NonNullable<RouteRecordNameGeneric>
Expand Down Expand Up @@ -345,7 +344,19 @@ export function createRouterMatcher(
// add initial routes
routes.forEach(route => addRoute(route))

return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher }
function clearRoutes() {
matchers.length = 0
matcherMap.clear()
}

return {
addRoute,
resolve,
removeRoute,
clearRoutes,
getRoutes,
getRecordMatcher,
}
}

function paramsFromLocation(
Expand Down
6 changes: 6 additions & 0 deletions packages/router/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,11 @@ export interface Router {
*/
getRoutes(): RouteRecord[]

/**
* Delete all routes from the router matcher.
*/
clearRoutes(): void

/**
* Returns the {@link RouteLocation | normalized version} of a
* {@link RouteLocationRaw | route location}. Also includes an `href` property
Expand Down Expand Up @@ -1228,6 +1233,7 @@ export function createRouter(options: RouterOptions): Router {

addRoute,
removeRoute,
clearRoutes: matcher.clearRoutes,
hasRoute,
getRoutes,
resolve,
Expand Down

0 comments on commit abe223d

Please sign in to comment.