1 | const { get } = require('./object');
|
2 | const expose = require('./expose');
|
3 | const { keys } = Object;
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | function getSegments(path) {
|
12 | const [pathComponent] = path.split('?');
|
13 | const [, ...segments] = pathComponent.split('/');
|
14 |
|
15 | return segments;
|
16 | }
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | function getSegment(path) {
|
25 | const [, segment] = getSegments(path);
|
26 |
|
27 | return segment;
|
28 | }
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | function buildParamString(params) {
|
37 | const paramsAsString = keys(params)
|
38 | .filter(param => params[param])
|
39 | .map(param => `${param}=${encodeURIComponent(get(params, param))}`)
|
40 | .join('&');
|
41 | const preParam = paramsAsString.length ? '?' : '';
|
42 |
|
43 | return `${preParam}${paramsAsString}`;
|
44 | }
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | function buildUrl(url, params) {
|
54 | return `${url}${buildParamString(params)}`;
|
55 | }
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | const objectifyParams = params => {
|
62 | if (!params) {
|
63 | return {};
|
64 | }
|
65 |
|
66 | return params.split('&').reduce((acc, param) => {
|
67 | const [name, value] = param.split('=');
|
68 |
|
69 | acc[name] = decodeURIComponent(value);
|
70 |
|
71 | return acc;
|
72 | }, {});
|
73 | };
|
74 |
|
75 | module.exports = expose({
|
76 | getSegments,
|
77 | getSegment,
|
78 | buildParamString,
|
79 | buildUrl,
|
80 | objectifyParams,
|
81 | });
|