Skip to content

Commit

Permalink
feat: 🎸 getQueryParams support hash router & array params
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed Mar 5, 2023
1 parent f157f91 commit 91275cf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 15 deletions.
26 changes: 18 additions & 8 deletions packages/core/src/getQueryParams.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { getQueryParams } from './getQueryParams'

describe('getQueryParams', () => {
it('should works', () => {
const { name, surname, id } = getQueryParams<{
name: string
surname: string
it('history router', () => {
const { name, id, foo } = getQueryParams<{
name: string[]
id: string
}>('http://url.com/page?name=Adam&surname=Smith')
expect(name).toBe('Adam')
expect(surname).toBe('Smith')
expect(id).toBe(null)
foo: string
}>('http://url.com/page?name=Adam&name=Smith&id=1&foo')
expect(id).toBe('1')
expect(name).toEqual(['Adam', 'Smith'])
expect(foo).toBe(null)
})
it('hash router', () => {
const { name, id, foo } = getQueryParams<{
name: string[]
id: string
foo: string
}>('http://url.com/page#?name=Adam&name=Smith&id=1&foo#home')
expect(id).toBe('1')
expect(name).toEqual(['Adam', 'Smith'])
expect(foo).toBe(null)
})
})
25 changes: 18 additions & 7 deletions packages/core/src/getQueryParams.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import { parseQuery } from './parseQuery'
import type { LocationQuery } from './parseQuery'
/**
* It takes a URL and returns an object with the query parameters as properties
* @param {string} url - The URL to parse.
* @returns A proxy object that wraps a URLSearchParams object.
* @returns {LocationQuery} a query object
*/
export function getQueryParams<T extends Record<string, string>>(url: string) {
const url_ = new URL(url)
const params = new Proxy(new URLSearchParams(url_.search), {
get: (searchParams, prop) => typeof prop === 'string' ? searchParams.get(prop) : null,
})
export function getQueryParams<T extends LocationQuery>(location: string) {
let query: LocationQuery = {}

return params as unknown as T
const searchPos = location.indexOf('?')
let searchString = location.slice(
searchPos + 1,
location.length,
)

const hashPos = searchString.indexOf('#')
if (hashPos > -1) // maybe http://url.com/page?name=Adam&surname=Smith&id#home
searchString = searchString.slice(0, hashPos)

query = parseQuery(searchString)

return query as Partial<T>
}

0 comments on commit 91275cf

Please sign in to comment.