Skip to content

Commit ab78174

Browse files
committed
feat: add parameters as part of the url for fetch
1 parent 233286b commit ab78174

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

src/create-client.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* globals fetch */
22
import 'isomorphic-fetch'
33
import { API_BASE_URL } from './constants'
4+
import { buildUrlWithParams } from './utils';
45

56
export const clientConstructor = ({ token, ...options }) => {
67
return {
@@ -9,9 +10,12 @@ export const clientConstructor = ({ token, ...options }) => {
910
url,
1011
data,
1112
headers: argsHeaders = {},
13+
params,
1214
...otherArgs
1315
} = args
1416

17+
const requestUrl = buildUrlWithParams(`${API_BASE_URL}${url}`, params)
18+
1519
const {
1620
headers = {}
1721
} = options
@@ -21,7 +25,7 @@ export const clientConstructor = ({ token, ...options }) => {
2125
...otherArgs
2226
}
2327

24-
return fetch(`${API_BASE_URL}${url}`, {
28+
return fetch(requestUrl, {
2529
...requestParameters,
2630
body: JSON.stringify(data),
2731
headers: {

src/utils.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,21 @@ export const createMemberPatchQuery = ({ members, operation }) => {
1919
}
2020
}))
2121
}
22+
23+
export const buildUrlWithParams = (url, params = {}) => {
24+
const queryParams = Object.keys(params)
25+
.reduce((list, key) => {
26+
const currentValue = params[key]
27+
if (currentValue) {
28+
return [
29+
...list,
30+
`${encodeURIComponent(key)}=${encodeURIComponent(currentValue)}`
31+
]
32+
} else {
33+
return list
34+
}
35+
}, [])
36+
.join('&')
37+
38+
return queryParams ? `${url}?${queryParams}` : url
39+
}

tests/unit/utils.test.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { buildUrlWithParams } from '../../src/utils'
2+
3+
test('the url reminds the same if no parameter passed', () => {
4+
const url = 'http://typeform.com'
5+
expect(buildUrlWithParams(url)).toBe(url)
6+
})
7+
8+
test('the url has a query string if parameters are passed', () => {
9+
const url = 'http://typeform.com'
10+
const params = {
11+
a: '1',
12+
b: '2'
13+
}
14+
expect(buildUrlWithParams(url, params)).toBe('http://typeform.com?a=1&b=2')
15+
})
16+
17+
test('parameters should be enconded', () => {
18+
const url = 'http://typeform.com'
19+
const params = {
20+
a: '@1',
21+
b: '#2'
22+
}
23+
expect(buildUrlWithParams(url, params)).toBe('http://typeform.com?a=%401&b=%232')
24+
})
25+
26+
test.only('undefined values for parameter will be skipped', () => {
27+
const url = 'http://typeform.com'
28+
const params = {
29+
a: '@1',
30+
b: undefined
31+
}
32+
expect(buildUrlWithParams(url, params)).toBe('http://typeform.com?a=%401')
33+
})

0 commit comments

Comments
 (0)