| import express from "express"; |
| import cors from "cors"; |
| import fs from "node:fs"; |
| import path from "node:path"; |
| import { fileURLToPath } from "node:url"; |
| import { connectDatabase, isDatabaseReady, scheduleReconnect } from "./config/db.js"; |
| import { env } from "./config/env.js"; |
| import { requireAuth } from "./middleware/auth.js"; |
| import { authRoutes } from "./routes/authRoutes.js"; |
| import { cardRoutes } from "./routes/cardRoutes.js"; |
| import { entryRoutes } from "./routes/entryRoutes.js"; |
| const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| const repoRoot = path.resolve(__dirname, "../.."); |
| const clientDistPath = path.join(repoRoot, "client", "dist"); |
| const hasClientBuild = fs.existsSync(path.join(clientDistPath, "index.html")); |
| const app = express(); |
| app.use(cors()); |
| app.use(express.json({ limit: "1mb" })); |
| app.get("/api/health", (_req, res) => { |
| res.json({ ok: true, databaseReady: isDatabaseReady() }); |
| }); |
| app.use("/api/auth", authRoutes); |
| app.use("/api/cards", requireAuth, (req, res, next) => { |
| if (!isDatabaseReady()) { |
| return res.status(503).json({ error: "Database unavailable" }); |
| } |
| return next(); |
| }); |
| app.use("/api/cards", cardRoutes); |
| app.use("/api/entries", requireAuth, (req, res, next) => { |
| if (!isDatabaseReady()) { |
| return res.status(503).json({ error: "Database unavailable" }); |
| } |
| return next(); |
| }); |
| app.use("/api/entries", entryRoutes); |
| if (hasClientBuild) { |
| app.use(express.static(clientDistPath)); |
| app.get("*", (req, res, next) => { |
| if (req.path.startsWith("/api/")) { |
| return next(); |
| } |
| return res.sendFile(path.join(clientDistPath, "index.html")); |
| }); |
| } |
| app.use((error, _req, res, _next) => { |
| console.error(error); |
| res.status(500).json({ error: "Internal server error" }); |
| }); |
| app.listen(env.port, () => { |
| console.log(`MNEMO server running on ${env.port}`); |
| }); |
| connectDatabase() |
| .then(() => { |
| console.log("MongoDB connected"); |
| }) |
| .catch((error) => { |
| console.error("Database connection failed", error.message); |
| scheduleReconnect(); |
| }); |
|
|