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

81 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: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:11:34 -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,
}
});
const engine = new Engine();
io.bind(engine);
// Register socket.io events
io.on("connection", (socket) => {
console.log("connected1");
socket.on("ping", (c) => {
console.log(c);
socket.emit("pong", c);
});
});
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
response.headers.set("Access-Control-Allow-Origin", "http://localhost:5173");
response.headers.set("Access-Control-Allow-Credentials", "true");
return response;
} else {
return app.fetch(req, server);
}
},
websocket
};