import { Hono } from "hono"; import debug from "debug"; import type { FileCategory, } from "../client/share/types.ts"; import { DeleteStatus, } from "../client/share/types.ts"; import type { Variables, WithAuth } from "./middlewares.ts"; const log = { api: debug("api:file_categories"), }; // 创建文件分类路由 export function createFileCategoryRoutes(withAuth: WithAuth) { const fileCategoryRoutes = new Hono<{ Variables: Variables }>(); // 获取文件分类列表 fileCategoryRoutes.get("/", withAuth, async (c) => { try { const apiClient = c.get('apiClient'); const page = Number(c.req.query("page")) || 1; const pageSize = Number(c.req.query("pageSize")) || 10; const offset = (page - 1) * pageSize; const search = c.req.query("search") || ""; let query = apiClient.database.table("file_categories").orderBy("id", "desc"); if (search) { query = query.where("name", "like", `%${search}%`); } const total = await query.clone().count(); const categories = await query .select("id", "name", "code", "description") .limit(pageSize) .offset(offset); return c.json({ data: categories, total: Number(total), page, pageSize, }); } catch (error) { log.api("获取文件分类列表失败:", error); return c.json({ error: "获取文件分类列表失败" }, 500); } }); // 创建文件分类 fileCategoryRoutes.post("/", withAuth, async (c) => { try { const apiClient = c.get('apiClient'); const data = (await c.req.json()) as Partial; // 验证必填字段 if (!data.name) { return c.json({ error: "分类名称不能为空" }, 400); } // 插入文件分类 const [id] = await apiClient.database.table("file_categories").insert({ ...data, created_at: apiClient.database.fn.now(), updated_at: apiClient.database.fn.now(), }); return c.json({ message: "文件分类创建成功", data: { id, ...data, }, }); } catch (error) { log.api("创建文件分类失败:", error); return c.json({ error: "创建文件分类失败" }, 500); } }); // 更新文件分类 fileCategoryRoutes.put("/:id", withAuth, async (c) => { try { const apiClient = c.get('apiClient'); const id = Number(c.req.param("id")); if (!id || isNaN(id)) { return c.json({ error: "无效的分类ID" }, 400); } const data = (await c.req.json()) as Partial; // 更新文件分类 await apiClient.database .table("file_categories") .where("id", id) .update({ ...data, updated_at: apiClient.database.fn.now(), }); return c.json({ message: "文件分类更新成功", data: { id, ...data, }, }); } catch (error) { log.api("更新文件分类失败:", error); return c.json({ error: "更新文件分类失败" }, 500); } }); // 删除文件分类 fileCategoryRoutes.delete("/:id", withAuth, async (c) => { try { const apiClient = c.get('apiClient'); const id = Number(c.req.param("id")); if (!id || isNaN(id)) { return c.json({ error: "无效的分类ID" }, 400); } await apiClient.database.table("file_categories").where("id", id).update({ is_deleted: DeleteStatus.DELETED, updated_at: apiClient.database.fn.now(), }); return c.json({ message: "文件分类删除成功", }); } catch (error) { log.api("删除文件分类失败:", error); return c.json({ error: "删除文件分类失败" }, 500); } }); return fileCategoryRoutes; }