Skip to content

Commit

Permalink
feat: getParams
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Dec 12, 2020
1 parent 309f38a commit 5ad02f6
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -52,14 +52,21 @@ 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])
}
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)
Expand Down
14 changes: 13 additions & 1 deletion test/params.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-nocheck
import { withParams } from '../src'
import { getParams, withParams } from '../src'

describe('withParams', () => {
const tests = [
Expand All @@ -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])
})
}
})

0 comments on commit 5ad02f6

Please sign in to comment.