Skip to content

Commit

Permalink
feat: withParams
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Dec 12, 2020
1 parent 5c4c005 commit 309f38a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions test/params.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
}
})

0 comments on commit 309f38a

Please sign in to comment.