-
Notifications
You must be signed in to change notification settings - Fork 99
/
frameworks.shared.ts
101 lines (94 loc) · 2.8 KB
/
frameworks.shared.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
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
// deno-lint-ignore-file no-explicit-any
import { adapters as webAdapters } from "./frameworks.web.ts";
export const SECRET_HEADER = "X-Telegram-Bot-Api-Secret-Token";
/** express web framework */
const express = (req: any, res: any) => ({
update: Promise.resolve(req.body),
header: req.header(SECRET_HEADER),
end: () => res.end(),
respond: (json: string) => {
res.set("Content-Type", "application/json");
res.send(json);
},
unauthorized: () => {
res.send(401, "secret token is wrong");
},
});
/** koa web framework */
const koa = (ctx: any) => ({
update: Promise.resolve(ctx.request.body),
header: ctx.get(SECRET_HEADER),
end: () => {
ctx.body = "";
},
respond: (json: string) => {
ctx.set("Content-Type", "application/json");
ctx.response.body = json;
},
unauthorized: () => {
ctx.status = 401;
},
});
/** fastify web framework */
const fastify = (req: any, reply: any) => ({
update: Promise.resolve(req.body),
header: req.headers[SECRET_HEADER.toLowerCase()],
end: () => reply.status(200).send(),
respond: (json: string) => reply.send(json),
unauthorized: () => reply.code(401).send("secret token is wrong"),
});
/** std/http web server */
const stdHttp = (req: Request) => {
let resolveResponse: (res: Response) => void;
return {
update: req.json(),
header: req.headers.get(SECRET_HEADER) || undefined,
end: () => {
if (resolveResponse) {
resolveResponse(new Response(null, { status: 200 }));
}
},
respond: (json: string) => {
if (resolveResponse) {
const res = new Response(json, {
status: 200,
headers: { "Content-Type": "application/json" },
});
resolveResponse(res);
}
},
unauthorized: () => {
if (resolveResponse) {
const res = new Response('"unauthorized"', {
status: 401,
statusText: "secret token is wrong",
});
resolveResponse(res);
}
},
handlerReturn: new Promise((resolve) => {
resolveResponse = resolve;
}),
};
};
/** oak web framework */
const oak = (ctx: any) => ({
update: ctx.request.body({ type: "json" }).value,
header: ctx.request.headers.get(SECRET_HEADER) || undefined,
end: () => (ctx.response.status = 200),
respond: (json: string) => {
ctx.response.type = "json";
ctx.response.body = json;
},
unauthorized: () => {
ctx.response.status = 401;
},
});
export const adapters = {
express,
koa,
fastify,
"std/http": stdHttp,
oak,
hono: webAdapters.hono,
};