-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.js
87 lines (70 loc) · 2.24 KB
/
handler.js
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
"use strict";
const {
stringToJSON,
createResponse,
createErrorResponse,
} = require("./src/utils/parser");
const telegram = require("./src/telegraf");
const { haveCredentials } = require("./src/utils/telegraf");
const { logger } = require("./src/utils/logger");
const { trackMessage } = require("./src/utils/mixpanel");
const { connect: mongoConnect } = require("./src/persistence/mongodb");
const { connect: redisConnect } = require("./src/persistence/redis");
const setWebhook = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
try {
const {
headers: { Host },
requestContext: { stage },
} = event;
const url = `https://${Host}/${stage}/webhook`;
await telegram.setWebhook(url);
return callback(null, createResponse({ success: true, url }));
} catch (error) {
const { message } = error;
return callback(null, createErrorResponse(message));
}
};
const webhook = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
const startTime = new Date();
try {
const { body: bodyString } = event;
const body = stringToJSON(bodyString);
logger(body);
haveCredentials(body);
await redisConnect();
await mongoConnect();
await telegram.handleUpdate(body);
trackMessage(body);
const endTime = new Date();
console.log("[SUCCESS] time_execution: ", endTime - startTime);
return callback(null, createResponse());
} catch (error) {
const { message } = error;
const endTime = new Date();
console.error(message);
console.error(error);
console.error("[FAIL] time_execution: ", endTime - startTime);
return callback(null, createErrorResponse(message));
}
};
const publicWebhook = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
try {
const { body: bodyString, headers } = event;
const body = stringToJSON(bodyString);
logger(body);
await redisConnect();
await telegram.externalWebhook({ ...body, ...headers });
return callback(null, createResponse());
} catch (error) {
const { message } = error;
return callback(null, createErrorResponse(message));
}
};
module.exports = {
setWebhook,
webhook,
publicWebhook,
};