-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsocket.js
67 lines (58 loc) · 2.43 KB
/
socket.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
/* eslint-disable no-console */
import jwt from 'jsonwebtoken';
import { addToQueue, updateOrderStatus, getOrderStatus } from './models/queues.model';
// key: bar, value: { key: orderNum, value: socket }
const orderBarSockets = {};
const ioConfig = (io) => {
// when anyone connects
io.on('connect', (user) => {
const { bar } = user.handshake.query;
// if no namespace for this bar yet
if (!orderBarSockets[bar]) {
orderBarSockets[bar] = {};
const barId = bar.slice(1);
io.of(bar).on('connect', async (socket) => {
const { orderNumber, token } = socket.handshake.query;
// get orderNumber and/or token from socket connection
if (orderNumber) {
orderBarSockets[bar][orderNumber] = socket;
const orderStatus = await getOrderStatus(barId, orderNumber);
if (orderStatus) socket.emit('STATUS_UPDATE', orderStatus);
}
// if it's a staff member (token exists), join staff room
if (token) {
try {
const { barId: decBarId } = jwt.verify(token, process.env.JWT_SK);
if (decBarId === barId) socket.join('staff');
} catch (err) {
console.log(err);
socket.disconnect(true);
}
}
// when staff updates status of an order
socket.on('STATUS_UPDATE', (orderId, newStatus) => {
// if order exists, update the queue cache and emit to customer and staff
if (orderBarSockets[bar][orderId]) {
updateOrderStatus(barId, orderId, newStatus);
orderBarSockets[bar][orderId].emit('STATUS_UPDATE', newStatus);
io.of(bar).to('staff').emit('STATUS_UPDATE', orderId, newStatus);
} else {
console.error('Order does not exist');
}
});
// needs to be replaced with emitting on API call, not on connect
socket.on('NEW_ORDER', async (newOrder) => {
// update the cached queue on the server
const isNewOrder = await addToQueue(barId, newOrder);
// need to check if orderNumber already exists, if yes do not create new order
const orderStatus = await getOrderStatus(barId, orderNumber);
// emit new order to all bar staff
if (orderStatus) socket.emit('STATUS_UPDATE', orderStatus);
if (isNewOrder) io.of(bar).to('staff').emit('NEW_ORDER', newOrder);
});
});
}
});
return io;
};
export default ioConfig;