-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.js
55 lines (42 loc) · 1.25 KB
/
http.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
import config from "./config.js";
import https from "node:https";
import http from "node:http";
import axios from "axios";
const agents = {};
export async function requestOpFwApi(url, token) {
const agent = getInstance(url);
const response = await axios.get(url, {
httpAgent: agent,
timeout: config.timeout || 3000,
headers: {
"Authorization": `Bearer ${token}`
}
});
if (response.status !== 200) {
throw Error("http status code not 200");
}
const json = response.data;
if (!json || typeof json !== "object" || !("data" in json) || !("statusCode" in json)) {
throw Error("invalid json returned");
}
if (json.statusCode !== 200) {
throw Error("json status code not 200");
}
return json.data;
}
function getInstance(uri) {
const url = new URL(uri),
origin = url.origin;
if (!(origin in agents)) {
const agent = url.scheme === "https" ? new https.Agent({
keepAlive: true,
rejectUnauthorized: false,
keepAliveMsecs: 5000,
}) : new http.Agent({
keepAlive: true,
keepAliveMsecs: 5000,
});
agents[origin] = agent;
}
return agents[origin];
}