File size: 1,666 Bytes
5ef6e9d
 
 
 
43ef8b7
 
5ef6e9d
 
 
 
 
 
43ef8b7
 
 
5ef6e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43ef8b7
 
 
 
 
 
 
 
 
 
 
 
 
5ef6e9d
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
62
63
import express, { type Express } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import pinoHttp from "pino-http";
import path from "path";
import { fileURLToPath } from "url";
import router from "./routes";
import openaiRouter from "./routes/openai";
import publicRouter from "./routes/public";
import accountsRouter from "./routes/accounts";
import { logger } from "./lib/logger";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app: Express = express();

app.use(
  pinoHttp({
    logger,
    serializers: {
      req(req) {
        return {
          id: req.id,
          method: req.method,
          url: req.url?.split("?")[0],
        };
      },
      res(res) {
        return {
          statusCode: res.statusCode,
        };
      },
    },
  }),
);

app.use(cors({ credentials: true, origin: true }));
app.use(cookieParser());
app.use(express.json({ limit: "20mb" }));
app.use(express.urlencoded({ extended: true, limit: "20mb" }));

app.use("/api/public", publicRouter);
app.use("/api/admin/accounts", accountsRouter);
app.use("/api", router);
app.use("/v1", openaiRouter);
app.use("/api/v1", openaiRouter);

// 提供前端靜態檔案
const frontendDistPath = path.join(__dirname, "../../image-gen/dist");
app.use(express.static(frontendDistPath));

// SPA fallback - 所有非 API 路由都返回 index.html
app.get("*", (req, res) => {
  if (!req.path.startsWith("/api") && !req.path.startsWith("/v1")) {
    res.sendFile(path.join(frontendDistPath, "index.html"));
  } else {
    res.status(404).json({ error: "Not found" });
  }
});

export default app;