import { Hono } from "hono";
import { cors } from "hono/cors";
import { serveStatic } from "@hono/node-server/serve-static";
import { prisma } from "../../lib/prisma.js";
export function createCMSApp() {
const app = new Hono();
// 跨域支持
app.use("/*", cors());
// 静态文件服务 (必须在 API 路由之前)
app.use("/*", serveStatic({ root: "./public" }));
app.get("/", (c) => c.redirect("/index.html"));
// API 路由组
const api = new Hono().basePath("/api");
// 日志中间件
api.use("/*", async (c, next) => {
console.error(`[CMS API] ${c.req.method} ${c.req.url}`);
await next();
});
// Mock 登录接口
api.post("/auth/login", async (c) => {
const { username, password } = await c.req.json();
if (username === "admin" && password === "admin123") {
return c.json({
success: true,
data: {
token: "mock-token-" + Date.now(),
user: { id: 1, username: "admin", role: "admin" }
}
});
}
return c.json({
success: false,
error: { message: "用户名或密码错误" }
}, 401);
});
// Mock 分类接口
api.get("/categories", async (c) => {
return c.json({
success: true,
data: [
{ id: "wiki", name: "Wiki" },
{ id: "rule", name: "规章制度" },
{ id: "notification", name: "内部通知" }
]
});
});
// API 路由 (此时已带 /api 前缀)
api.get("/documents", async (c) => {
const docs = await prisma.document.findMany({
orderBy: { updatedAt: "desc" },
});
return c.json({ success: true, data: docs });
});
api.post("/documents", async (c) => {
const body = await c.req.json();
const { title, content, type, tags } = body;
const doc = await prisma.document.create({
data: {
title,
content,
type,
tags: Array.isArray(tags) ? JSON.stringify(tags) : tags
},
});
return c.json({ success: true, data: doc });
});
api.put("/documents/:id", async (c) => {
const id = parseInt(c.req.param("id"));
const body = await c.req.json();
const { title, content, type, tags } = body;
await prisma.document.update({
where: { id },
data: {
title,
content,
type,
tags: Array.isArray(tags) ? JSON.stringify(tags) : tags
},
});
return c.json({ success: true, data: { success: true } });
});
api.delete("/documents/:id", async (c) => {
const id = parseInt(c.req.param("id"));
await prisma.document.delete({
where: { id },
});
return c.json({ success: true, data: { success: true } });
});
// 404 兜底
api.notFound((c) => {
console.error(`[CMS API] 404 NOT FOUND: ${c.req.method} ${c.req.url}`);
return c.text("Not Found", 404);
});
app.route("/", api);
return app;
}