-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
47 lines (37 loc) · 1.13 KB
/
server.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
import { createServer, IncomingMessage, ServerResponse } from "http";
function parseBody(req: IncomingMessage) {
return new Promise<any>((resolve, reject) => {
(req as IncomingMessage & { rawBody: string }).rawBody = "";
req.setEncoding("utf8");
req.on("data", (chunk: string) => {
(req as IncomingMessage & { rawBody: string }).rawBody += chunk;
});
req.on("end", () => {
resolve((req as IncomingMessage & { rawBody: string }).rawBody);
});
});
}
// add rawBody to IncomingMessage
type Request = IncomingMessage & { rawBody: string };
interface RPCRequest<T extends any[] = any[]> {
method: string;
request: T;
}
interface RPCResponse<T> {
response: T;
}
const server = createServer(
async (req: IncomingMessage, res: ServerResponse) => {
try {
await parseBody(req);
console.log((req as Request).rawBody);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello World\n");
} catch (error) {
console.error(error);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error\n");
}
}
);
server.listen(3000);