-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
86 lines (69 loc) · 2.39 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
76
77
78
79
80
81
82
83
84
85
86
/**
* Created by mario (https://github.com/hyprstack) on 20/01/2018.
*/
const io = require('socket.io');
const app = require('./app');
const configs = require('./lib/config/configs');
const customEmitter = require('./lib/custom-emitter/internal-emitter');
const validator = require('./lib/validator/check-signature');
require('./lib/coinapi-socket/coinbase-socket');
const _port = configs.get('PORT');
const server = app.listen(_port, () => {
const port = server.address().port;
console.log('App listening on port %s', port);
});
const socketConfig = configs.get('SOCKET');
const socket = io.listen(server, socketConfig);
socket.use((socket, next) => {
const { handshake } = socket;
if (validator.verifySignature(handshake)) {
return next();
}
return next(new Error('Invalid signature'));
});
const createRoomName = (data) => {
if (Array.isArray(data)) {
const roomNameList = data.map((coins) => {
const { fromCoin, toCoin } = coins;
return `${fromCoin}_${toCoin}-`;
});
return ''.concat(...roomNameList)
}
const { fromCoin, toCoin } = data;
return `${fromCoin}_${toCoin}-`;
};
const extractPartialRoomNameFromData = (data) => {
const { symbol_id, type } = JSON.parse(data.utf8Data)
if (type === 'heartbeat') return;
return symbol_id.split('SPOT_').pop();
}
const checkCoinPairInRoomName = (coinPair, roomName) => {
const coinPairList = roomName.split('-');
return coinPairList.indexOf(coinPair) > -1;
}
socket.on('connection', (client) => {
console.log('Client connected...');
customEmitter.emit('connectExchanges')
client.on('getExchangeRates', function(data) {
const room = createRoomName(data.subs);
client.join(room, () => {
console.log(`A new client ${client.id} has joined the room ${room}`)
});
customEmitter.on('coinApiExchanges', (msg) => {
const partialMatch = extractPartialRoomNameFromData(msg)
if (checkCoinPairInRoomName(partialMatch, room)) {
socket.sockets.in(room).emit('coinExchange', msg.utf8Data);
}
});
client.on('disconnect', () => {
console.log(`Client disconnected and left room ${room}`);
})
client.on('cancelExchangeRates', () => {
client.leave(room, () => {
console.log(`Client ${client.id} left room ${room}`);
client.emit('leftRoom', `Room ${room} left!`);
})
});
});
});
module.exports = server;