home-lab/backend/index.ts

36 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-03-16 10:14:17 +07:00
import "dotenv/config";
2024-03-15 09:05:49 +07:00
import { Hono } from "hono";
import { cors } from "hono/cors";
2024-03-16 10:40:17 +07:00
import fs from "node:fs";
2024-03-16 07:52:42 +07:00
import { HTTPException } from "hono/http-exception";
2024-03-16 10:14:17 +07:00
import { serveStatic } from "@hono/node-server/serve-static";
import { serve } from "@hono/node-server";
2024-03-16 07:52:42 +07:00
import routes from "./routes/_routes";
2024-03-16 10:14:17 +07:00
import createWsServer from "./websocket";
2024-03-15 09:05:49 +07:00
2024-03-16 10:40:17 +07:00
const PUBLIC_DIR = "./public";
2024-03-15 09:05:49 +07:00
const app = new Hono()
.use(cors())
2024-03-16 10:40:17 +07:00
.route("/api", routes)
.use("*", serveStatic({ root: PUBLIC_DIR }), async (c) => {
const index = fs.readFileSync(PUBLIC_DIR + "/index.html", "utf8");
c.header("Content-Type", "text/html");
return c.html(index);
})
2024-03-16 07:52:42 +07:00
.onError((err, c) => {
if (err instanceof HTTPException) {
return err.getResponse();
2024-03-15 09:05:49 +07:00
}
2024-03-16 07:52:42 +07:00
return c.json({ message: err.message }, 500);
});
2024-03-15 09:05:49 +07:00
2024-03-16 10:20:21 +07:00
const server = serve(
{ fetch: app.fetch, port: parseInt(process.env.PORT || "") || 3000 },
(info) => {
console.log(`App listening on http://${info.address}:${info.port}`);
}
);
2024-03-16 10:14:17 +07:00
createWsServer(server);