honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
20.53k stars 595 forks source link

Support for subscribe and publish Websocket API in Bun Adapter #3230

Open newarifrh opened 3 months ago

newarifrh commented 3 months ago

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

Proposal

Benefits

References

nakasyou commented 3 months ago

It is capable without Bun, so I think that it's good that Hono will provide this API for all runtime as utils.

newarifrh commented 3 months ago

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.

manastunga787 commented 1 month ago

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