-
Notifications
You must be signed in to change notification settings - Fork 6
/
api.js
353 lines (309 loc) · 13.1 KB
/
api.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import { Observable } from "./observable";
import { verify, urlEncode, globals } from "../util";
import fetch from "node-fetch";
const AUTH_ERRORS = [401, 403, 440, 499];
export class API extends Observable {
constructor(kwargs = {}) {
super();
this.kwargs = kwargs;
}
async build(method, url, options = {}) {}
async authCallback(params, headers) {}
async get(url, options = {}) {
const result = await this.methodBasic("GET", url, options);
return result;
}
async post(url, options = {}) {
const result = await this.methodPayload("POST", url, options);
return result;
}
async put(url, options = {}) {
const result = await this.methodPayload("PUT", url, options);
return result;
}
async delete(url, options = {}) {
const result = await this.methodBasic("DELETE", url, options);
return result;
}
async patch(url, options = {}) {
const result = await this.methodPayload("PATCH", url, options);
return result;
}
async options(url, options = {}) {
const result = await this.methodBasic("OPTIONS", url, options);
return result;
}
async methodBasic(method, url, options = {}) {
options.params = options.params !== undefined ? options.params : {};
options.headers = options.headers !== undefined ? options.headers : {};
try {
return await this._methodBasic(method, url, options);
} catch (err) {
if (AUTH_ERRORS.includes(err.code)) {
await this.authCallback(options.params, options.headers);
return await this._methodBasic(method, url, options);
} else {
throw err;
}
}
}
async methodPayload(method, url, options = {}) {
options.params = options.params !== undefined ? options.params : {};
options.headers = options.headers !== undefined ? options.headers : {};
try {
return await this._methodPayload(method, url, options);
} catch (err) {
if (AUTH_ERRORS.includes(err.code)) {
await this.authCallback(options.params, options.headers);
return await this._methodPayload(method, url, options);
} else {
throw err;
}
}
}
async _methodBasic(method, url, options = {}) {
const params = options.params !== undefined ? options.params : {};
let headers = options.headers !== undefined ? options.headers : {};
const kwargs = options.kwargs !== undefined ? options.kwargs : {};
const handle = options.handle !== undefined ? options.handle : true;
const getAgent = options.getAgent !== undefined ? options.getAgent : undefined;
await this.build(method, url, {
params: params,
headers: headers,
kwargs: kwargs
});
const query = urlEncode(params || {});
if (query) url += url.includes("?") ? "&" + query : "?" + query;
// runs a dummy agent retrieval to check if the current agent
// is set to keep connections alive
const _getAgent = getAgent || globals.getAgent || undefined;
const agent = _getAgent ? _getAgent(new URL(url)) : undefined;
const keepAlive = (agent && agent.keepAlive) || false;
headers = Object.assign({}, headers);
if (keepAlive) headers.Connection = "keep-alive";
// adds a new forced loop, tick to the event loop, this should
// help solve closed connection handling problems in node-fetch
// while not adding extra issues
await new Promise(resolve => setTimeout(resolve, 0));
const response = await fetchRetry(url, {
method: method,
headers: headers || {},
agent: getAgent || globals.getAgent || undefined
});
const result = handle ? await this._handleResponse(response) : response;
return result;
}
async _methodPayload(method, url, options = {}) {
const params = options.params !== undefined ? options.params : {};
let headers = options.headers !== undefined ? options.headers : {};
let data = options.data !== undefined ? options.data : null;
const dataJ = options.dataJ !== undefined ? options.dataJ : null;
const dataM = options.dataM !== undefined ? options.dataM : null;
let mime = options.mime !== undefined ? options.mime : null;
const kwargs = options.kwargs !== undefined ? options.kwargs : {};
const handle = options.handle !== undefined ? options.handle : true;
const getAgent = options.getAgent !== undefined ? options.getAgent : undefined;
await this.build(method, url, {
params: params,
headers: headers,
data: data,
dataJ: dataJ,
dataM: dataM,
mime: mime,
kwargs: kwargs
});
const query = urlEncode(params || {});
if (data !== null) {
if (query) url += url.includes("?") ? "&" + query : "?" + query;
} else if (dataJ !== null) {
data = JSON.stringify(dataJ);
if (query) url += url.includes("?") ? "&" + query : "?" + query;
mime = mime || "application/json";
} else if (dataM !== null) {
if (query) url += url.includes("?") ? "&" + query : "?" + query;
[mime, data] = this._encodeMultipart(dataM, mime, true);
} else if (query) {
data = query;
mime = mime || "application/x-www-form-urlencoded";
}
// runs a dummy agent retrieval to check if the current agent
// is set to keep connections alive
const _getAgent = getAgent || globals.getAgent || undefined;
const agent = _getAgent ? _getAgent(new URL(url)) : undefined;
const keepAlive = (agent && agent.keepAlive) || false;
headers = Object.assign({}, headers);
if (mime) headers["Content-Type"] = mime;
if (keepAlive) headers.Connection = "keep-alive";
// adds a new forced loop, tick to the event loop, this should
// help solve closed connection handling problems in node-fetch
// while not adding extra issues
await new Promise(resolve => setTimeout(resolve, 0));
const response = await fetchRetry(url, {
method: method,
headers: headers || {},
body: data,
agent: getAgent || global.getAgent || undefined
});
const result = handle ? await this._handleResponse(response) : response;
return result;
}
async _handleResponse(response, errorMessage = "Problem in request") {
let result = null;
if (
response.headers.get("content-type") &&
response.headers.get("content-type").toLowerCase().startsWith("application/json")
) {
result = await response.json();
} else if (
response.headers.get("content-type") &&
response.headers.get("content-type").toLowerCase().startsWith("text/")
) {
result = await response.text();
} else {
result = await response.blob();
}
verify(
response.ok,
(result.error && result.error.message) ||
(result.exception && result.exception.message) ||
result.error ||
result.exception ||
errorMessage,
response.status || 500,
undefined,
{
response: response,
result: result
}
);
return result;
}
_encodeMultipart(fields, mime = null, doseq = false) {
mime = mime || "multipart/form-data";
const boundary = this._createBoundary(fields, undefined, doseq);
const encoder = new TextEncoder("utf-8");
const buffer = [];
for (let [key, values] of Object.entries(fields)) {
const isList = doseq && Array.isArray(values);
values = isList ? values : [values];
for (let value of values) {
if (value === null) continue;
let header;
if (
typeof value === "object" &&
!(value instanceof Array) &&
value.constructor !== Uint8Array
) {
const headerL = [];
let data = null;
for (const [key, item] of Object.entries(value)) {
if (key === "data") data = item;
else headerL.push(`${key}: ${item}`);
}
value = data;
header = headerL.join("\r\n");
} else if (value instanceof Array) {
let name = null;
let contents = null;
let contentTypeD = null;
if (value.length === 2) [name, contents] = value;
else [name, contentTypeD, contents] = value;
header = `Content-Disposition: form-data; name="${key}"; filename="${name}"`;
if (contentTypeD) header += `\r\nContent-Type: ${contentTypeD}`;
value = contents;
} else {
header = `Content-Disposition: form-data; name="${key}"`;
value = value.constructor === Uint8Array ? value : encoder.encode(value);
}
buffer.push(encoder.encode("--" + boundary + "\r\n"));
buffer.push(encoder.encode(header + "\r\n"));
buffer.push(encoder.encode("\r\n"));
buffer.push(value);
buffer.push(encoder.encode("\r\n"));
}
}
buffer.push(encoder.encode("--" + boundary + "--\r\n"));
buffer.push(encoder.encode("\r\n"));
const body = this._joinBuffer(buffer);
const contentType = `${mime}; boundary=${boundary}`;
return [contentType, body];
}
_createBoundary(fields, size = 32, doseq = false) {
return "Vq2xNWWHbmWYF644q9bC5T2ALtj5CynryArNQRXGYsfm37vwFKMNsqPBrpPeprFs";
}
_joinBuffer(bufferArray) {
const bufferSize = bufferArray.map(item => item.byteLength).reduce((a, v) => a + v, 0);
const buffer = new Uint8Array(bufferSize);
let offset = 0;
for (const item of bufferArray) {
buffer.set(item, offset);
offset += item.byteLength;
}
return buffer;
}
}
export const fetchRetry = async (url, options = {}, retries = 5, delay = 0, timeout = 100) => {
let response = null;
while (!response && retries > 0) {
const start = Date.now();
try {
response = await fetch(url, options);
} catch (error) {
const isHangup =
error.name === "FetchError" &&
error.code === "ECONNRESET" &&
error.message.includes("socket hang up");
const elapsed = Date.now() - start;
if (retries === 0 || elapsed > timeout || !isHangup) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, delay));
retries--;
}
}
return response;
};
export const buildGetAgent = (AgentHttp, AgentHttps, set = true, options = {}) => {
const httpAgent = new AgentHttp({
keepAlive: options.keepAlive === undefined ? true : options.keepAlive,
keepAliveMsecs: options.keepAliveMsecs || 120000,
timeout: options.timeout || 60000,
scheduling: options.scheduling || "fifo"
});
const httpsAgent = new AgentHttps({
keepAlive: options.keepAlive === undefined ? true : options.keepAlive,
keepAliveMsecs: options.keepAliveMsecs || 120000,
timeout: options.timeout || 60000,
scheduling: options.scheduling || "fifo"
});
const getAgent = parsedURL => (parsedURL.protocol === "http:" ? httpAgent : httpsAgent);
if (set) globals.getAgent = getAgent;
return getAgent;
};
/**
* Tries to patch the global environment with a proper `getAgent`
* function that can handle HTTP and HTTP connection polling.
*
* This can only be performed in a node.js environment (uses `require`).
*
* @returns {Function} The `getAgent` function that has just been
* built and set in the globals.
*/
export const patchAgent = () => {
if (typeof require !== "function") return;
if (globals.getAgent) return;
let http, https;
try {
http = require("http");
https = require("https");
} catch (err) {
return;
}
if (!http || !https) return;
if (!http.Agent || !https.Agent) return;
return buildGetAgent(http.Agent, https.Agent, true);
};
// patches the global agent if possible, using the
// global dynamic require statements
patchAgent();
export default API;