241 lines
6 KiB
TypeScript
241 lines
6 KiB
TypeScript
/**
|
|
* WebSocket server for real-time shopping list synchronization
|
|
* Handles live updates when items are checked, added, or removed
|
|
*/
|
|
|
|
import { WebSocketServer, WebSocket } from 'ws';
|
|
import type { IncomingMessage } from 'http';
|
|
import type { Server } from 'http';
|
|
|
|
// Track connected clients by household
|
|
interface ClientConnection {
|
|
ws: WebSocket;
|
|
userId: string;
|
|
householdId: string;
|
|
listId?: string;
|
|
}
|
|
|
|
const connectedClients = new Map<string, ClientConnection[]>(); // householdId -> clients
|
|
|
|
/**
|
|
* Initialize WebSocket server
|
|
* Call this from your Next.js server initialization
|
|
*/
|
|
export function initializeWebSocketServer(httpServer: Server) {
|
|
const wss = new WebSocketServer({ noServer: true });
|
|
|
|
// Handle upgrade from HTTP to WebSocket
|
|
httpServer.on('upgrade', (request: IncomingMessage, socket, head) => {
|
|
if (request.url?.startsWith('/api/ws')) {
|
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
handleNewConnection(ws, request);
|
|
});
|
|
} else {
|
|
socket.destroy();
|
|
}
|
|
});
|
|
|
|
wss.on('close', () => {
|
|
console.log('WebSocket server closed');
|
|
});
|
|
|
|
return wss;
|
|
}
|
|
|
|
/**
|
|
* Handle new WebSocket connection
|
|
*/
|
|
function handleNewConnection(ws: WebSocket, request: IncomingMessage) {
|
|
// Extract auth from URL params or headers
|
|
const url = new URL(request.url || '', `http://${request.headers.host}`);
|
|
const userId = url.searchParams.get('userId');
|
|
const householdId = url.searchParams.get('householdId');
|
|
const listId = url.searchParams.get('listId') || undefined;
|
|
|
|
if (!userId || !householdId) {
|
|
console.warn('WebSocket connection rejected: missing userId or householdId');
|
|
ws.close(4001, 'Missing auth parameters');
|
|
return;
|
|
}
|
|
|
|
const connection: ClientConnection = {
|
|
ws,
|
|
userId,
|
|
householdId,
|
|
listId,
|
|
};
|
|
|
|
// Add to connected clients
|
|
if (!connectedClients.has(householdId)) {
|
|
connectedClients.set(householdId, []);
|
|
}
|
|
connectedClients.get(householdId)!.push(connection);
|
|
|
|
console.log(
|
|
`[WebSocket] User ${userId} connected to household ${householdId}. Total: ${connectedClients.get(householdId)!.length}`
|
|
);
|
|
|
|
// Send confirmation
|
|
ws.send(
|
|
JSON.stringify({
|
|
type: 'connected',
|
|
userId,
|
|
householdId,
|
|
timestamp: new Date().toISOString(),
|
|
})
|
|
);
|
|
|
|
// Handle messages
|
|
ws.on('message', (data) => {
|
|
try {
|
|
const message = JSON.parse(data.toString());
|
|
handleWebSocketMessage(connection, message);
|
|
} catch (err) {
|
|
console.error('[WebSocket] Failed to parse message:', err);
|
|
ws.send(
|
|
JSON.stringify({
|
|
type: 'error',
|
|
message: 'Invalid message format',
|
|
})
|
|
);
|
|
}
|
|
});
|
|
|
|
// Handle disconnect
|
|
ws.on('close', () => {
|
|
handleDisconnect(connection);
|
|
});
|
|
|
|
ws.on('error', (err) => {
|
|
console.error('[WebSocket] Connection error:', err);
|
|
handleDisconnect(connection);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Handle incoming WebSocket messages
|
|
*/
|
|
function handleWebSocketMessage(connection: ClientConnection, message: any) {
|
|
const { type, data } = message;
|
|
|
|
console.log(`[WebSocket] Message from ${connection.userId}: ${type}`);
|
|
|
|
switch (type) {
|
|
case 'item_checked':
|
|
broadcastToHousehold(connection.householdId, {
|
|
type: 'item_checked',
|
|
listId: data.listId,
|
|
itemId: data.itemId,
|
|
checked: data.checked,
|
|
userId: connection.userId,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
break;
|
|
|
|
case 'item_added':
|
|
broadcastToHousehold(connection.householdId, {
|
|
type: 'item_added',
|
|
listId: data.listId,
|
|
item: data.item,
|
|
userId: connection.userId,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
break;
|
|
|
|
case 'item_removed':
|
|
broadcastToHousehold(connection.householdId, {
|
|
type: 'item_removed',
|
|
listId: data.listId,
|
|
itemId: data.itemId,
|
|
userId: connection.userId,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
break;
|
|
|
|
case 'list_reset':
|
|
broadcastToHousehold(connection.householdId, {
|
|
type: 'list_reset',
|
|
listId: data.listId,
|
|
excludedItemIds: data.excludedItemIds,
|
|
userId: connection.userId,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
break;
|
|
|
|
case 'list_created':
|
|
broadcastToHousehold(connection.householdId, {
|
|
type: 'list_created',
|
|
list: data.list,
|
|
userId: connection.userId,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
break;
|
|
|
|
case 'ping':
|
|
connection.ws.send(
|
|
JSON.stringify({
|
|
type: 'pong',
|
|
timestamp: new Date().toISOString(),
|
|
})
|
|
);
|
|
break;
|
|
|
|
default:
|
|
console.warn(`[WebSocket] Unknown message type: ${type}`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Broadcast message to all clients in a household
|
|
*/
|
|
function broadcastToHousehold(householdId: string, message: any) {
|
|
const clients = connectedClients.get(householdId);
|
|
if (!clients) return;
|
|
|
|
let sentCount = 0;
|
|
for (const client of clients) {
|
|
if (client.ws.readyState === WebSocket.OPEN) {
|
|
client.ws.send(JSON.stringify(message));
|
|
sentCount++;
|
|
}
|
|
}
|
|
|
|
console.log(
|
|
`[WebSocket] Broadcast to household ${householdId}: sent to ${sentCount}/${clients.length} clients`
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Handle client disconnect
|
|
*/
|
|
function handleDisconnect(connection: ClientConnection) {
|
|
const clients = connectedClients.get(connection.householdId);
|
|
if (!clients) return;
|
|
|
|
const index = clients.indexOf(connection);
|
|
if (index > -1) {
|
|
clients.splice(index, 1);
|
|
}
|
|
|
|
if (clients.length === 0) {
|
|
connectedClients.delete(connection.householdId);
|
|
}
|
|
|
|
console.log(
|
|
`[WebSocket] User ${connection.userId} disconnected from household ${connection.householdId}. Remaining: ${clients?.length || 0}`
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Graceful shutdown
|
|
*/
|
|
export function closeWebSocketServer(wss: WebSocketServer) {
|
|
connectedClients.forEach((clients) => {
|
|
clients.forEach((client) => {
|
|
client.ws.close(1000, 'Server shutting down');
|
|
});
|
|
});
|
|
connectedClients.clear();
|
|
wss.close();
|
|
console.log('[WebSocket] Server closed');
|
|
}
|