-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
91 lines (86 loc) · 1.84 KB
/
index.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
import express from "express";
import cors from "cors";
import { json, urlencoded } from "body-parser";
export type hookType = {
path: string;
type?: "GET" | "POST";
action: <T = any, J = any, K = any, I = any>(
data?: T,
params?: K,
query?: I
) => J | Promise<J>;
};
export type hooksType = hookType[];
const webhook = (
hooks: hooksType,
PORT: number = 3010,
debug: boolean = false
) => {
const log = (...arg: any) => {
if (debug) {
console.log("WEBHOOK 👉", ...arg);
}
};
const app = express();
app.use(cors());
app.use(json());
app.use(urlencoded({ extended: true }));
hooks.forEach((hook) => {
const action = (
req: express.Request,
res: express.Response
) => {
log(
"EVENT",
hook.path,
hook.type ? hook.type : "GET"
);
Promise.all([
hook.action(
req.body,
req.params,
req.query
),
])
.then(([response]) => {
res.setHeader(
"X-Powered-By",
"VOS Webhook"
);
res.send(response);
})
.catch((err) => {
console.error(err);
res.setHeader(
"X-Powered-By",
"VOS Webhook"
);
res.send({
status: false,
msg: "hook failed",
});
});
};
switch (hook.type) {
case undefined:
case "GET":
app.get(hook.path, action);
break;
default:
app.post(hook.path, action);
break;
}
});
app.use((req, res) => {
log("NOT FOUND", req.path);
res.setHeader("X-Powered-By", "VOS Webhook");
res.status(404).send({
status: false,
msg: "hook not found",
});
});
app.listen(PORT, () => {
log("Server started at", PORT);
});
};
export default webhook;