Support for subscribe and publish Websocket API in Bun Adapter
What is the feature you are proposing?
Description
Currently, Hono.js's WebSocket helper provides several adapters, one of which is Bun. However, the Bun adapter only supports the send() API. According to the Bun WebSocket documentation, there are other useful APIs like subscribe and publish. These APIs can be used to send data/messages to users subscribed to the same topic. With the current send() API, messages have to be sent in a loop which is not efficient for broadcasting messages.
Use Case
- Broadcast Messages: Efficiently send messages to all users subscribed to a specific topic.
- Topic-Based Messaging: Allow users to subscribe to specific topics and receive relevant messages without sending individual messages in a loop.
Proposal
- Implement support for
subscribeandpublishAPIs in the Bun adapter. - Update the documentation to reflect the new capabilities.
Benefits
- Improved efficiency in message broadcasting.
- Enhanced flexibility in handling WebSocket connections and messages.
References
It is capable without Bun, so I think that it's good that Hono will provide this API for all runtime as utils.
Yes, I agree with that. However, I haven't seen if there are native APIs for other adapters. So far, I have been able to work for Bun adapter using native API.
If you want to use publish and subscribe api of Bun. You can use ws.raw in hono app.
import { Hono } from 'hono'
import { createBunWebSocket } from 'hono/bun'
import type { ServerWebSocket } from 'bun'
app.get(
"/ws",
upgradeWebSocket((c) => {
return {
onOpen: (_, ws) => {
const rawWs = ws.raw as ServerWebSocket;
rawWs.subscribe("the-group-chat");
// in rawWs you can access bun's subscribe and publish api
},
onClose: (_, ws) => {
},
onMessage: (data, ws) => {
const rawWs = ws.raw as ServerWebSocket;
},
};
})
);
if you want to use server.publish api of bun
const server = Bun.serve({
port: 3001,
fetch: app.fetch,
websocket: websocket,
});
// now you can use server.publish()
you can find more information Here