UNPKG

2.33 kBJavaScriptView Raw
1import axios from 'axios';
2import FileDownload from 'js-file-download';
3
4export const isNotForwardSlash = (v) => v && v !== '/';
5
6export const prependForwardSlash = (v) => {
7 let output = String(v);
8 if (output.startsWith('/')) output = output.substr(1);
9
10 if (output.charAt(output.length - 1) === '/')
11 output = output.substring(0, output.length - 1);
12
13 return `/${output}`;
14};
15
16export const getFn = (obj, prop) => {
17 if (!(prop in obj) || typeof obj[prop] !== 'function')
18 throw new Error('Unknown action');
19
20 return obj[prop]();
21};
22
23export const isEmpty = (obj) =>
24 !obj ||
25 (typeof obj === 'object' &&
26 !Object.keys(obj).length &&
27 !(obj instanceof Error));
28
29export const makeUrlPath = (a, b) => {
30 let url = Array.isArray(a)
31 ? a
32 .filter(isNotForwardSlash)
33 .map(prependForwardSlash)
34 .join('')
35 : a;
36
37 if (Array.isArray(b))
38 url += `?ids[]=${b.join('&ids[]=')}`;
39
40 return url;
41};
42
43export const addSearchQuery = (v, term) =>
44 v.includes('?')
45 ? `${v}&search=${term}`
46 : `${v}?search=${term}`;
47
48export const acceptCsvFiletype = (params = {}) => (
49 data,
50 headers,
51) => {
52 Object.assign(headers, params, {
53 'Accept': 'text/csv',
54 });
55 return data;
56};
57
58export const getWithContentTypeCsv = (url, params) =>
59 axios({
60 url,
61 method: 'get',
62 transformRequest: [acceptCsvFiletype(params)],
63 });
64
65export const getAsCSV = (url, params = {}) =>
66 getWithContentTypeCsv(url, params)
67 .then((e) => FileDownload(e.data, 'file.csv'))
68 .catch(() => {
69 // noop
70 });
71
72export const formatUrlPath = (url, query, select) => {
73 let endpoint = url;
74
75 const hasQuery = (v) => v.includes('?');
76 const appendAmpersand = (v) =>
77 v.startsWith('&') ? v : `&${v}`;
78
79 const hasLength = (v) =>
80 typeof v === 'string' && v.length;
81
82 const addToEndpoint = (v) => {
83 if (hasQuery(endpoint)) {
84 endpoint += appendAmpersand(v.replace('?', '&'));
85 } else if (v.startsWith('&')) {
86 endpoint += endpoint.endsWith('&') ? v.substr(1) : v;
87 } else {
88 endpoint += !v.startsWith('?') ? `?${v}` : v;
89 }
90 };
91
92 if (hasLength(query)) addToEndpoint(query);
93 if (hasLength(select)) addToEndpoint(`fields=${select}`);
94
95 return endpoint;
96};