Skip to content

Commit

Permalink
feat: pass state in guards and redirect
Browse files Browse the repository at this point in the history
Close #1472
  • Loading branch information
posva committed Aug 16, 2022
1 parent a73edd1 commit add447b
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
48 changes: 48 additions & 0 deletions packages/router/__tests__/guards/beforeEach.spec.ts
Expand Up @@ -19,6 +19,10 @@ const routes: RouteRecordRaw[] = [
{ path: 'home', name: 'nested-home', component: Home },
],
},
{
path: '/redirect',
redirect: { path: '/other', state: { fromRecord: true } },
},
]

describe('router.beforeEach', () => {
Expand Down Expand Up @@ -106,6 +110,50 @@ describe('router.beforeEach', () => {
expect(router.currentRoute.value.fullPath).toBe('/other')
})

it('can add state when redirecting', async () => {
const router = createRouter({ routes })
await router.push('/foo')
router.beforeEach((to, from) => {
// only allow going to /other
if (to.fullPath !== '/other') {
return {
path: '/other',
state: { added: 'state' },
}
}
return
})

const spy = jest.spyOn(history, 'pushState')
await router.push({ path: '/', state: { a: 'a' } })
expect(spy).toHaveBeenCalledTimes(1)
// called before redirect
expect(spy).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ added: 'state', a: 'a' }),
'',
expect.stringMatching(/\/other$/)
)
spy.mockClear()
})

it('can add state to a redirect route', async () => {
const router = createRouter({ routes })
await router.push('/foo')

const spy = jest.spyOn(history, 'pushState')
await router.push({ path: '/redirect', state: { a: 'a' } })
expect(spy).toHaveBeenCalledTimes(1)
// called before redirect
expect(spy).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ fromRecord: true, a: 'a' }),
'',
expect.stringMatching(/\/other$/)
)
spy.mockClear()
})

async function assertRedirect(redirectFn: (i: string) => RouteLocationRaw) {
const spy = jest.fn()
const router = createRouter({ routes })
Expand Down
10 changes: 8 additions & 2 deletions packages/router/src/router.ts
Expand Up @@ -655,7 +655,10 @@ export function createRouter(options: RouterOptions): Router {
if (shouldRedirect)
return pushWithRedirect(
assign(locationAsObject(shouldRedirect), {
state: data,
state:
typeof shouldRedirect === 'object'
? assign({}, data, shouldRedirect.state)
: data,
force,
replace,
}),
Expand Down Expand Up @@ -735,7 +738,10 @@ export function createRouter(options: RouterOptions): Router {
},
locationAsObject(failure.to),
{
state: data,
state:
typeof failure.to === 'object'
? assign({}, data, failure.to.state)
: data,
force,
}
),
Expand Down

0 comments on commit add447b

Please sign in to comment.