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 =
|
38 | keys(params)
|
39 | .filter(param => params[param])
|
40 | .map(param => `${param}=${encodeURIComponent(get(params, param))}`)
|
41 | .join('&');
|
42 | const preParam = paramsAsString.length ? '?' : '';
|
43 |
|
44 | return `${preParam}${paramsAsString}`;
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | function buildUrl(url, params) {
|
55 | return `${url}${buildParamString(params)}`;
|
56 | }
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | const objectifyParams = params => {
|
63 | if(!params) {
|
64 | return {};
|
65 | }
|
66 |
|
67 | return params
|
68 | .split('&')
|
69 | .reduce((acc, param) => {
|
70 | const [name, value] = param.split('=');
|
71 |
|
72 | acc[name] = value;
|
73 |
|
74 | return acc;
|
75 | }, {});
|
76 | };
|
77 |
|
78 | module.exports = expose({
|
79 | getSegments,
|
80 | getSegment,
|
81 | buildParamString,
|
82 | buildUrl,
|
83 | objectifyParams,
|
84 | });
|