Spaces:
Runtime error
Runtime error
| import path from "node:path"; | |
| import express from "express"; | |
| import { createApiRouter } from "./routes/apiRouter.js"; | |
| import { HttpError } from "./utils/httpError.js"; | |
| export function createApp({ | |
| jsonLimit, | |
| publicDir, | |
| chatController, | |
| mediaController | |
| }) { | |
| const app = express(); | |
| app.disable("x-powered-by"); | |
| app.use((req, res, next) => { | |
| res.setHeader("Access-Control-Allow-Origin", "*"); | |
| res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS"); | |
| const requestedHeaders = req.get("access-control-request-headers"); | |
| res.setHeader("Access-Control-Allow-Headers", requestedHeaders || "Content-Type, Authorization"); | |
| if (req.method === "OPTIONS") { | |
| res.status(204).end(); | |
| return; | |
| } | |
| next(); | |
| }); | |
| app.use(express.json({ limit: jsonLimit })); | |
| app.get("/", (_req, res) => { | |
| res.sendFile(path.join(publicDir, "index.html")); | |
| }); | |
| app.get(["/chatclient", "/chatclient/"], (_req, res) => { | |
| res.sendFile(path.join(publicDir, "chatclient", "index.html")); | |
| }); | |
| app.get(["/chat", "/chat/"], (_req, res) => { | |
| res.redirect(302, "/chatclient/"); | |
| }); | |
| app.use(express.static(publicDir, { | |
| extensions: ["html"], | |
| index: false, | |
| redirect: false | |
| })); | |
| app.use("/v1", createApiRouter({ chatController, mediaController })); | |
| app.use((req, _res, next) => { | |
| next(new HttpError(404, `Route not found: ${req.method} ${req.originalUrl}`)); | |
| }); | |
| app.use((error, _req, res, _next) => { | |
| const statusCode = error.statusCode ?? 500; | |
| res.status(statusCode).json({ | |
| error: { | |
| message: error.message ?? "Internal server error", | |
| details: error.details ?? null | |
| } | |
| }); | |
| }); | |
| return app; | |
| } | |