1 | import axios from 'axios';
|
2 | import FileDownload from 'js-file-download';
|
3 |
|
4 | const isNotForwardSlash = (v) => v && v !== '/';
|
5 |
|
6 | 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 |
|
16 | export 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 |
|
23 | export const isEmpty = (obj) =>
|
24 | !obj ||
|
25 | (typeof obj === 'object' &&
|
26 | !Object.keys(obj).length &&
|
27 | !(obj instanceof Error));
|
28 |
|
29 | export const makePath = (a = []) =>
|
30 | a
|
31 | .filter(isNotForwardSlash)
|
32 | .map(prependForwardSlash)
|
33 | .join('');
|
34 |
|
35 | export const makeQueryPath = (url, ids) =>
|
36 | `${url}?ids[]=${ids.join('&ids[]=')}`;
|
37 |
|
38 | export const addSearchQuery = (v, term) =>
|
39 | v.includes('?')
|
40 | ? `${v}&search=${term}`
|
41 | : `${v}?search=${term}`;
|
42 |
|
43 | export const acceptCsvFiletype = (params = {}) => (
|
44 | data,
|
45 | headers,
|
46 | ) => {
|
47 | Object.assign(headers, params, {
|
48 | 'Accept': 'text/csv',
|
49 | });
|
50 | return data;
|
51 | };
|
52 |
|
53 | export const getWithContentTypeCsv = (url, params) =>
|
54 | axios({
|
55 | url,
|
56 | method: 'get',
|
57 | transformRequest: [acceptCsvFiletype(params)],
|
58 | });
|
59 |
|
60 | export const getAsCSV = (url, params = {}) =>
|
61 | getWithContentTypeCsv(url, params)
|
62 | .then((e) => FileDownload(e.data, 'file.csv'))
|
63 | .catch(() => {
|
64 |
|
65 | });
|
66 |
|
67 | export const formatUrlPath = (url, query, select) => {
|
68 | let endpoint = url;
|
69 |
|
70 | const hasQuery = (v) => v.includes('?');
|
71 | const appendAmpersand = (v) =>
|
72 | v.startsWith('&') ? v : `&${v}`;
|
73 |
|
74 | const hasLength = (v) =>
|
75 | typeof v === 'string' && v.length;
|
76 |
|
77 | const addToEndpoint = (v) => {
|
78 | if (hasQuery(endpoint)) {
|
79 | endpoint += appendAmpersand(v.replace('?', '&'));
|
80 | } else if (v.startsWith('&')) {
|
81 | endpoint += endpoint.endsWith('&') ? v.substr(1) : v;
|
82 | } else {
|
83 | endpoint += !v.startsWith('?') ? `?${v}` : v;
|
84 | }
|
85 | };
|
86 |
|
87 | if (hasLength(query)) addToEndpoint(query);
|
88 | if (hasLength(select)) addToEndpoint(`fields=${select}`);
|
89 |
|
90 | return endpoint;
|
91 | };
|