UNPKG

1.64 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 =
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 * Build a URL from the base url and given params
49 *
50 * @param {string} url
51 * @param {Object} params
52 * @return {string}
53 */
54function buildUrl(url, params) {
55 return `${url}${buildParamString(params)}`;
56}
57
58/**
59 * @param {string} params
60 * @return {Object}
61 */
62const 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
78module.exports = expose({
79 getSegments,
80 getSegment,
81 buildParamString,
82 buildUrl,
83 objectifyParams,
84});