import cuid from "cuid"; import _ from "lodash"; import { getDb } from "funjia-server/lib/funjia-server.mjs"; import { getTable, pickFilters, matchRow, listResponse } from "../helpers.mjs"; /** * 通知路由。 * * 改造前与 `dynamic.mjs` 存在同款问题: * - 表为空时 `data.length` 抛 TypeError; * - `upd` / `delete` 在表缺失时用 `db.data = { Notice: [] }` **整体替换数据库对象**, * 紧接着 `db.write()` 落盘,会把其它业务表全部清掉; * - `upd` 允许请求体覆盖主键 id; * - 每次请求 `console.log` 完整参数。 */ const getNotice = (router) => { const tableName = "Notice"; router.post("/api/Notice/list", async (ctx) => { ctx.type = "application/json"; const { table } = await getTable(getDb, tableName); const body = ctx.request.body || {}; const data = table .filter((item) => matchRow(item, pickFilters(body))) .sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)); ctx.body = listResponse(data, body); }); router.get("/api/Notice", async (ctx) => { ctx.type = "application/json"; const { table } = await getTable(getDb, tableName); const detail = table.find((item) => item.id == ctx.request.query.id); ctx.body = { code: 0, data: detail || {} }; }); router.post("/api/Notice/add", async (ctx) => { ctx.type = "application/json"; const { db, table } = await getTable(getDb, tableName); const { id, createTime, ...rest } = ctx.request.body || {}; void id; void createTime; table.push({ ...rest, id: cuid(), createTime: new Date() }); await db.write(); ctx.body = { code: 0 }; }); router.post("/api/Notice/upd", async (ctx) => { ctx.type = "application/json"; const { db, table } = await getTable(getDb, tableName); const { id, createTime, ...patch } = ctx.request.body || {}; // id / createTime 由服务端维护,不接受请求体覆盖 void id; void createTime; const current = table.find((item) => item.id == id); if (!current) { ctx.body = { code: 1, msg: "通知不存在" }; return; } _.merge(current, patch); await db.write(); ctx.body = { code: 0 }; }); router.post("/api/Notice/delete", async (ctx) => { ctx.type = "application/json"; const { db, table } = await getTable(getDb, tableName); const ids = (ctx.request.body?.ids || []).map(String); if (ids.length === 0) { ctx.body = { code: 1, msg: "未指定要删除的记录" }; return; } const before = table.length; const rest = table.filter((item) => !ids.includes(String(item.id))); table.length = 0; table.push(...rest); await db.write(); ctx.body = { code: 0, data: { deleted: before - table.length } }; }); }; export default getNotice;