diff --git a/README.md b/README.md index f7c58ed3..132daa1f 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,13 @@ joinURL('a', '/b', '/c') joinURL('http://foo.com/foo?test=123#token', 'bar', 'baz') ``` +### `withparams` + +```ts +// Result: /foo?page=a&token=secret +withParams('/foo?page=a', { token: 'secret' }) +``` + ### `withTrailingSlash` Ensures url ends with a trailing slash diff --git a/src/index.ts b/src/index.ts index b75094cb..80133cc9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,8 @@ export interface ParsedURL { export type InputURL = string | ParsedURL +export type URLParams = { [key: string]: any } + export function withoutTrailingSlash (input: string = ''): string { return input.endsWith('/') ? input.slice(0, -1) : input } @@ -50,6 +52,14 @@ export function normalizeURL (input: InputURL, stripBase?: boolean): string { return isRelative ? path.substr(1) : path } +export function withParams (input: InputURL, params: URLParams): string { + const parsed = parseURL(input) + for (const name in params) { + parsed.url.searchParams.set(name, params[name]) + } + return normalizeURL(parsed) +} + 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 new file mode 100644 index 00000000..969c1644 --- /dev/null +++ b/test/params.test.ts @@ -0,0 +1,19 @@ +// @ts-nocheck +import { withParams } from '../src' + +describe('withParams', () => { + const tests = [ + { input: '', params: {}, out: '' }, + { input: '/', params: {}, out: '/' }, + { input: '?test', params: {}, out: '?test' }, + { input: '/?test', params: {}, out: '/?test' }, + { input: '/?test', params: { foo: 1 }, out: '/?test=&foo=1' }, + { input: '/?foo=1', params: { foo: 2 }, out: '/?foo=2' } + ] + + for (const t of tests) { + test(t.input.toString() + ' with ' + JSON.stringify(t.params), () => { + expect(withParams(t.input, t.params)).toBe(t.out) + }) + } +})