This repository has been archived by the owner on Sep 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 186
/
Https.ts
75 lines (71 loc) · 2.48 KB
/
Https.ts
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
import { IncomingMessage } from "http";
import https from "https";
import url from "url";
/**
* Maks an HTTPS GET request to the specified URI and returns the parsed JSON
* body data.
*/
export async function get<T>(uri: string): Promise<T> {
const result = await getResponse<T>(uri);
return result.data;
}
/**
* Make an HTTPS GET request to the specified URI and returns the parsed JSON
* body data as well as the full response.
*/
export async function getResponse<T>(uri: string): Promise<{ data: T; response: IncomingMessage }> {
return new Promise((resolve, reject) => {
const req = https.get(url.parse(uri), res => {
const results: Buffer[] = [];
res.on("error", reject);
res.on("data", (data: Buffer) => results.push(data));
res.on("end", () => {
const finalResults = Buffer.concat(results).toString();
if (res.statusCode !== 200) {
return reject(new Error(results.toString()));
} else {
const resultsParsed = JSON.parse(finalResults) as T;
return resolve({
data: resultsParsed,
response: res,
});
}
});
});
req.on("error", reject);
req.end();
});
}
export async function post<T>(uri: string, postData: string = ""): Promise<T> {
return new Promise((resolve, reject) => {
const { hostname, port, pathname } = url.parse(uri);
const req = https.request(
{
host: hostname,
port,
path: pathname,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": postData.length,
},
},
res => {
const results: Buffer[] = [];
res.on("error", reject);
res.on("data", data => results.push(data));
res.on("end", () => {
const finalResults = Buffer.concat(results).toString();
if (res.statusCode !== 200) {
return reject(results.toString());
} else {
return resolve(JSON.parse(finalResults));
}
});
},
);
req.on("error", reject);
req.write(postData);
req.end();
});
}