-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (54 loc) · 1.77 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
const http = require("http");
const WebSocketServer = require("websocket").server;
const validate = require("./validator/validate").validate;
const logger = require("./logger/logger");
const errors = require("./validator/errors");
const PORT = require("./configs/config").server.port;
const server = http.createServer();
server.listen(PORT);
const wsServer = new WebSocketServer({
httpServer: server,
});
wsServer.on("request", (request) => {
const connection = request.accept(null, request.origin);
connection.on("message", (message) => {
let payload;
const answer = {
action: {
method: "",
response: {
status: "",
description: "",
},
},
};
try {
payload = JSON.parse(message.utf8Data);
const validationError = validate(payload);
if (validationError) {
answer.action.response.status = "ERROR";
answer.action.response.description = validationError;
} else {
answer.action.response.status = "OK";
answer.action.response.description = "SUCCESS";
answer.action.response.batch_id = payload.action.parameters.batch_id;
}
if (payload.action && payload.action.method) {
answer.action.method = payload.action.method;
}
} catch (error) {
answer.action.response.status = "ERROR";
answer.action.response.description = errors.VALIDATION_ERROR;
}
logger.log("info", "request and response log", {
payload,
answer,
});
connection.sendUTF(JSON.stringify(answer), (sendError) => {
sendError ? console.log("answer send with errors: ", sendError) : null;
});
});
connection.on("close", (reasonCode, description) => {
console.log("Client has disconnected.", reasonCode, desciption);
});
});