Handle websockets from Durable Objects
I have my own Durable Object class that implements websockets. It works well with raw cloudflare workers
But when I try to implement hono, it does not works.
How to make Hono handle my Cloudflare Durable Object with Websocket. I do not want to use the Hono websockets helpe, I have my own class to handle it.
const app = new Hono()
app.get('/websocket', async ({ req, env }) => {
const id = req.param('id');
const notifierId = env.WEBSOCKET_NOTIFIER.idFromName(id);
const notifier = env.WEBSOCKET_NOTIFIER.get(id);
return notifier.fetch(req.url, req);
});
export class WebsocketNotifier extends DurableObject<Env> {
sessions = new Set<WebSocket>();
async fetch(request: Request) {
if (request.headers.get('Upgrade') != 'websocket') {
return new Response('expected websocket', { status: 400 });
}
const pair = new WebSocketPair();
// We're going to take pair[1] as our end, and return pair[0] to the client.
await this.handleSession(pair[1]);
// Now we return the other end of the pair to the client.
return new Response(null, { status: 101, webSocket: pair[0] });
}
// handleSession() implements our WebSocket-based chat protocol.
async handleSession(webSocket: WebSocket) {
// Accept our end of the WebSocket. This tells the runtime that we'll be terminating the
// WebSocket in JavaScript, not sending it elsewhere.
this.state.acceptWebSocket(webSocket);
this.sessions.add(webSocket);
let storage = await this.storage.list<Record<any, any>>({ reverse: true, limit: 100 });
let backlog = [...storage.values()];
backlog.reverse();
backlog.forEach((value) => {
webSocket.send(JSON.stringify(value));
});
}
...
}
const app = new Hono()
app.get('/websocket', async ({ req, env }) => {
const id = req.param('id');
const notifierId = env.WEBSOCKET_NOTIFIER.idFromName(id);
const notifier = env.WEBSOCKET_NOTIFIER.get(id);
return notifier.fetch(req.url, req);
});
export class WebsocketNotifier extends DurableObject<Env> {
sessions = new Set<WebSocket>();
async fetch(request: Request) {
if (request.headers.get('Upgrade') != 'websocket') {
return new Response('expected websocket', { status: 400 });
}
const pair = new WebSocketPair();
// We're going to take pair[1] as our end, and return pair[0] to the client.
await this.handleSession(pair[1]);
// Now we return the other end of the pair to the client.
return new Response(null, { status: 101, webSocket: pair[0] });
}
// handleSession() implements our WebSocket-based chat protocol.
async handleSession(webSocket: WebSocket) {
// Accept our end of the WebSocket. This tells the runtime that we'll be terminating the
// WebSocket in JavaScript, not sending it elsewhere.
this.state.acceptWebSocket(webSocket);
this.sessions.add(webSocket);
let storage = await this.storage.list<Record<any, any>>({ reverse: true, limit: 100 });
let backlog = [...storage.values()];
backlog.reverse();
backlog.forEach((value) => {
webSocket.send(JSON.stringify(value));
});
}
...
}
0 Replies