This repository has been archived by the owner on Sep 8, 2022. It is now read-only.
/
utils.js
95 lines (84 loc) · 2.48 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* @flow */
import { format as formatUrl } from "url";
import fumble from "fumble";
import debugFactory from "debug";
const debug = debugFactory("app:server:services");
export function read(axios: any, name: string, pathname: string, query: any) {
const formattedUrl = formatUrl({ pathname, query });
debug(`[${name}]: GET ${formattedUrl}`);
return axios.get(formattedUrl).then(
response => {
const responseBody = response.data;
if (!responseBody || !responseBody.results) {
return rejectWith(fumble.create(), {
name,
formattedUrl,
reason: "no result"
});
}
const { results } = responseBody;
if (results.error) {
const { code, message } = results.error;
return rejectWith(fumble.create(code, message), { name, formattedUrl });
}
return results;
},
error => rejectWith(fumble.create(), { name, formattedUrl, reason: error.message })
);
}
export function readAll(
axios: any,
name: string,
pathname: string,
params: any,
itemsName: string,
loaded: any = []
) {
const actualParams = { ...params, start: loaded.length + 1 };
return read(axios, name, pathname, actualParams).then(results => {
const available = +results.results_available; // eslint-disable-line camelcase
if (!available) {
return results;
}
const items = results[itemsName];
if (loaded.length + items.length === available) {
results.results_returned = available; // eslint-disable-line camelcase
results[itemsName] = [...loaded, ...items];
return results;
}
return readAll(axios, name, pathname, params, itemsName, [...loaded, ...items]);
});
}
export function create(
axios: any,
name: string,
pathname: string,
body: any,
query: any,
headers: any
) {
const formattedUrl = formatUrl({ pathname, query });
debug(`[${name}]: POST ${formattedUrl} with body: ${JSON.stringify(body)}`);
return axios.post(formattedUrl, body, { headers }).then(
response => response.data,
error => {
if (error.response) {
return rejectWith(fumble.http.create(error.response.status), {
name,
formattedUrl,
reason: error.response.data
});
}
return rejectWith(fumble.http.create(500), {
name,
formattedUrl,
reason: error.message
});
}
);
}
export function rejectWith(error: any, output: any = {}) {
error.output = output;
debug(error);
return Promise.reject(error);
}