-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
108 lines (90 loc) · 2.63 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
'use strict';
const
app = require('express')(),
express = require('express'),
http = require('http').Server(app),
io = require('socket.io')(http),
config = requireOrDefault('./config.js', { products: [] });
let
orders = {},
products = config.products,
sockets = {};
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', socket => {
const
clientIp = socket.request.connection.remoteAddress,
socketId = socket.id;
log('CONNECT');
emitProducts();
emitOrders();
socket.on('disconnect', () => {
const userName = sockets[socketId];
log('DISCONNECT', { userName });
if (typeof orders[userName] !== 'undefined' && orders[userName].product === '') {
delete orders[userName];
}
delete sockets[socketId];
emitOrders();
});
socket.on('register', (userName, fn) => {
const result = register(userName, clientIp);
log('REGISTER', { userName, result });
fn(result);
if (result.success) {
sockets[socketId] = userName;
orders[userName] = orders[userName] || { clientIp, product: '' };
emitOrders();
}
});
socket.on('product', productName => {
if (products.indexOf(productName) === -1) {
log('ADD PRODUCT', { userName: sockets[socketId], productName });
products.push(productName);
emitProducts();
}
});
socket.on('order', productName => {
const userName = sockets[socketId];
log('ADD ORDER', { userName, productName });
orders[userName].product = productName;
emitOrders();
});
function log(event, ...objs) {
console.log(new Date() + ' ' + event, { socketId, clientIp }, ...objs);
}
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
function requireOrDefault(module, defaultValue) {
try {
return require(module);
} catch (e) {
if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
return defaultValue;
}
throw e;
}
}
function register(userName, clientIp) {
if (userName.trim() === '') {
return { success: false, errorCode: 'USER_NAME_CANNOT_BE_WHITE_SPACES' };
}
const userNames = Object.keys(orders);
if (userNames.indexOf(userName) !== -1 && orders[userName].clientIp !== clientIp) {
return { success: false, errorCode: 'USER_NAME_EXISTS' };
}
return { success: true };
}
function emitProducts() {
io.emit('products', products);
}
function emitOrders() {
const ordersViewModel = Object.keys(orders).reduce((accumulator, key) => {
return Object.assign({}, accumulator, { [key]: orders[key].product });
}, {});
io.emit('orders', ordersViewModel);
}