File size: 2,049 Bytes
81fc505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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();
  });