forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
https.ts
62 lines (56 loc) · 1.31 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
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { IncomingHttpHeaders } from "http";
import { request, RequestOptions } from "https";
import { Writable, pipeline } from "stream";
export async function fetch(
uri: string,
data?: Buffer,
options?: RequestOptions
) {
return new Promise<{
status?: number;
headers: IncomingHttpHeaders;
data: Buffer;
}>((resolve, reject) => {
const req = request(uri, options ?? {}, (res) =>
pipeline(
[
res,
collectBuffer((data) =>
resolve({ status: res.statusCode, headers: res.headers, data })
),
],
done
)
);
function done(error?: Error | null) {
if (!error) return;
req.destroy(error);
reject(error);
}
req.on("error", done);
req.end(data);
});
}
const collectBuffer = (callback: (collectedBuffer: Buffer) => void) => {
const chunks = [] as Buffer[];
return new Writable({
write: (chunk, _encoding, done) => {
try {
chunks.push(chunk);
done();
} catch (err) {
done(err);
}
},
final: (done) => {
try {
callback(Buffer.concat(chunks));
done();
} catch (err) {
done(err);
}
},
});
};