// Durable Object
export default class WebSocketHibernationServer extends DurableObject {
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
// Extract userId from the protocol
const wsProtocol = request.headers.get('Sec-WebSocket-Protocol');
const [protocol] = wsProtocol?.split(', ') || [];
console.log('server', { protocol });
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);
this.ctx.acceptWebSocket(server);
return new Response(null, {
status: 101,
headers: {
Upgrade: 'websocket',
Connection: 'Upgrade',
'Sec-WebSocket-Protocol': protocol || '',
},
webSocket: client,
});
}
async webSocketMessage(ws: WebSocket, message: ArrayBuffer | string) {
// TODO: How do we get the user ID from the websocket?
const websockets = this.ctx.getWebSockets();
for (const ws of websockets) {
ws.send(message);
}
}
async webSocketClose(ws: WebSocket, code: number, reason: string, _wasClean: boolean) {
ws.close(code, reason);
}
}