-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
75 lines (59 loc) · 1.94 KB
/
server.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
require('dotenv').config();
const path = require('path');
const http = require('http');
const exec = require('child_process').exec;
const APP_NAME = process.env.APP_NAME;
const SERVER_PORT = process.env.SERVER_PORT;
// # HOOKS
const createWebhookHandler = require('github-webhook-handler');
// Initialize webhook handler
const WebhookHandler = createWebhookHandler({ path: process.env.GITHUB_HOOK_PATH, secret: process.env.GITHUB_HOOK_SECRET });
// # MESSAGES
// Get initialized singleton class of MessageService
const MessageService = require('./services/MessageService');
// MessageService is a singleton so set its attributes
MessageService.setAttributes({appName: APP_NAME, port: SERVER_PORT});
// # DEPLOY
const DeployService = require('./services/DeployService');
// # ROUTES
const routes = require('./routes');
// # SERVER
http
.createServer((req, res) => {
return WebhookHandler(
req,
res,
(err) => routes(err, req, res) // Handle routes that are not equal to GITHUB_HOOK_PATH
);
})
.listen(SERVER_PORT, () => {
// Server start message
return MessageService.writeMessage(
undefined,
MessageService.server.start,
{
appName: APP_NAME,
port: SERVER_PORT
}
);
});
WebhookHandler.on('error', (error) => {
// Handle Errors
return MessageService.writeMessage(
undefined,
MessageService.server.error,
{
appName: APP_NAME,
error
}
);
})
WebhookHandler.on('push', (event) => {
const repoName = event.payload.repository.name;
const branchName = event.payload.ref.replace("refs/heads/", "");
// Deploy if the pushed branch is the tracked branch for this server
if (branchName === process.env.GIT_BRANCH) {
const deployer = new DeployService(repoName, branchName);
return deployer.deploy();
}
});