From 5dce7bcbfbb4a80bd1edbe061a250fa646f2afd7 Mon Sep 17 00:00:00 2001 From: Austin Akers Date: Tue, 17 Mar 2020 03:36:28 -0500 Subject: [PATCH] feat(router): support custom parseQuery and stringifyQuery (#136) --- __tests__/router.spec.ts | 22 +++++++++++++++++++--- src/router.ts | 10 +++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/__tests__/router.spec.ts b/__tests__/router.spec.ts index 7f4a6f9a..15952582 100644 --- a/__tests__/router.spec.ts +++ b/__tests__/router.spec.ts @@ -7,7 +7,6 @@ import { RouteLocation, START_LOCATION_NORMALIZED, } from '../src/types' -import { RouterHistory } from '../src/history/common' const routes: RouteRecord[] = [ { path: '/', component: components.Home, name: 'home' }, @@ -56,9 +55,12 @@ const routes: RouteRecord[] = [ }, ] -async function newRouter({ history }: { history?: RouterHistory } = {}) { +async function newRouter({ + history, + ...args +}: Partial[0]> = {}) { history = history || createMemoryHistory() - const router = createRouter({ history, routes }) + const router = createRouter({ history, routes, ...args }) await router.push('/') return { history, router } @@ -90,6 +92,20 @@ describe('Router', () => { ) }) + it('can allows the end user to override parseQuery', async () => { + const parseQuery = jest.fn() + const { router } = await newRouter({ parseQuery: parseQuery }) + router.resolve('/foo?bar=baz') + expect(parseQuery).toHaveBeenCalled() + }) + + it('can allows the end user to stringify the query', async () => { + const stringifyQuery = jest.fn() + const { router } = await newRouter({ stringifyQuery: stringifyQuery }) + router.resolve({ query: { foo: 'bar' } }) + expect(stringifyQuery).toHaveBeenCalled() + }) + it('can do initial navigation to /', async () => { const router = createRouter({ history: createMemoryHistory(), diff --git a/src/router.ts b/src/router.ts index df5b42d7..4c2f8791 100644 --- a/src/router.ts +++ b/src/router.ts @@ -33,7 +33,11 @@ import { } from './utils' import { useCallbacks } from './utils/callbacks' import { encodeParam, decode } from './utils/encoding' -import { normalizeQuery, parseQuery, stringifyQuery } from './utils/query' +import { + normalizeQuery, + parseQuery as originalParseQuery, + stringifyQuery as originalStringifyQuery, +} from './utils/query' import { ref, Ref, markNonReactive, nextTick, App, warn } from 'vue' import { RouteRecordNormalized } from './matcher/types' import { Link } from './components/Link' @@ -55,6 +59,8 @@ export interface RouterOptions { history: RouterHistory routes: RouteRecord[] scrollBehavior?: ScrollBehavior + parseQuery?: typeof originalParseQuery + stringifyQuery?: typeof originalStringifyQuery // TODO: allow customizing encoding functions } @@ -87,6 +93,8 @@ export function createRouter({ history, routes, scrollBehavior, + parseQuery = originalParseQuery, + stringifyQuery = originalStringifyQuery, }: RouterOptions): Router { const matcher = createRouterMatcher(routes, {}) -- 2.39.5