generated from parzh/package-javascript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
http-get.impl.ts
53 lines (45 loc) · 1.23 KB
/
http-get.impl.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
import type { URL } from "url";
import https from "https";
/** @private */
type Chunk = string | Buffer;
/** @private */
function isChunk(value: unknown): value is Chunk {
return typeof value === "string" || Buffer.isBuffer(value);
}
export class MalformedChunkError extends Error {
constructor(
public chunk: unknown,
) {
super("Received a malformed chunk");
}
}
export class UnexpectedResponseStatus extends Error {
constructor(
public statusCode?: number,
public statusMessage?: string,
) {
super(`Expected a 2xx status code, received "${statusCode} ${statusMessage}"`);
}
}
export default function httpGet(url: string | URL, options: https.RequestOptions = {}): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Chunk[] = [];
https.get(url, options, (res) => {
if (!String(res.statusCode).startsWith("2"))
return reject(new UnexpectedResponseStatus(res.statusCode, res.statusMessage));
res
.setEncoding("utf8")
.on("data", (chunk) => {
if (isChunk(chunk)) {
chunks.push(chunk);
} else {
res.destroy(new MalformedChunkError(chunk));
}
})
.once("end", () => {
const result = chunks.map(String).join("");
resolve(result);
});
});
});
}