-
Notifications
You must be signed in to change notification settings - Fork 101
/
frameworks.node.ts
60 lines (55 loc) · 2.06 KB
/
frameworks.node.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
// deno-lint-ignore-file no-explicit-any
import {
adapters as sharedAdapters,
SECRET_HEADER,
} from "./frameworks.shared.ts";
import { type IncomingMessage, type ServerResponse } from "http";
/** Node.js native 'http' and 'https' modules */
const http = (req: IncomingMessage, res: ServerResponse) => {
const secretHeaderFromRequest = req.headers[SECRET_HEADER.toLowerCase()];
return {
update: new Promise<any>((resolve, reject) => {
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(chunk))
.once("end", () => {
const raw = Buffer.concat(chunks).toString("utf-8");
resolve(JSON.parse(raw));
})
.once("error", reject);
}),
header: Array.isArray(secretHeaderFromRequest)
? secretHeaderFromRequest[0]
: secretHeaderFromRequest,
end: () => res.end(),
respond: (json: string) =>
res
.writeHead(200, { "Content-Type": "application/json" })
.end(json),
unauthorized: () => res.writeHead(401).end("secret token is wrong"),
};
};
/** worktop CloudFlare workers framework */
const worktop = (req: any, res: any) => ({
update: Promise.resolve(req.body.json()),
header: req.headers.get(SECRET_HEADER),
end: () => res.end(),
respond: (json: string) => res.send(200, json),
unauthorized: () => res.send(401, "secret token is wrong"),
});
/** AWS lambda serverless functions */
const awsLambda = (event: any, _context: any, callback: any) => ({
update: JSON.parse(event.body),
header: event.headers[SECRET_HEADER],
end: () => callback(null, { statusCode: 200 }),
respond: (json: string) => callback(null, { statusCode: 200, body: json }),
unauthorized: () => callback(null, { statusCode: 401 }),
});
// please open a PR if you want to add another
export const adapters = {
http,
https: http,
worktop,
"aws-lambda": awsLambda,
...sharedAdapters,
};
export const defaultAdapter = "express";