| 1 | // Hibernatable WebSocket: a DO whose webSocketMessage echoes and persists a |
| 2 | // count. The socket is held by the host, so the DO can hibernate between |
| 3 | // messages and wake with count intact. |
| 4 | // Connect with a WebSocket upgrade against the node's listener, e.g.: |
| 5 | // websocat ws://127.0.0.1:8080/ |
| 6 | export class W { |
| 7 | constructor(state, env) { this.state = state; } |
| 8 | async fetch(request) { |
| 9 | if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") { |
| 10 | return new Response("websocket upgrade required", { status: 426 }); |
| 11 | } |
| 12 | const pair = new WebSocketPair(); |
| 13 | const server = pair[0]; |
| 14 | this.state.acceptWebSocket(server); |
| 15 | return new Response(null, { status: 101, webSocket: pair[1] }); |
| 16 | } |
| 17 | async webSocketMessage(ws, msg) { |
| 18 | let count = (await this.state.storage.get("count")) ?? 0; |
| 19 | count++; |
| 20 | await this.state.storage.put("count", count); |
| 21 | ws.send(JSON.stringify({ echo: msg, count })); |
| 22 | } |
| 23 | } |
| 24 | export default { |
| 25 | async fetch(request, env) { |
| 26 | return env.W.get(env.W.idFromName("w")).fetch(request); |
| 27 | } |
| 28 | }; |