Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

To enable websocket support, set the "websocket" object in Bun.serve({}) #3618

Open
moshOntong-IT opened this issue Nov 3, 2024 · 2 comments
Labels

Comments

@moshOntong-IT
Copy link

What version of Hono are you using?

4.6.8

What runtime/platform is your app running on? (with version if possible)

Bun

What steps can reproduce the bug?

Setup the a bun runtime with websocket. use the Bun.serve. Then create a front end that implemented a websocket

What is the expected behavior?

It will run smoothly but try to go to a page that has websocket. It will connected to websocket successfully

What do you see instead?

Actual:

9 |   const upgradeWebSocket = defineWebSocketHelper((c, events) => {
20 |     const server = getBunServer(c);
21 |     if (!server) {
22 |       throw new TypeError("env has to include the 2nd argument of fetch.");
23 |     }
24 |     const upgradeResult = server.upgrade(c.req.raw, {     
                                      ^
TypeError: To enable websocket support, set the "websocket" object in Bun.serve({})
 code: "ERR_INVALID_ARG_TYPE"

      at E:\react-project\bun-hono-websocket\backend\node_modules\hono\dist\adapter\bun\websocket.js:24:34
      at E:\react-project\bun-hono-websocket\backend\node_modules\hono\dist\helper\websocket\index.js:33:28

--> GET /api/v1/ws 500 437ms

Additional information

import { Hono } from "hono";
import { createBunWebSocket } from "hono/bun";
import { cors } from "hono/cors";
import accountRoutes from "./routers/account-routes";
import { logger } from "hono/logger";
import type { AuthorizationType } from "./types";
import { routeGuardMiddleware } from "../middleware/route-guard-middleware";
import corsExtension from "../middleware/cors-extension-middleware";
import type { ServerWebSocket } from "bun";

declare module "hono" {
  interface ContextVariableMap {
    authorizationType: AuthorizationType;
    authorizationValue: string;
  }
}

const app = new Hono().basePath("/api/v1");
const { upgradeWebSocket, websocket } = createBunWebSocket();

const topic = "anonymous-chat-room";

app.use(logger());
app.use(corsExtension);
app.route("/account", accountRoutes);

Bun.serve({
  fetch: app.fetch,
  port: 5000,
  websocket,
});

app.get(
  "/ws",
  routeGuardMiddleware,
  async (c, next) => {
    console.log("WebSocket server opened");
    c.json({ message: "WebSocket server opened" });
    return next();
  },
  upgradeWebSocket((c) => ({
    onOpen(_, ws) {
      const rawWs = ws.raw as ServerWebSocket;
      rawWs.subscribe(topic);
      // server.publish(topic, "WebSocket server opened and subscribed to topic");
      console.log(`Authorization type: ${c.get("authorizationType")}`);
      console.log(`Authorization value: ${c.get("authorizationValue")}`);
      console.log(`WebSocket server opened and subscribed to topic '${topic}'`);
    },
    onClose(_, ws) {
      const rawWs = ws.raw as ServerWebSocket;
      rawWs.unsubscribe(topic);
      console.log(
        `WebSocket server closed and unsubscribed from topic '${topic}'`
      );
    },
  }))
);

export default app;
// export default serve({
//   port: 5000,
//   fetch: app.fetch,
//   websocket,
// });

// export default {
//   port: 5000,
//   fetch: app.fetch,
//   websocket,
// };

// export default {
//   port: 4000,
//   fetch: app.fetch,
//   websocket,
// };
@moshOntong-IT
Copy link
Author

export default {
  port: 3000,
  fetch: app.fetch,
  websocket,
};

But when I am only using this it will run all smoothly. But I need the instance of Bun.serve because I want the Pub sub

@yusukebe
Copy link
Member

yusukebe commented Nov 4, 2024

Hi @moshOntong-IT

Remove the following at the last line:

export default app

and access the 5000 port.

@yusukebe yusukebe added not bug and removed triage labels Nov 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants