Files
concord/concord-server/src/index.ts

83 lines
1.9 KiB
TypeScript
Raw Normal View History

import { Hono } from "hono";
import { cors } from "hono/cors";
import { Server as Engine } from "@socket.io/bun-engine";
import { Server } from "socket.io";
import routes from "./routes/index";
import { Scalar } from "@scalar/hono-api-reference";
import { openAPIRouteHandler } from "hono-openapi";
2025-09-28 03:18:11 -04:00
import { registerSocketHandlers } from "./sockets";
2025-09-28 03:11:34 -04:00
// Routes
const app = new Hono();
2025-09-26 23:36:08 -04:00
app.use(
"*",
cors({
origin: "http://localhost:5173",
2025-09-28 03:18:11 -04:00
allowHeaders: [
"Content-Type",
"Authorization",
"Access-Control-Allow-Origin",
],
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
credentials: true,
}),
);
app.route("/api", routes);
app.get(
2025-09-27 15:55:20 -04:00
"/openapi",
openAPIRouteHandler(app, {
documentation: {
info: {
2025-09-27 15:55:20 -04:00
title: "Hono API",
version: "1.0.0",
description: "Greeting API",
},
2025-09-27 15:55:20 -04:00
servers: [{ url: "http://localhost:3000", description: "Local Server" }],
},
2025-09-27 15:55:20 -04:00
}),
);
2025-09-27 15:55:20 -04:00
app.get("/scalar", Scalar({ url: "/openapi" }));
2025-09-28 03:11:34 -04:00
// initialize socket.io server
const io = new Server({
cors: {
origin: "http://localhost:5173",
credentials: true,
2025-09-28 03:18:11 -04:00
},
2025-09-28 03:11:34 -04:00
});
const engine = new Engine();
io.bind(engine);
// Register socket.io events
2025-09-28 03:18:11 -04:00
registerSocketHandlers(io);
2025-09-28 03:11:34 -04:00
const { websocket } = engine.handler();
export default {
port: 3000,
idleTimeout: 30, // must be greater than the "pingInterval" option of the engine, which defaults to 25 seconds
async fetch(req: Request, server: Bun.Server) {
const url = new URL(req.url);
if (url.pathname === "/socket.io/") {
const response = await engine.handleRequest(req, server);
// Add CORS headers explicitly
2025-09-28 03:18:11 -04:00
response.headers.set(
"Access-Control-Allow-Origin",
"http://localhost:5173",
);
2025-09-28 03:11:34 -04:00
response.headers.set("Access-Control-Allow-Credentials", "true");
return response;
} else {
return app.fetch(req, server);
}
},
2025-09-28 03:18:11 -04:00
websocket,
2025-09-28 03:11:34 -04:00
};