Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useQueryValue composition to make working with query values that are not params just as easy #314

Merged
merged 5 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions src/compositions/useQueryValue.browser.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
import { createRouter } from '@/services'
import { createRoute } from '@/services/createRoute'
import { expect, test } from 'vitest'
import { useQueryValue } from './useQueryValue'
import { flushPromises, mount } from '@vue/test-utils'

test('returns correct value and values when key does not exist', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/',
})

await router.start()

const component = {
setup() {
return useQueryValue('foo')
},
}

const wrapper = mount(component, {
global: {
plugins: [router],
},
})

expect(wrapper.vm.value).toBe(null)
expect(wrapper.vm.values).toEqual([])
})

test('returns correct value and values when key does exist', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/?foo=1&foo=2',
})

await router.start()

const component = {
setup() {
return useQueryValue('foo')
},
}

const wrapper = mount(component, {
global: {
plugins: [router],
},
})

expect(wrapper.vm.value).toBe('1')
expect(wrapper.vm.values).toEqual(['1', '2'])
})

test('returns correct value and values when a param is used', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/?foo=1&foo=2',
})

await router.start()

const component = {
setup() {
return useQueryValue('foo', Number)
},
}

const wrapper = mount(component, {
global: {
plugins: [router],
},
})

expect(wrapper.vm.value).toBe(1)
expect(wrapper.vm.values).toEqual([1, 2])
})

test('updates value and values when the query string changes', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/?foo=1&foo=2',
})

await router.start()

const component = {
setup() {
return useQueryValue('foo', Number)
},
}

const wrapper = mount(component, {
global: {
plugins: [router],
},
})

expect(wrapper.vm.value).toBe(1)
expect(wrapper.vm.values).toEqual([1, 2])

await router.push('/?foo=3')

expect(wrapper.vm.value).toBe(3)
expect(wrapper.vm.values).toEqual([3])
})

test('updates the query string when the value is set', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/?foo=1&foo=2',
})

await router.start()

const component = {
setup() {
const { value } = useQueryValue('foo', Number)

value.value = 3
},
}

mount(component, {
global: {
plugins: [router],
},
})

await flushPromises()

expect(router.route.query.toString()).toBe('foo=3')
})

test('updates the query string when the values is set', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/?foo=1&foo=2',
})

await router.start()

const component = {
setup() {
const { values } = useQueryValue('foo', Number)

values.value = [3, 4]
},
}

mount(component, {
global: {
plugins: [router],
},
})

await flushPromises()

expect(router.route.query.toString()).toBe('foo=3&foo=4')
})

test('removes the query string when the remove method is called', async () => {
const root = createRoute({
name: 'root',
path: '/',
})

const router = createRouter([root], {
initialUrl: '/?foo=1&foo=2',
})

await router.start()

const component = {
setup() {
const { remove } = useQueryValue('foo')

remove()
},
}

mount(component, {
global: {
plugins: [router],
},
})

await flushPromises()

expect(router.route.query.toString()).toBe('')
})
71 changes: 71 additions & 0 deletions src/compositions/useQueryValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { computed, Ref, MaybeRefOrGetter, toValue } from 'vue'
import { useRoute } from './useRoute'
import { Param } from '@/types'
import { ExtractParamType } from '@/types/params'
import { safeGetParamValue, setParamValue } from '@/services/params'

export type UseQueryValue<T> = {
value: Ref<T | null>,
values: Ref<T[]>,
remove: () => void,
}

export function useQueryValue(key: MaybeRefOrGetter<string>): UseQueryValue<string>

export function useQueryValue<
TParam extends Param
>(
key: MaybeRefOrGetter<string>,
param: TParam
): UseQueryValue<ExtractParamType<TParam>>

export function useQueryValue(
key: MaybeRefOrGetter<string>,
param: Param = String,
): UseQueryValue<unknown> {
const route = useRoute()

const value = computed({
get() {
const value = route.query.get(toValue(key))

if (value === null) {
return null
}

return safeGetParamValue(value, param)
},
set(value) {
route.query.set(toValue(key), setParamValue(value, param))
},
})

const values = computed({
get() {
const values = route.query.getAll(toValue(key))

return values
.map((value) => safeGetParamValue(value, param))
.filter((value) => value !== null)
},
set(values) {
const query = new URLSearchParams(route.query.toString())

query.delete(toValue(key))

values.forEach((value) => {
query.append(toValue(key), setParamValue(value, param))
})

route.query = query
},
})

return {
value,
values,
remove: () => {
route.query.delete(toValue(key))
},
}
}
11 changes: 11 additions & 0 deletions src/services/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,17 @@ export function getParamValue<T extends Param>(value: string | undefined, param:
return value
}

export function safeGetParamValue<T extends Param>(value: string | undefined, param: T, isOptional = false): ExtractParamType<T> | undefined {
try {
return getParamValue(value, param, isOptional)
} catch (error) {
if (error instanceof InvalidRouteParamValueError) {
return undefined
}
throw error
}
}

export function setParamValue(value: unknown, param: Param, isOptional = false): string {
if (value === undefined) {
if (isOptional) {
Expand Down
Loading