-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
96 lines (86 loc) · 2.38 KB
/
index.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
88
89
90
91
92
93
94
95
96
const http = require('http');
const { parse } = require('querystring');
const {
predictAction,
predictInteraction,
logAction,
} = require('./vacabot/helpers');
const {
actionCheckVacationBalance,
actionDenyVacationRequest,
actionOpenCreateVacation,
actionSubmitVacationRequest,
actionUpdateManager,
} = require('./vacabot/actions');
const C = require('./vacabot/consts');
const User = require('./vacabot/models/user');
function serverHandler(req, res) {
let body = [];
req
.on('error', console.error)
.on('data', (data) => body.push(data))
.on('end', () => {
try {
body = parse(Buffer.concat(body).toString());
mainHandler(body);
} catch (err) {
console.error(err);
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end();
});
}
http.createServer(serverHandler).listen(process.env.PORT || 80);
function mainHandler(body) {
if (body.command) {
handleCommand(body);
} else {
handleInteractions(JSON.parse(body.payload));
}
}
async function handleCommand(body) {
let user = await User.createIfNotExists({
userId: body.user_id,
userName: body.user_name,
teamId: body.team_id,
});
console.log('\vNew request from:', user.userName);
const responseUrl = body.response_url;
const triggerId = body.trigger_id;
const query = body.text;
const action = predictAction(query);
logAction(action);
switch (action) {
case C.SET_MANAGER:
actionUpdateManager(responseUrl, user);
break;
case C.OPEN_DIALOG_CREATE_VACATION:
actionOpenCreateVacation(triggerId, user);
break;
case C.CHECK_VACATION:
actionCheckVacationBalance(responseUrl, query);
break;
default:
console.log("Command couldn't be processed:", query);
}
}
async function handleInteractions(payload) {
const user = await User.createIfNotExists({
userId: payload.user.id,
userName: payload.user.username,
teamId: payload.user.team_id,
});
console.log('\vNew request from:', user.userName);
const interaction = predictInteraction(payload);
logAction(interaction);
switch (interaction) {
case C.SUBMIT_VACATION_DIALOG:
actionSubmitVacationRequest(user, payload);
break;
case C.DENY_VACATION_REQUEST:
actionDenyVacationRequest(payload);
break;
default:
console.log("Interaction couldn't be processed:", payload);
}
}