]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
feat(router): add beforeResolve
authorEduardo San Martin Morote <posva13@gmail.com>
Wed, 22 Apr 2020 13:11:50 +0000 (15:11 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Wed, 22 Apr 2020 13:11:50 +0000 (15:11 +0200)
__tests__/guards/beforeResolve.spec.ts [new file with mode: 0644]
src/router.ts

diff --git a/__tests__/guards/beforeResolve.spec.ts b/__tests__/guards/beforeResolve.spec.ts
new file mode 100644 (file)
index 0000000..a0dbeae
--- /dev/null
@@ -0,0 +1,25 @@
+import { createDom, noGuard, newRouter as createRouter } from '../utils'
+import { RouteRecordRaw } from '../../src/types'
+
+const Home = { template: `<div>Home</div>` }
+const Foo = { template: `<div>Foo</div>` }
+
+const routes: RouteRecordRaw[] = [
+  { path: '/', component: Home },
+  { path: '/foo', component: Foo },
+]
+
+describe('router.beforeEach', () => {
+  beforeAll(() => {
+    createDom()
+  })
+
+  it('calls beforeEach guards on navigation', async () => {
+    const spy = jest.fn()
+    const router = createRouter({ routes })
+    router.beforeResolve(spy)
+    spy.mockImplementationOnce(noGuard)
+    await router.push('/foo')
+    expect(spy).toHaveBeenCalledTimes(1)
+  })
+})
index 0bce78a4b6a025c17976c7888d0fa944f06a7cb1..cb10805b75da2cce2ba12eaf362b8afb745081c7 100644 (file)
@@ -147,6 +147,7 @@ export interface Router {
   go(distance: number): void
 
   beforeEach(guard: NavigationGuardWithThis<undefined>): () => void
+  beforeResolve(guard: NavigationGuardWithThis<undefined>): () => void
   afterEach(guard: PostNavigationGuard): () => void
 
   onError(handler: ErrorHandler): () => void
@@ -170,6 +171,7 @@ export function createRouter({
   const matcher = createRouterMatcher(routes, {})
 
   const beforeGuards = useCallbacks<NavigationGuardWithThis<undefined>>()
+  const beforeResolveGuards = useCallbacks<NavigationGuardWithThis<undefined>>()
   const afterGuards = useCallbacks<PostNavigationGuard>()
   const currentRoute = ref<RouteLocationNormalizedLoaded>(
     START_LOCATION_NORMALIZED
@@ -452,6 +454,14 @@ export function createRouter({
 
     // run the queue of per route beforeEnter guards
     await runGuardQueue(guards)
+
+    // check global guards beforeEach
+    guards = []
+    for (const guard of beforeResolveGuards.list()) {
+      guards.push(guardToPromiseFn(guard, to, from))
+    }
+
+    await runGuardQueue(guards)
   }
 
   function triggerAfterEach(
@@ -660,6 +670,7 @@ export function createRouter({
     forward: () => history.go(1),
 
     beforeEach: beforeGuards.add,
+    beforeResolve: beforeResolveGuards.add,
     afterEach: afterGuards.add,
 
     onError: errorHandlers.add,