diff --git a/README.md b/README.md index 132daa1f..829b4325 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,13 @@ joinURL('http://foo.com/foo?test=123#token', 'bar', 'baz') withParams('/foo?page=a', { token: 'secret' }) ``` +### `getParams` + +```ts +// Result: { test: '123', unicode: '好' } +getParams('http://foo.com/foo?test=123&unicode=%E5%A5%BD') +``` + ### `withTrailingSlash` Ensures url ends with a trailing slash diff --git a/src/index.ts b/src/index.ts index 80133cc9..e06b73f9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,7 @@ export interface ParsedURL { export type InputURL = string | ParsedURL -export type URLParams = { [key: string]: any } +export type SearchParams = { [key: string]: any } export function withoutTrailingSlash (input: string = ''): string { return input.endsWith('/') ? input.slice(0, -1) : input @@ -52,7 +52,7 @@ export function normalizeURL (input: InputURL, stripBase?: boolean): string { return isRelative ? path.substr(1) : path } -export function withParams (input: InputURL, params: URLParams): string { +export function withParams (input: InputURL, params: SearchParams): string { const parsed = parseURL(input) for (const name in params) { parsed.url.searchParams.set(name, params[name]) @@ -60,6 +60,13 @@ export function withParams (input: InputURL, params: URLParams): string { return normalizeURL(parsed) } +export function getParams (input: InputURL): SearchParams { + const parsed = parseURL(input) + const params: SearchParams = {} + parsed.url.searchParams.forEach((value, key) => { params[value] = key }) + return params +} + export function joinURL (input0: string, ...input: string[]): string { const path = input.map(parseURL) const baseURL = parseURL(input0) diff --git a/test/params.test.ts b/test/params.test.ts index 969c1644..72a90860 100644 --- a/test/params.test.ts +++ b/test/params.test.ts @@ -1,5 +1,5 @@ // @ts-nocheck -import { withParams } from '../src' +import { getParams, withParams } from '../src' describe('withParams', () => { const tests = [ @@ -17,3 +17,15 @@ describe('withParams', () => { }) } }) + +describe('getParams', () => { + const tests = { + 'http://foo.com/foo?test=123&unicode=%E5%A5%BD': { 123: 'test', 好: 'unicode' } + } + + for (const t in tests) { + test(t, () => { + expect(getParams(t)).toMatchObject(tests[t]) + }) + } +})