import cuid from "cuid"; import _ from "lodash"; import { getDb } from "funjia-server/lib/funjia-server.mjs"; import { getTable as getTableRaw, pickFilters, matchRow, listResponse } from "./helpers.mjs"; /** * 通用动态表 CRUD 路由。 * * ## 改造前存在的三个严重缺陷 * * 1. **upd / delete 会把整库数据清空** * ```js * if (!db.data[tableName]) db.data = { dynamic: [] } // ← 整个 db.data 被替换 * ``` * 当目标表不存在时,不是创建该表,而是把**整个数据库对象**换成 `{ dynamic: [] }`, * 紧接着 `db.write()` 落盘——employee / Notice / qa 等所有业务表瞬间消失。 * 现在只创建缺失的那一张表。 * * 2. **列表接口在表为空时抛 TypeError** * `db.data[name]?.filter(...)` 得到 `undefined` 后,紧接着访问 * `data.length` / `data.slice(...)`,直接 500。`employee` / `Notice` / * `upload` 路由都有同样问题,这里统一补默认空数组。 * * 3. **删除用 splice 逐个匹配,ids 中不存在的 id 会被静默忽略** * 改为过滤后回填,并返回实际删除条数,便于前端核对。 * * 另外:原实现每次请求都 `console.log` 完整查询参数与写入的数据对象, * 密码、手机号等个人信息会直接进日志,已全部移除。 * * 「过滤 / 分页 / 取表」等工具已收口到 `helpers.mjs`,本文件不再重复实现。 */ const getDynamic = (router) => { /** 取表并保证其为数组(关键:只在表缺失时补该表,不动 db.data 本身) */ const getTable = (tableName) => getTableRaw(getDb, tableName); router.post("/api/dynamic/list/:tableName", async (ctx) => { ctx.type = "application/json"; const { table } = await getTable(ctx.params.tableName); const body = ctx.request.body || {}; const data = table.filter((item) => matchRow(item, pickFilters(body))); ctx.body = listResponse(data, body); }); router.get("/api/dynamic/:tableName", async (ctx) => { ctx.type = "application/json"; const { table } = await getTable(ctx.params.tableName); const { id } = ctx.request.query; ctx.body = { code: 0, data: table.find((item) => item.id == id) || {}, }; }); router.post("/api/dynamic/add/:tableName", async (ctx) => { ctx.type = "application/json"; const { db, table } = await getTable(ctx.params.tableName); table.push({ ...(ctx.request.body || {}), id: cuid(), createTime: new Date() }); await db.write(); ctx.body = { code: 0 }; }); router.post("/api/dynamic/upd/:tableName", async (ctx) => { ctx.type = "application/json"; const { db, table } = await getTable(ctx.params.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/dynamic/delete/:tableName", async (ctx) => { ctx.type = "application/json"; const { db, table } = await getTable(ctx.params.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 getDynamic;