-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
174 lines (167 loc) · 5.33 KB
/
app.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
const environment = require('./environment').getEnvironment();
// Databases
const redis = require('redis');
const mongoClient = require('mongodb').MongoClient;
const http = require('http');
const Ws = require('ws');
const {v4} = require('uuid');
const Sentry = require('@sentry/node');
const {Dependencies} = require('./dependencyHandler');
const {findCommand, registerCommands} = require('./command');
const {Responses, ErrorCodeHelper} = require('./helper');
const ech = new ErrorCodeHelper();
exports.App = class App {
/**
* Initial setup for server
*/
constructor() {
this.server = http.createServer();
this.websocketServer = new Ws.Server({
port: environment.PORT,
server: this.server,
});
if (environment.TYPE === 'prod' ) {
console.log('[*] Server started');
Sentry.init({dsn: environment.SENTRY_DSN});
}
}
/**
* Establishes a connection to the mongo database
*/
async connectMongo() {
const url = `mongodb://${environment.MONGO_HOST}`
+ `:${environment.MONGO_PORT}/${environment.MONGO_DATABASE}`;
await mongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
}, (err) => {
if (err !== null) {
return console.error(
'[!] Mongo connection could not be established.');
}
console.log('[*] Mongo connection established.');
});
}
/**
* Establishes a connection to the redis database
* @return {Promise}
*/
connectRedis() {
return new Promise((resolve, reject) => {
const client = redis.createClient({
host: environment.REDIS_HOST,
port: environment.REDIS_PORT,
});
client.on('connect', () => {
console.log('[*] Redis connection established.');
resolve(true);
});
client.on('error', () => {
reject(
new Error('[!] Redis connection could not be established!'),
);
});
this.redisClient = client;
});
}
/**
* Defines actions that run after the websockt receives a message
*/
defineWebSocketHandler() {
this.websocketServer.on('connection', (ws) => {
ws.uuid = v4();
ws.on('message', (message) => {
this.parseRequest(message, ws).then((response) => {
ws.send(response);
});
});
});
}
/**
* Starts the server
* @return {Promise}
*/
start() {
return new Promise(async (resolve) => {
this.connectRedis().then(async () => {
await this.connectMongo();
registerCommands(this);
Dependencies['redis'] = this.redisClient;
this.defineWebSocketHandler();
resolve();
});
});
}
/**
* @param {string} commandObject
* @param {any} requiredArgs
* @return {any}
*/
parseCommandObject(commandObject) {
const command = findCommand(commandObject.command);
if (command === undefined) {
return undefined;
}
const requiredArgs = command.requiredArgs;
const params = commandObject.params === undefined ?
{} : commandObject.params;
let valid = true;
requiredArgs.forEach((arg) => {
if (Object.keys(params).find((c) => c === arg) === undefined) {
valid = false;
}
});
return valid ? command : undefined;
}
/**
* @param {any} requestObject
* @param {any} responseObject
* @return {any} preparedResponse
*/
prepareResponse(requestObject, responseObject) {
const preparedResponse = JSON.parse(responseObject);
const queueId = requestObject.queueId;
if (queueId !== undefined) {
preparedResponse.queueId = queueId;
}
return JSON.stringify(preparedResponse);
}
/**
* @param {string} message
* @param {Websocket} ws
* @return {any}
*/
parseRequest(message, ws) {
return new Promise(async (resolve) => {
let requestObject = undefined;
try {
requestObject = JSON.parse(message);
} catch (Error) {
return resolve(ech.sendResponse(Responses.INVALID_JSON));
}
const command = this.parseCommandObject(requestObject);
if (command === undefined) {
return resolve(ech.sendResponse(Responses.COMMAND_NOT_FOUND));
}
if (command.async === undefined || !command.async) {
const response = command.run(requestObject.params, ws);
return resolve(this.prepareResponse(requestObject, response));
}
const response = await command.run(requestObject.params, ws);
return resolve(this.prepareResponse(requestObject, response));
});
}
/**
* Stops the server
*/
stop() {
console.log('[*] Stopping server');
this.websocketServer.close();
};
/**
* Port the server is running on.
*/
get Port() {
return environment.PORT;
};
};