-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (67 loc) · 2.63 KB
/
Copy pathserver.js
File metadata and controls
76 lines (67 loc) · 2.63 KB
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
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
const clients = {};
const boards = {};
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
let msg;
try {
msg = JSON.parse(message);
} catch (e) {
console.error('Invalid JSON', e);
return;
}
if (msg.type === 'join') {
const { token, boardId } = msg;
// TODO: Kolla att usern har access till boardId
ws.boardId = boardId;
if (!clients[boardId]) {
clients[boardId] = new Set();
}
clients[boardId].add(ws);
// Skicka hela nuvarande board staten till klienten
const boardState = boards[boardId] || [];
ws.send(JSON.stringify({ type: 'init', tickets: boardState }));
} else if (['createTicket', 'updateTicket', 'deleteTicket', 'moveTicket'].includes(msg.type)) {
const boardId = ws.boardId;
if (!boardId) {
console.error('No boardId associated with this connection');
return;
}
// Uppdatera board state när den ändras på en klient
let boardState = boards[boardId] || [];
switch (msg.type) {
case 'createTicket':
boardState.push(msg.ticket);
break;
case 'updateTicket':
const updateIndex = boardState.findIndex(t => t.id === msg.ticket.id);
if (updateIndex !== -1) boardState[updateIndex] = msg.ticket;
break;
case 'deleteTicket':
boards[boardId] = boardState.filter(t => t.id !== msg.ticketId);
break;
case 'moveTicket':
const moveIndex = boardState.findIndex(t => t.id === msg.ticket.id);
if (moveIndex !== -1) boardState[moveIndex].position = msg.ticket.position;
break;
}
boards[boardId] = boardState;
// Skicka uppdatering till alla klienter
clients[boardId].forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg));
}
});
}
});
ws.on('close', () => {
const boardId = ws.boardId;
if (boardId && clients[boardId]) {
clients[boardId].delete(ws);
if (clients[boardId].size === 0) {
delete clients[boardId];
}
}
});
});