UNPKG

1.63 kBJavaScriptView Raw
1const { get } = require('./object');
2const expose = require('./expose');
3const { keys } = Object;
4
5/**
6 * Get the path segments from an absolute path with an optional query.
7 *
8 * @param {string} path
9 * @return {Array}
10 */
11function getSegments(path) {
12 const [pathComponent] = path.split('?');
13 const [, ...segments] = pathComponent.split('/');
14
15 return segments;
16}
17
18/**
19 * Get the second path segment from an absolute path with an optional query.
20 *
21 * @param {string} path
22 * @return {string}
23 */
24function getSegment(path) {
25 const [, segment] = getSegments(path);
26
27 return segment;
28}
29
30/**
31 * Build a paramString from an the keyValues of an object
32 *
33 * @param {Object} params
34 * @return {string}
35 */
36function 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 * Build a URL from the base url and given params
48 *
49 * @param {string} url
50 * @param {Object} params
51 * @return {string}
52 */
53function buildUrl(url, params) {
54 return `${url}${buildParamString(params)}`;
55}
56
57/**
58 * @param {string} params
59 * @return {Object}
60 */
61const 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
75module.exports = expose({
76 getSegments,
77 getSegment,
78 buildParamString,
79 buildUrl,
80 objectifyParams,
81});