-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.js
More file actions
113 lines (94 loc) · 2.63 KB
/
bridge.js
File metadata and controls
113 lines (94 loc) · 2.63 KB
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
const http = require("http");
function normalizeEvent(event) {
let isApiGateway = true;
if (event.Action === "Invoke") {
isApiGateway = false;
const invokeEvent = JSON.parse(event.body);
const { method, path, headers, encoding } = invokeEvent;
let { body } = invokeEvent;
if (body) {
if (encoding === "base64") {
body = Buffer.from(body, encoding);
} else if (encoding === undefined) {
body = Buffer.from(body);
} else {
throw new Error(`Unsupported encoding: ${encoding}`);
}
}
return {
isApiGateway,
method,
path,
headers,
body
};
}
const { httpMethod: method, path, headers, body } = event;
return {
isApiGateway,
method,
path,
headers,
body
};
}
class Bridge {
constructor() {
this.launcher = this.launcher.bind(this);
}
launcher(event) {
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
if (this.userError) {
console.error("Error while initializing entrypoint:", this.userError);
return resolve({ statusCode: 500, body: "" });
}
if (!this.port) {
return resolve({ statusCode: 504, body: "" });
}
const { isApiGateway, method, path, headers, body } = normalizeEvent(
event
);
const opts = {
hostname: "127.0.0.1",
port: this.port,
path,
method,
headers
};
const req = http.request(opts, res => {
const response = res;
const respBodyChunks = [];
response.on("data", chunk => respBodyChunks.push(Buffer.from(chunk)));
response.on("error", reject);
response.on("end", () => {
const bodyBuffer = Buffer.concat(respBodyChunks);
delete response.headers.connection;
if (isApiGateway) {
delete response.headers["content-length"];
} else if (response.headers["content-length"]) {
response.headers["content-length"] = bodyBuffer.length;
}
resolve({
statusCode: response.statusCode,
headers: response.headers,
body: bodyBuffer.toString("base64"),
isBase64Encoded: true
});
});
});
req.on("error", error => {
setTimeout(() => {
// this lets express print the true error of why the connection was closed.
// it is probably 'Cannot set headers after they are sent to the client'
reject(error);
}, 2);
});
if (body) req.write(body);
req.end();
});
}
}
module.exports = {
Bridge
};