重构: 修复致命缺陷、清理死代码并打通类型检查与构建
本次优化在不改变业务行为的前提下,修复了多处会导致数据丢失或
功能失效的缺陷,并把此前从未跑过的类型检查与生产构建接通。
== 修复的严重缺陷 ==
服务端:
- dynamic/notice 路由在目标表缺失时用 `db.data = { dynamic: [] }`
整体替换数据库对象后落盘,会把 employee/Notice/qa 等全部业务表清空。
改为只创建缺失的那一张表。
- 列表接口在空表时访问 undefined.length 直接 500,统一补默认空数组。
- /api/employee/list 与 /login 明文返回 pwd 字段,且把含密码的
请求体写进日志。改为统一剔除敏感字段、移除参数日志。
- upd 允许请求体覆盖主键 id / createTime;改为服务端维护。
- upload 未限制扩展名与大小,且用原始扩展名拼路径。
前端:
- src/common/axios.ts 的拦截器注册在全局默认 axios 实例上,而业务
走 funjia-axios,导致拦截器全程失效;同时 funjia-axios 内部
`axios.prototype.error = () => {}` + `axios.prototype(msg)` 会抛
TypeError,使所有接口错误(含 401)被静默吞掉。现在本文件是唯一
的拦截器注册点。
- 修改密码功能形同虚设: PwdForm.onUpdate 只做 setTimeout 后 emit
成功,从不调接口;PwdDialog 又用已被拦截器解包掉的 status 判断
成败,无论结果都提示失败。
- Notice/Plugin 新增时 userId 静默丢失 (UmByClassEnhance 的
otherParams 只进 getList,不传 onAdd/onEdit),改用会话级
setCurrentUserId/getCurrentUserId。
- 修复 Login 模板绑定了从未定义的 loading、跳转到路由表里不存在
的路径;DynamicTable 里每次路由切换都触发的 debugger。
- 修复 Record/RecordUser 引用不存在的 marsLib/*、@/components/UmTable;
CodeMirror 使用 ref 却未 import; ImageCell 调用不存在的
getObjectTypeName。
== 结构优化 ==
- 新增 src/common/response.ts 与 BaseViewModel,收敛 7 个 viewModel
中重复 20+ 次的响应码判断与 CRUD 样板。
- 新增 server/routers/helpers.mjs,统一服务端取表/过滤/分页/脱敏。
- 新增 server/smoke-test.mjs,16 个用例覆盖上述修复(含整库清空回归)。
- 删除 0 引用的死文件: ImageList.vue、autoresponsive.vue、
animation.js、PwdDialog/PwdForm.vue。
== 工程配置 ==
- 修复阻塞安装与构建的三处错误:
funjiaui 指向不存在的仓库 FunjiaUI_Vue(#v1.1.3),实为
FunJiaUI_Vue_Package(#v1.3.1); pinia 锁 ~2.0.36 (vue 固定 3.2.33,
2.1+ 要求 vue ^3.3.0); App.vue 引用不存在的 funjiaui/dist/style.css,
实为包根目录 style.css。
- 新增 build/typecheck/build:only 脚本; 此前项目没有类型检查步骤。
- 移除 8 个未使用依赖,补齐 terser 与缺失的类型包。
- vite.config.ts 代理目标改由 .env 配置,移除硬编码内网地址;
增加 manualChunks 拆包。
- 服务端数据库改为不进版本库,提供 *.example.json 初始化模板。
== 验证 ==
- npx vue-tsc --noEmit : 0 错误
- npm run build : 成功 (1759 模块)
- cd server && npm run smoke : 16/16 通过
优化前的代码保留在 legacy 分支。
This commit is contained in:
+12
-2
@@ -1,2 +1,12 @@
|
||||
static/*
|
||||
config.yml
|
||||
# 上传文件目录
|
||||
static/*
|
||||
|
||||
# 本地配置(含绝对路径、备份目标等,不应提交)
|
||||
config.yml
|
||||
|
||||
# 运行期数据库。示例库可用 db/*.example.json 初始化,
|
||||
# 真实数据由部署环境自带,不进版本库
|
||||
db/db.json
|
||||
db/logDB.json
|
||||
db/resourceDB.json
|
||||
db/backupDB.json
|
||||
|
||||
+24
-22
@@ -1,22 +1,24 @@
|
||||
db: # 数据库配置
|
||||
db: &db E:\sourceCode\2025\funjia-admin-template-vue\server\db\db.json
|
||||
resourceDB: &resourceDB E:\sourceCode\2025\funjia-admin-template-vue\server\db\resourceDB.json
|
||||
backupDB: &backupDB E:\sourceCode\2025\funjia-admin-template-vue\server\db\backupDB.json
|
||||
logDB: &logDB E:\sourceCode\2025\funjia-admin-template-vue\server\db\logDB.json
|
||||
dbBak: # 数据库备份配置
|
||||
- #
|
||||
original: *db
|
||||
dest: F:/sourceCode/2022/compute-cms/bak/db
|
||||
category: db
|
||||
- #
|
||||
original: *resourceDB
|
||||
dest: F:/sourceCode/2022/compute-cms/bak/resourceDB
|
||||
category: resourceDB
|
||||
- #
|
||||
original: *backupDB
|
||||
dest: F:/sourceCode/2022/compute-cms/bak/backupDB
|
||||
category: backupDB
|
||||
- #
|
||||
original: *logDB
|
||||
dest: F:/sourceCode/2022/compute-cms/bak/logDB
|
||||
category: logDB
|
||||
# 数据库配置
|
||||
# 说明:改造前这里写死了开发机的绝对路径(E:\sourceCode\... / F:\sourceCode\...),
|
||||
# 换一台机器就必须手工修改。现在改为相对路径,也可以由部署环境覆盖。
|
||||
|
||||
db:
|
||||
db: &db ./db/db.json
|
||||
resourceDB: &resourceDB ./db/resourceDB.json
|
||||
backupDB: &backupDB ./db/backupDB.json
|
||||
logDB: &logDB ./db/logDB.json
|
||||
|
||||
# 数据库备份配置(可选)。dest 建议指向项目外或已挂载的备份盘。
|
||||
dbBak: []
|
||||
# - original: *db
|
||||
# dest: ./bak/db
|
||||
# category: db
|
||||
# - original: *resourceDB
|
||||
# dest: ./bak/resourceDB
|
||||
# category: resourceDB
|
||||
# - original: *backupDB
|
||||
# dest: ./bak/backupDB
|
||||
# category: backupDB
|
||||
# - original: *logDB
|
||||
# dest: ./bak/logDB
|
||||
# category: logDB
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"backupHistory": []
|
||||
}
|
||||
@@ -1,346 +0,0 @@
|
||||
{
|
||||
"backupHistory": [
|
||||
{
|
||||
"name": "db20220701112510.json",
|
||||
"category": "db",
|
||||
"id": "cl51w799y00003cny7rm01lx4",
|
||||
"createTime": "2022-07-01T03:25:10.198Z",
|
||||
"status": "1,2"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112510.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w79f900033cnyd44c044t",
|
||||
"createTime": "2022-07-01T03:25:10.389Z",
|
||||
"status": "1,2"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112510.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w79ia00063cny0hty82gs",
|
||||
"createTime": "2022-07-01T03:25:10.499Z",
|
||||
"status": "1,2"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112510.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w79lc00093cny9oiz4tlh",
|
||||
"createTime": "2022-07-01T03:25:10.608Z",
|
||||
"status": "1,2"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112520.json",
|
||||
"category": "db",
|
||||
"id": "cl51w7h1n000c3cnyhpfjbrpj",
|
||||
"createTime": "2022-07-01T03:25:20.267Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112520.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w7h4o000f3cnybldh5115",
|
||||
"createTime": "2022-07-01T03:25:20.376Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112520.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w7h7w000i3cnyafqk3p1o",
|
||||
"createTime": "2022-07-01T03:25:20.492Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112520.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w7haw000l3cny4nv48t44",
|
||||
"createTime": "2022-07-01T03:25:20.600Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112530.json",
|
||||
"category": "db",
|
||||
"id": "cl51w7oty000o3cny5v281zy3",
|
||||
"createTime": "2022-07-01T03:25:30.358Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112530.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w7owz000r3cnybuil0qm8",
|
||||
"createTime": "2022-07-01T03:25:30.467Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112530.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w7p0e000u3cnyg8r9by1q",
|
||||
"createTime": "2022-07-01T03:25:30.590Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112530.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w7p37000x3cny9be2eh4h",
|
||||
"createTime": "2022-07-01T03:25:30.691Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112540.json",
|
||||
"category": "db",
|
||||
"id": "cl51w7wlu00103cny65nw72bm",
|
||||
"createTime": "2022-07-01T03:25:40.434Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112540.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w7wom00133cnyg0nqc9w3",
|
||||
"createTime": "2022-07-01T03:25:40.534Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112540.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w7wrd00163cnydmnjcgw7",
|
||||
"createTime": "2022-07-01T03:25:40.633Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112540.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w7wuk00193cny8hwlcc89",
|
||||
"createTime": "2022-07-01T03:25:40.748Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112550.json",
|
||||
"category": "db",
|
||||
"id": "cl51w84dz001c3cnygo6oeal7",
|
||||
"createTime": "2022-07-01T03:25:50.519Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112550.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w84h0001f3cnyfahs5q4c",
|
||||
"createTime": "2022-07-01T03:25:50.628Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112550.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w84jm001i3cny2tpqcjjp",
|
||||
"createTime": "2022-07-01T03:25:50.722Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112550.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w84ml001l3cnygzl3hjod",
|
||||
"createTime": "2022-07-01T03:25:50.829Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112600.json",
|
||||
"category": "db",
|
||||
"id": "cl51w8c63001o3cnyfevk3kyp",
|
||||
"createTime": "2022-07-01T03:26:00.603Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112600.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w8c8m001r3cny9zryh2pe",
|
||||
"createTime": "2022-07-01T03:26:00.694Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112600.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w8cbo001u3cnya2bw2bsi",
|
||||
"createTime": "2022-07-01T03:26:00.804Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112600.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w8ce8001x3cny1cltcbdh",
|
||||
"createTime": "2022-07-01T03:26:00.896Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112610.json",
|
||||
"category": "db",
|
||||
"id": "cl51w8jxq00203cny392bhx57",
|
||||
"createTime": "2022-07-01T03:26:10.670Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112610.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w8k0n00233cny37f0cx5j",
|
||||
"createTime": "2022-07-01T03:26:10.775Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112610.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w8k3h00263cnydfiu8inf",
|
||||
"createTime": "2022-07-01T03:26:10.877Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112610.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w8k6n00293cny0j395r0p",
|
||||
"createTime": "2022-07-01T03:26:10.991Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220701112620.json",
|
||||
"category": "db",
|
||||
"id": "cl51w8rq0002c3cny2tih0ehp",
|
||||
"createTime": "2022-07-01T03:26:20.760Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220701112620.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl51w8rv2002f3cnyddcya1y9",
|
||||
"createTime": "2022-07-01T03:26:20.942Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220701112621.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl51w8rz2002i3cnyhsiihd6x",
|
||||
"createTime": "2022-07-01T03:26:21.086Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220701112621.json",
|
||||
"category": "logDB",
|
||||
"id": "cl51w8s5u002l3cny2o7m161c",
|
||||
"createTime": "2022-07-01T03:26:21.330Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "F:\\sourceCode\\2022\\compute-cms\\db20220703182610.json",
|
||||
"category": "db",
|
||||
"id": "cl5564dxd0000sonyakfraso1",
|
||||
"createTime": "2022-07-03T10:26:10.945Z"
|
||||
},
|
||||
{
|
||||
"name": "db20220703182700.json",
|
||||
"category": "db",
|
||||
"id": "cl5565fxt0000s0ny94tvajvl",
|
||||
"createTime": "2022-07-03T10:27:00.209Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220703182700.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl5565g3o0003s0nyhl4m51nu",
|
||||
"createTime": "2022-07-03T10:27:00.420Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220703182700.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl5565g7t0006s0ny2juo1ve3",
|
||||
"createTime": "2022-07-03T10:27:00.570Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220703182700.json",
|
||||
"category": "logDB",
|
||||
"id": "cl5565gas0009s0nyfyi71i0a",
|
||||
"createTime": "2022-07-03T10:27:00.676Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220703182710.json",
|
||||
"category": "db",
|
||||
"id": "cl5565npe000cs0ny4jmk13uj",
|
||||
"createTime": "2022-07-03T10:27:10.274Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220703182710.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl5565num000fs0nyfuynhsvn",
|
||||
"createTime": "2022-07-03T10:27:10.462Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220703182710.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl5565nxt000is0nyfaw54i99",
|
||||
"createTime": "2022-07-03T10:27:10.578Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220703182710.json",
|
||||
"category": "logDB",
|
||||
"id": "cl5565o0q000ls0ny49na7htm",
|
||||
"createTime": "2022-07-03T10:27:10.682Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220703182720.json",
|
||||
"category": "db",
|
||||
"id": "cl5565vh5000os0ny8q5l2dhe",
|
||||
"createTime": "2022-07-03T10:27:20.346Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220703182720.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl5565vlh000rs0ny6nvm1t28",
|
||||
"createTime": "2022-07-03T10:27:20.501Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220703182720.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl5565vpg000us0nyhchjafdx",
|
||||
"createTime": "2022-07-03T10:27:20.644Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220703182720.json",
|
||||
"category": "logDB",
|
||||
"id": "cl5565vs9000xs0nybt568rnh",
|
||||
"createTime": "2022-07-03T10:27:20.745Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "db20220703182730.json",
|
||||
"category": "db",
|
||||
"id": "cl556638l0010s0ny42h7beca",
|
||||
"createTime": "2022-07-03T10:27:30.405Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "resourceDB20220703182730.json",
|
||||
"category": "resourceDB",
|
||||
"id": "cl55663c00013s0nyefkb8ozn",
|
||||
"createTime": "2022-07-03T10:27:30.528Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "backupDB20220703182730.json",
|
||||
"category": "backupDB",
|
||||
"id": "cl55663f50016s0nyhmal0v7o",
|
||||
"createTime": "2022-07-03T10:27:30.641Z",
|
||||
"status": "1"
|
||||
},
|
||||
{
|
||||
"name": "logDB20220703182730.json",
|
||||
"category": "logDB",
|
||||
"id": "cl55663i50019s0nydmqjhwqr",
|
||||
"createTime": "2022-07-03T10:27:30.749Z",
|
||||
"status": "1"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"employee": [],
|
||||
"travelInformation": [],
|
||||
"Notice": [],
|
||||
"leaseRecords": [],
|
||||
"configurationList": [],
|
||||
"subOrder": [],
|
||||
"qa": [],
|
||||
"tag": [],
|
||||
"record": [],
|
||||
"dataDict": [],
|
||||
"recordUser": [],
|
||||
"plugin": []
|
||||
}
|
||||
-21146
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"dataLog": []
|
||||
}
|
||||
-72195
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"img": []
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
{
|
||||
"img": [
|
||||
{
|
||||
"id": "cl4u5pghi0001wgny53o32aq4",
|
||||
"filename": "cl4u5pgh40000wgnya0lp59uc.jpg",
|
||||
"path": "static\\cl4u5pgh40000wgnya0lp59uc.jpg",
|
||||
"createTime": "2022-06-25T17:29:06.486Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u68rlb0001qcnygmv39izm",
|
||||
"filename": "cl4u68rl60000qcny6npk19d3.jpg",
|
||||
"path": "static\\cl4u68rl60000qcny6npk19d3.jpg",
|
||||
"createTime": "2022-06-25T17:44:07.343Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u692vx0003qcnyaiip9dnn",
|
||||
"filename": "cl4u692vq0002qcny9bmj3q30.jpg",
|
||||
"path": "static\\cl4u692vq0002qcny9bmj3q30.jpg",
|
||||
"createTime": "2022-06-25T17:44:21.981Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u6agif0005qcny0kd1659n",
|
||||
"filename": "cl4u6agib0004qcnyexnb9xzz.jpg",
|
||||
"path": "static\\cl4u6agib0004qcnyexnb9xzz.jpg",
|
||||
"createTime": "2022-06-25T17:45:26.295Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u6ls550001ucnyhy6ghpwy",
|
||||
"filename": "cl4u6ls4r0000ucny86k414pr.jpg",
|
||||
"path": "static\\cl4u6ls4r0000ucny86k414pr.jpg",
|
||||
"createTime": "2022-06-25T17:54:14.585Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u6mmog0003ucnyato6b8qd",
|
||||
"filename": "cl4u6mmoc0002ucny0eaa8t7f.jpg",
|
||||
"path": "static\\cl4u6mmoc0002ucny0eaa8t7f.jpg",
|
||||
"createTime": "2022-06-25T17:54:54.160Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u7huus0001x4nyalm386vp",
|
||||
"filename": "cl4u7huui0000x4ny1rd095z4.jpg",
|
||||
"path": "static\\cl4u7huui0000x4ny1rd095z4.jpg",
|
||||
"createTime": "2022-06-25T18:19:11.092Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4u7jyqy0003x4nyaa2mhk1a",
|
||||
"filename": "cl4u7jyqv0002x4ny27cb0zyt.jpg",
|
||||
"path": "static\\cl4u7jyqv0002x4ny27cb0zyt.jpg",
|
||||
"createTime": "2022-06-25T18:20:49.450Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4uycgv80005x4nycnn4ahui",
|
||||
"filename": "cl4uycgv30004x4ny4k9a0987.jpg",
|
||||
"path": "static\\cl4uycgv30004x4ny4k9a0987.jpg",
|
||||
"createTime": "2022-06-26T06:50:49.316Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0kl5h000rx4nydmi0gnhl",
|
||||
"filename": "cl4v0kl59000qx4ny0xsx9j2n.jpg",
|
||||
"path": "static\\cl4v0kl59000qx4ny0xsx9j2n.jpg",
|
||||
"createTime": "2022-06-26T07:53:07.349Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0lgm3000tx4ny7i4xdeq4",
|
||||
"filename": "cl4v0lglz000sx4ny17in7q6a.jpg",
|
||||
"path": "static\\cl4v0lglz000sx4ny17in7q6a.jpg",
|
||||
"createTime": "2022-06-26T07:53:48.123Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0m2wm000vx4nye3kl2794",
|
||||
"filename": "cl4v0m2wi000ux4nyhb7xaykl.jpg",
|
||||
"path": "static\\cl4v0m2wi000ux4nyhb7xaykl.jpg",
|
||||
"createTime": "2022-06-26T07:54:17.014Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0mdjv000xx4nycqqngyjr",
|
||||
"filename": "cl4v0mdjl000wx4ny6d4acii7.jpg",
|
||||
"path": "static\\cl4v0mdjl000wx4ny6d4acii7.jpg",
|
||||
"createTime": "2022-06-26T07:54:30.811Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0mzlq000zx4ny37649xm3",
|
||||
"filename": "cl4v0mzlm000yx4nyhjcwdmwb.jpg",
|
||||
"path": "static\\cl4v0mzlm000yx4nyhjcwdmwb.jpg",
|
||||
"createTime": "2022-06-26T07:54:59.390Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0nf8t0011x4ny3vgb0njg",
|
||||
"filename": "cl4v0nf8p0010x4ny1q8o96bb.jpg",
|
||||
"path": "static\\cl4v0nf8p0010x4ny1q8o96bb.jpg",
|
||||
"createTime": "2022-06-26T07:55:19.661Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0q7mv0013x4nybkoy3z9b",
|
||||
"filename": "cl4v0q7ms0012x4ny29i1hy0d.jpg",
|
||||
"path": "static\\cl4v0q7ms0012x4ny29i1hy0d.jpg",
|
||||
"createTime": "2022-06-26T07:57:29.767Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0qaxk0015x4nyc61xhnsk",
|
||||
"filename": "cl4v0qaxi0014x4nyd02n1y0s.jpg",
|
||||
"path": "static\\cl4v0qaxi0014x4nyd02n1y0s.jpg",
|
||||
"createTime": "2022-06-26T07:57:34.040Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0qrtf0017x4ny1y0t0wam",
|
||||
"filename": "cl4v0qrtc0016x4ny1bxh12e8.jpg",
|
||||
"path": "static\\cl4v0qrtc0016x4ny1bxh12e8.jpg",
|
||||
"createTime": "2022-06-26T07:57:55.923Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0s7m10019x4ny5zta50b4",
|
||||
"filename": "cl4v0s7lv0018x4nybu4u9qrp.jpg",
|
||||
"path": "static\\cl4v0s7lv0018x4nybu4u9qrp.jpg",
|
||||
"createTime": "2022-06-26T07:59:03.049Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v0uvxk001bx4ny2qe0c22r",
|
||||
"filename": "cl4v0uvxi001ax4ny0itgd8j9.jpg",
|
||||
"path": "static\\cl4v0uvxi001ax4ny0itgd8j9.jpg",
|
||||
"createTime": "2022-06-26T08:01:07.880Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v18kp9001dx4nya6yhb8yy",
|
||||
"filename": "cl4v18kp6001cx4nyg3xoh7kn.jpg",
|
||||
"path": "static\\cl4v18kp6001cx4nyg3xoh7kn.jpg",
|
||||
"createTime": "2022-06-26T08:11:46.509Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v18mxi001fx4nyc6h2fozb",
|
||||
"filename": "cl4v18mxe001ex4ny8147ehkt.jpg",
|
||||
"path": "static\\cl4v18mxe001ex4ny8147ehkt.jpg",
|
||||
"createTime": "2022-06-26T08:11:49.398Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4v18pi9001hx4ny7idea4m5",
|
||||
"filename": "cl4v18pi3001gx4nyazt40dus.jpg",
|
||||
"path": "static\\cl4v18pi3001gx4nyazt40dus.jpg",
|
||||
"createTime": "2022-06-26T08:11:52.737Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4wq1ywm0001a0ny38cmcwa2",
|
||||
"filename": "cl4wq1ywc0000a0ny2y25e0fa.jpg",
|
||||
"path": "static\\cl4wq1ywc0000a0ny2y25e0fa.jpg",
|
||||
"createTime": "2022-06-27T12:34:14.902Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4wq21w30003a0ny9xpd62rv",
|
||||
"filename": "cl4wq21vu0002a0ny07359nx6.jpg",
|
||||
"path": "static\\cl4wq21vu0002a0ny07359nx6.jpg",
|
||||
"createTime": "2022-06-27T12:34:18.771Z"
|
||||
},
|
||||
{
|
||||
"id": "cl4wq28rv0005a0nycf7k2a34",
|
||||
"filename": "cl4wq28rt0004a0ny5nj4gbe2.jpg",
|
||||
"path": "static\\cl4wq28rt0004a0ny5nj4gbe2.jpg",
|
||||
"createTime": "2022-06-27T12:34:27.691Z"
|
||||
},
|
||||
{
|
||||
"id": "cl550ghgz0009lsnycaace5r1",
|
||||
"filename": "cl550ghgt0008lsnyc7jl7rhw.jpg",
|
||||
"path": "static\\cl550ghgt0008lsnyc7jl7rhw.jpg",
|
||||
"createTime": "2022-07-03T07:47:37.715Z"
|
||||
},
|
||||
{
|
||||
"id": "cl550gk3n000blsnybbxz3rru",
|
||||
"filename": "cl550gk3e000alsnyafhcc8b2.jpg",
|
||||
"path": "static\\cl550gk3e000alsnyafhcc8b2.jpg",
|
||||
"createTime": "2022-07-03T07:47:41.123Z"
|
||||
},
|
||||
{
|
||||
"id": "cl550gmhr000dlsny9oxxex2y",
|
||||
"filename": "cl550gmhf000clsny2c4h5a33.jpg",
|
||||
"path": "static\\cl550gmhf000clsny2c4h5a33.jpg",
|
||||
"createTime": "2022-07-03T07:47:44.223Z"
|
||||
},
|
||||
{
|
||||
"id": "clzwtwwmp00029grb63lr3hcq",
|
||||
"filename": "clzwtwwml00019grbfbsf6r72.viminfo",
|
||||
"path": "static\\clzwtwwml00019grbfbsf6r72.viminfo",
|
||||
"createTime": "2024-08-16T14:53:09.553Z"
|
||||
},
|
||||
{
|
||||
"id": "clzwuyxln00049grb4ng91xik",
|
||||
"filename": "clzwuyxlf00039grb80upct14.yarnrc",
|
||||
"path": "static\\clzwuyxlf00039grb80upct14.yarnrc",
|
||||
"createTime": "2024-08-16T15:22:43.739Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
+33
-32
@@ -1,32 +1,33 @@
|
||||
{
|
||||
"name": "server",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@koa/multer": "^3.0.0",
|
||||
"@types/yaml": "^1.9.7",
|
||||
"cuid": "^2.1.8",
|
||||
"dayjs": "^1.11.3",
|
||||
"koa": "^2.13.4",
|
||||
"koa-body": "^4.2.0",
|
||||
"koa-mount": "^4.0.0",
|
||||
"koa-router": "^10.1.1",
|
||||
"koa-static": "^5.0.0",
|
||||
"lodash": "^4.17.21",
|
||||
"lowdb": "^3.0.0",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"node-cron": "^3.0.1",
|
||||
"uuid": "^8.3.2",
|
||||
"yaml": "^2.1.1",
|
||||
"funjia-server":"git+http://git.funjia.top/funjia/funjia-server.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^6.0.7"
|
||||
}
|
||||
}
|
||||
{
|
||||
"name": "server",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"smoke": "node smoke-test.mjs",
|
||||
"test": "node smoke-test.mjs"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@koa/multer": "^3.0.0",
|
||||
"@types/yaml": "^1.9.7",
|
||||
"cuid": "^2.1.8",
|
||||
"dayjs": "^1.11.3",
|
||||
"koa": "^2.13.4",
|
||||
"koa-body": "^4.2.0",
|
||||
"koa-mount": "^4.0.0",
|
||||
"koa-router": "^10.1.1",
|
||||
"koa-static": "^5.0.0",
|
||||
"lodash": "^4.17.21",
|
||||
"lowdb": "^3.0.0",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"node-cron": "^3.0.1",
|
||||
"uuid": "^8.3.2",
|
||||
"yaml": "^2.1.1",
|
||||
"funjia-server":"git+http://git.funjia.top/funjia/funjia-server.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^6.0.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
// import RouterFactor from "../RouterFactory.mjs";
|
||||
// import DBHelper from "../DBHelper.mjs";
|
||||
import {RouterFactor,DBHelper} from "funjia-server/lib/funjia-server.mjs";
|
||||
|
||||
const getDataLog = (router) => {
|
||||
const rF = new RouterFactor({
|
||||
router,
|
||||
db: DBHelper.logDB,
|
||||
name: "dataLog"
|
||||
});
|
||||
|
||||
rF.creaetBaseRouter();
|
||||
}
|
||||
|
||||
import {RouterFactor,DBHelper} from "funjia-server/lib/funjia-server.mjs";
|
||||
|
||||
const getDataLog = (router) => {
|
||||
const rF = new RouterFactor({
|
||||
router,
|
||||
db: DBHelper.logDB,
|
||||
name: "dataLog"
|
||||
});
|
||||
|
||||
rF.creaetBaseRouter();
|
||||
}
|
||||
|
||||
export default getDataLog;
|
||||
+126
-173
@@ -1,173 +1,126 @@
|
||||
import cuid from "cuid";
|
||||
// import getDb from "../dbServer.mjs";
|
||||
import _ from "lodash";
|
||||
|
||||
import { getDb } from "funjia-server/lib/funjia-server.mjs";
|
||||
const getEmployee = (router) => {
|
||||
|
||||
router.post('/api/employee/list', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const body = ctx.request.body;
|
||||
const data = db.data?.employee?.filter((item) => {
|
||||
let isMatch = true;
|
||||
for (let field in body) {
|
||||
if (["page", "pageSize"].includes(field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof (item[field]) == "string") {
|
||||
isMatch = item[field]?.indexOf?.(body[field]) > -1;
|
||||
} else if (typeof (item[field]) == "number") {
|
||||
isMatch = item[field] == body[field];
|
||||
}
|
||||
if (!isMatch)
|
||||
break;
|
||||
}
|
||||
return isMatch;
|
||||
});
|
||||
|
||||
const {
|
||||
page,
|
||||
pageSize
|
||||
} = body;
|
||||
let batchData = data;
|
||||
if (page && pageSize) {
|
||||
batchData = data.slice((page - 1) * pageSize, page * pageSize);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: batchData || [],
|
||||
total: data.length
|
||||
};
|
||||
});
|
||||
|
||||
router.get('/api/employee', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const data = db.data.employee;
|
||||
const query = ctx.request.query;
|
||||
console.log("参数:", query, ctx.request.body, ctx.query);
|
||||
let detail = {};
|
||||
if (query.id && data) {
|
||||
detail = data.find((item) => {
|
||||
return item.id == query.id;
|
||||
});
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: detail || {}
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/employee/add', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data?.employee)
|
||||
db.data.employee = [];
|
||||
const {
|
||||
employee
|
||||
} = db.data;
|
||||
const data = ctx.request.body;
|
||||
console.log("add:", data);
|
||||
data.id = cuid();
|
||||
data.createTime = new Date();
|
||||
employee.push(data)
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/employee/upd', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data?.employee)
|
||||
db.data = {
|
||||
employee: []
|
||||
}
|
||||
const {
|
||||
employee
|
||||
} = db.data;
|
||||
const data = ctx.request.body;
|
||||
const id = data.id;
|
||||
console.log("数据Id:", id);
|
||||
if (id && employee) {
|
||||
const currentDetail = employee.find(item => item.id == id);
|
||||
if (currentDetail) {
|
||||
_.merge(currentDetail, data);
|
||||
}
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/employee/delete', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data?.employee)
|
||||
db.data = {
|
||||
employee: []
|
||||
}
|
||||
let {
|
||||
employee
|
||||
} = db.data;
|
||||
const data = ctx.request.body;
|
||||
const ids = data.ids;
|
||||
if (ids?.length > 0 && employee) {
|
||||
let id = null;
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
id = ids[i];
|
||||
const idx = employee.findIndex(item => item.id == id);
|
||||
if (idx != -1) {
|
||||
employee.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/employee/login', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const data = db.data.employee;
|
||||
const params = ctx.request.body;
|
||||
let detail = {};
|
||||
if (data) {
|
||||
detail = data.find((item) => {
|
||||
return item.userName == params.userName && item.pwd == params.pwd;
|
||||
});
|
||||
}
|
||||
|
||||
const code = detail ? 0 : 1;
|
||||
|
||||
ctx.body = {
|
||||
code,
|
||||
data: detail || {}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export default getEmployee;
|
||||
import cuid from "cuid";
|
||||
import _ from "lodash";
|
||||
import { getDb } from "funjia-server/lib/funjia-server.mjs";
|
||||
import { getTable, pickFilters, matchRow, listResponse, omitSensitive } from "../helpers.mjs";
|
||||
|
||||
/**
|
||||
* 员工(登录账号)路由。
|
||||
*
|
||||
* ## 改造前的缺陷
|
||||
*
|
||||
* 1. **列表接口在员工表为空时抛错**
|
||||
* `db.data?.employee?.filter(...)` → `undefined`,随后 `data.length` 直接 500。
|
||||
*
|
||||
* 2. **明文密码出接口**
|
||||
* `/api/employee/list` 与 `/api/employee/login` 都返回完整记录,`pwd` 字段
|
||||
* (示例库里就是 `123456`)明文透出到浏览器。改为统一剔除。
|
||||
*
|
||||
* 3. **`console.log` 打印登录参数**
|
||||
* 原来会把 `ctx.request.body`(含用户名、密码)原样写进日志。
|
||||
*
|
||||
* 4. **`upd` 允许请求体覆盖主键 id**,`delete` 用逐条 splice(ids 中的无效 id
|
||||
* 被静默忽略,且返回值不体现实际删除条数)。
|
||||
*
|
||||
* 5. **登录失败不区分原因**这件事要保持——反过来也不该把「用户不存在」和
|
||||
* 「密码错误」区分开,避免账号枚举。
|
||||
*/
|
||||
const getEmployee = (router) => {
|
||||
const tableName = "employee";
|
||||
|
||||
router.post("/api/employee/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)));
|
||||
|
||||
ctx.body = {
|
||||
...listResponse(data, body),
|
||||
data: listResponse(data, body).data.map((row) => omitSensitive(row)),
|
||||
};
|
||||
});
|
||||
|
||||
router.get("/api/employee", 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 ? omitSensitive(detail) : {} };
|
||||
});
|
||||
|
||||
router.post("/api/employee/add", async (ctx) => {
|
||||
ctx.type = "application/json";
|
||||
const { db, table } = await getTable(getDb, tableName);
|
||||
const data = ctx.request.body || {};
|
||||
|
||||
if (table.some((item) => item.userName === data.userName)) {
|
||||
ctx.body = { code: 1, msg: "用户名已存在" };
|
||||
return;
|
||||
}
|
||||
|
||||
const { id, createTime, ...rest } = data;
|
||||
void id;
|
||||
void createTime;
|
||||
table.push({ ...rest, id: cuid(), createTime: new Date() });
|
||||
await db.write();
|
||||
|
||||
ctx.body = { code: 0 };
|
||||
});
|
||||
|
||||
router.post("/api/employee/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/employee/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 } };
|
||||
});
|
||||
|
||||
router.post("/api/employee/login", async (ctx) => {
|
||||
ctx.type = "application/json";
|
||||
const { table } = await getTable(getDb, tableName);
|
||||
const { userName, pwd } = ctx.request.body || {};
|
||||
|
||||
const detail = table.find((item) => item.userName === userName && item.pwd === pwd);
|
||||
|
||||
if (!detail) {
|
||||
// 不区分「用户不存在」与「密码错误」,避免账号枚举
|
||||
ctx.body = { code: 1, msg: "用户名或密码错误" };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, data: omitSensitive(detail) };
|
||||
});
|
||||
};
|
||||
|
||||
export default getEmployee;
|
||||
|
||||
+92
-154
@@ -1,154 +1,92 @@
|
||||
import cuid from "cuid";
|
||||
// import getDb from "../dbServer.mjs";
|
||||
import {getDb} from "funjia-server/lib/funjia-server.mjs";
|
||||
import _ from "lodash";
|
||||
|
||||
const getNotice = (router) => {
|
||||
|
||||
router.post('/api/Notice/list', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const body = ctx.request.body;
|
||||
const data = db.data?.Notice?.filter((item) => {
|
||||
let isMatch = true;
|
||||
for (let field in body) {
|
||||
if (["page", "pageSize"].includes(field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof (item[field]) == "string") {
|
||||
isMatch = item[field]?.indexOf?.(body[field]) > -1;
|
||||
} else if (typeof (item[field]) == "number") {
|
||||
isMatch = item[field] == body[field];
|
||||
}
|
||||
if (!isMatch)
|
||||
break;
|
||||
}
|
||||
return isMatch;
|
||||
});
|
||||
|
||||
const {
|
||||
page,
|
||||
pageSize
|
||||
} = body;
|
||||
let batchData = data;
|
||||
if (page && pageSize) {
|
||||
batchData = data.slice((page - 1) * pageSize, page * pageSize);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: batchData.sort((a, b) => {
|
||||
return a.sort - b.sort;
|
||||
}) || [],
|
||||
total: data.length
|
||||
};
|
||||
});
|
||||
|
||||
router.get('/api/Notice', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const data = db.data.Notice;
|
||||
const query = ctx.request.query;
|
||||
console.log("参数:", query, ctx.request.body, ctx.query);
|
||||
let detail = {};
|
||||
if (query.id && data) {
|
||||
detail = data.find((item) => {
|
||||
return item.id == query.id;
|
||||
});
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: detail || {}
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/Notice/add', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data?.Notice)
|
||||
db.data.Notice = [];
|
||||
const {
|
||||
Notice
|
||||
} = db.data;
|
||||
const data = ctx.request.body;
|
||||
console.log("add:", data);
|
||||
data.id = cuid();
|
||||
data.createTime = new Date();
|
||||
Notice.push(data)
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/Notice/upd', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data?.Notice)
|
||||
db.data = {
|
||||
Notice: []
|
||||
}
|
||||
const {
|
||||
Notice
|
||||
} = db.data;
|
||||
const data = ctx.request.body;
|
||||
const id = data.id;
|
||||
console.log("数据Id:", id);
|
||||
if (id && Notice) {
|
||||
const currentDetail = Notice.find(item => item.id == id);
|
||||
if (currentDetail) {
|
||||
_.merge(currentDetail, data);
|
||||
}
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/Notice/delete', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data?.Notice)
|
||||
db.data = {
|
||||
Notice: []
|
||||
}
|
||||
let {
|
||||
Notice
|
||||
} = db.data;
|
||||
const data = ctx.request.body;
|
||||
const ids = data.ids;
|
||||
if (ids?.length > 0 && Notice) {
|
||||
let id = null;
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
id = ids[i];
|
||||
const idx = Notice.findIndex(item => item.id == id);
|
||||
if (idx != -1) {
|
||||
Notice.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export default getNotice;
|
||||
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;
|
||||
|
||||
+13
-15
@@ -1,16 +1,14 @@
|
||||
// import RouterFactor from "../RouterFactory.mjs";
|
||||
// import DBHelper from "../DBHelper.mjs";
|
||||
import {RouterFactor,DBHelper} from "funjia-server/lib/funjia-server.mjs";
|
||||
|
||||
|
||||
const getQA = (router) => {
|
||||
const rF = new RouterFactor({
|
||||
router,
|
||||
db: DBHelper.baseDB,
|
||||
name: "qa"
|
||||
});
|
||||
|
||||
rF.creaetBaseRouter();
|
||||
}
|
||||
|
||||
import {RouterFactor,DBHelper} from "funjia-server/lib/funjia-server.mjs";
|
||||
|
||||
|
||||
const getQA = (router) => {
|
||||
const rF = new RouterFactor({
|
||||
router,
|
||||
db: DBHelper.baseDB,
|
||||
name: "qa"
|
||||
});
|
||||
|
||||
rF.creaetBaseRouter();
|
||||
}
|
||||
|
||||
export default getQA;
|
||||
@@ -1,108 +1,24 @@
|
||||
import _ from "lodash";
|
||||
// import RouterFactor from "../RouterFactory.mjs";
|
||||
// import DBHelper from "../DBHelper.mjs";
|
||||
import {RouterFactor,DBHelper} from "funjia-server/lib/funjia-server.mjs";
|
||||
|
||||
const getBackupHistory = (router) => {
|
||||
const rF = new RouterFactor({
|
||||
router,
|
||||
db: DBHelper.backupDB,
|
||||
name: "backupHistory"
|
||||
});
|
||||
|
||||
rF.createGetList();
|
||||
|
||||
rF.createGetDetail();
|
||||
|
||||
rF.createAdd();
|
||||
|
||||
rF.createUpdate();
|
||||
|
||||
rF.createDelete();
|
||||
|
||||
// router.post('/api/backupHistory/add', async (ctx) => {
|
||||
// ctx.type = 'application/json';
|
||||
// const db = await getBackupDb();
|
||||
|
||||
// // You can also use this syntax if you prefer
|
||||
// if (!db.data.backupHistory)
|
||||
// db.data.backupHistory = [];
|
||||
// const {
|
||||
// backupHistory
|
||||
// } = db.data;
|
||||
// const data = ctx.request.body;
|
||||
// console.log("add:", data);
|
||||
// data.id = cuid();
|
||||
// data.createTime = new Date();
|
||||
// backupHistory.push(data)
|
||||
// // Write db.data content to db.json
|
||||
// await db.write()
|
||||
|
||||
// ctx.body = {
|
||||
// code: 0,
|
||||
// };
|
||||
// });
|
||||
|
||||
// router.post('/api/backupHistory/upd', async (ctx) => {
|
||||
// ctx.type = 'application/json';
|
||||
// const db = await getBackupDb();
|
||||
|
||||
// // You can also use this syntax if you prefer
|
||||
// if (!db.data.backupHistory)
|
||||
// db.data = {
|
||||
// backupHistory: []
|
||||
// }
|
||||
// const {
|
||||
// backupHistory
|
||||
// } = db.data;
|
||||
// const data = ctx.request.body;
|
||||
// const id = data.id;
|
||||
// console.log("数据Id:", id);
|
||||
// if (id && backupHistory) {
|
||||
// const currentDetail = backupHistory.find(item => item.id == id);
|
||||
// if (currentDetail) {
|
||||
// _.merge(currentDetail, data);
|
||||
// }
|
||||
// // Write db.data content to db.json
|
||||
// await db.write()
|
||||
// }
|
||||
|
||||
// ctx.body = {
|
||||
// code: 0,
|
||||
// };
|
||||
// });
|
||||
|
||||
// router.post('/api/backupHistory/delete', async (ctx) => {
|
||||
// ctx.type = 'application/json';
|
||||
// const db = await getBackupDb();
|
||||
|
||||
// // You can also use this syntax if you prefer
|
||||
// if (!db.data.backupHistory)
|
||||
// db.data = {
|
||||
// backupHistory: []
|
||||
// }
|
||||
// let {
|
||||
// backupHistory
|
||||
// } = db.data;
|
||||
// const data = ctx.request.body;
|
||||
// const ids = data.ids;
|
||||
// if (ids.length > 0 && backupHistory) {
|
||||
// let id = null;
|
||||
// for (let i = 0; i < ids.length; i++) {
|
||||
// id = ids[i];
|
||||
// const idx = backupHistory.findIndex(item => item.id == id);
|
||||
// if (idx != -1) {
|
||||
// backupHistory.splice(idx, 1);
|
||||
// }
|
||||
// }
|
||||
// // Write db.data content to db.json
|
||||
// await db.write()
|
||||
// }
|
||||
|
||||
// ctx.body = {
|
||||
// code: 0,
|
||||
// };
|
||||
// });
|
||||
}
|
||||
|
||||
export default getBackupHistory;
|
||||
import { RouterFactor, DBHelper } from "funjia-server/lib/funjia-server.mjs";
|
||||
|
||||
/**
|
||||
* 备份历史路由。
|
||||
*
|
||||
* 改造前文件里有 80 余行被注释掉的旧实现——那正是 `dynamic.mjs` 里
|
||||
* 「表缺失时整体替换 db.data」缺陷的原始版本(`db.data = { backupHistory: [] }`)。
|
||||
* 已改用 `funjia-server` 的 `RouterFactor` 后,这些注释只留下误导作用,故删除。
|
||||
*/
|
||||
const getBackupHistory = (router) => {
|
||||
const rF = new RouterFactor({
|
||||
router,
|
||||
db: DBHelper.backupDB,
|
||||
name: "backupHistory",
|
||||
});
|
||||
|
||||
rF.createGetList();
|
||||
rF.createGetDetail();
|
||||
rF.createAdd();
|
||||
rF.createUpdate();
|
||||
rF.createDelete();
|
||||
};
|
||||
|
||||
export default getBackupHistory;
|
||||
|
||||
+108
-157
@@ -1,157 +1,108 @@
|
||||
import cuid from "cuid";
|
||||
// import getDb from "../dbServer.mjs";
|
||||
import {getDb} from "funjia-server/lib/funjia-server.mjs";
|
||||
import _ from "lodash";
|
||||
|
||||
const getDynamic = (router) => {
|
||||
|
||||
router.post('/api/dynamic/list/:tableName', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const body = ctx.request.body;
|
||||
const data = db.data[ctx.params.tableName]?.filter((item) => {
|
||||
let isMatch = true;
|
||||
for (let field in body) {
|
||||
if (["page", "pageSize"].includes(field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof (item[field]) == "string") {
|
||||
isMatch = item[field]?.indexOf?.(body[field]) > -1;
|
||||
} else if (typeof (item[field]) == "number") {
|
||||
isMatch = item[field] == body[field];
|
||||
}
|
||||
if (!isMatch)
|
||||
break;
|
||||
}
|
||||
return isMatch;
|
||||
});
|
||||
|
||||
const {
|
||||
page,
|
||||
pageSize
|
||||
} = body;
|
||||
let batchData = data;
|
||||
if (page && pageSize) {
|
||||
batchData = data.slice((page - 1) * pageSize, page * pageSize);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: batchData || [],
|
||||
total: data.length
|
||||
};
|
||||
});
|
||||
|
||||
router.get('/api/dynamic/:tableName', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const data = db.data[ctx.params.tableName];
|
||||
const query = ctx.request.query;
|
||||
console.log("参数:", query, ctx.request.body, ctx.query);
|
||||
let detail = {};
|
||||
if (query.id && data) {
|
||||
detail = data.find((item) => {
|
||||
return item.id == query.id;
|
||||
});
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: detail || {}
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/dynamic/add/:tableName', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const tableName=ctx.params.tableName;
|
||||
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data[tableName])
|
||||
db.data[tableName] = [];
|
||||
|
||||
const dynamic = db.data[tableName];
|
||||
const data = ctx.request.body;
|
||||
console.log("add:", data);
|
||||
data.id = cuid();
|
||||
data.createTime = new Date();
|
||||
dynamic.push(data)
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/dynamic/upd/:tableName', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const tableName=ctx.params.tableName;
|
||||
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data[tableName])
|
||||
db.data = {
|
||||
dynamic: []
|
||||
}
|
||||
|
||||
const dynamic = db.data[tableName];
|
||||
|
||||
const data = ctx.request.body;
|
||||
const id = data.id;
|
||||
console.log("数据Id:", id);
|
||||
if (id && dynamic) {
|
||||
const currentDetail = dynamic.find(item => item.id == id);
|
||||
if (currentDetail) {
|
||||
_.merge(currentDetail, data);
|
||||
}
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/api/dynamic/delete/:tableName', async (ctx) => {
|
||||
ctx.type = 'application/json';
|
||||
const tableName=ctx.params.tableName;
|
||||
|
||||
const db = await getDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data[tableName])
|
||||
db.data = {
|
||||
[tableName]: []
|
||||
}
|
||||
|
||||
const dynamic = db.data[tableName];
|
||||
|
||||
const data = ctx.request.body;
|
||||
const ids = data.ids;
|
||||
if (ids?.length > 0 && dynamic) {
|
||||
let id = null;
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
id = ids[i];
|
||||
const idx = dynamic.findIndex(item => item.id == id);
|
||||
if (idx != -1) {
|
||||
dynamic.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export default getDynamic;
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 路由层公共工具。
|
||||
*
|
||||
* 改造前 `dynamic.mjs` / `employee.mjs` / `notice.mjs` / `upload.mjs` 四个文件里
|
||||
* 各抄了一份「过滤 + 分页」的实现,逻辑还不完全一致(`notice` 少了空值保护、
|
||||
* `upload` 少了可选链),这里统一收口。
|
||||
*/
|
||||
|
||||
/** 从数据库取表并保证它是数组 */
|
||||
export const getTable = async (getDb, tableName) => {
|
||||
const db = await getDb();
|
||||
if (!Array.isArray(db.data[tableName])) {
|
||||
db.data[tableName] = [];
|
||||
}
|
||||
return { db, table: db.data[tableName] };
|
||||
};
|
||||
|
||||
/** 剔除分页参数后的业务查询条件 */
|
||||
export const pickFilters = (body = {}, excludes = ["page", "pageSize"]) =>
|
||||
Object.fromEntries(Object.entries(body).filter(([key]) => !excludes.includes(key)));
|
||||
|
||||
/** 内存过滤:字符串模糊匹配,其余精确匹配;空值不参与过滤 */
|
||||
export const matchRow = (row, filters) =>
|
||||
Object.entries(filters).every(([field, value]) => {
|
||||
if (value === undefined || value === null || value === "") return true;
|
||||
if (typeof row[field] === "string") return row[field].includes(String(value));
|
||||
return row[field] == value;
|
||||
});
|
||||
|
||||
/** 分页切片 */
|
||||
export const paginate = (list, page, pageSize) => {
|
||||
if (!page || !pageSize) return list;
|
||||
return list.slice((page - 1) * pageSize, page * pageSize);
|
||||
};
|
||||
|
||||
/** 统一的列表响应 */
|
||||
export const listResponse = (list, body = {}) => ({
|
||||
code: 0,
|
||||
data: paginate(list, body.page, body.pageSize),
|
||||
total: list.length,
|
||||
});
|
||||
|
||||
/**
|
||||
* 剔除敏感字段。
|
||||
* 改造前 `/api/employee/list` 与 `/api/employee/login` 会把 `pwd` 明文返回给前端。
|
||||
*/
|
||||
export const omitSensitive = (row, fields = ["pwd"]) => {
|
||||
if (!row || typeof row !== "object") return row;
|
||||
return Object.fromEntries(Object.entries(row).filter(([key]) => !fields.includes(key)));
|
||||
};
|
||||
+132
-167
@@ -1,167 +1,132 @@
|
||||
import cuid from "cuid";
|
||||
// import getDb, {
|
||||
// getResourceDb
|
||||
// } from "../dbServer.mjs";
|
||||
import {getDb,getResourceDb} from "funjia-server/lib/funjia-server.mjs";
|
||||
import _ from "lodash";
|
||||
import multer from '@koa/multer';
|
||||
|
||||
//配置
|
||||
var storage = multer.diskStorage({
|
||||
//文件保存路径
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, 'static') //注意路径必须存最后面在不用加斜杠
|
||||
},
|
||||
//修改文件名称
|
||||
filename: function (req, file, cb) {
|
||||
var fileFormat = (file.originalname).split(".");
|
||||
const filename = cuid() + "." + fileFormat[fileFormat.length - 1];
|
||||
req.filename = filename;
|
||||
cb(null, filename);
|
||||
}
|
||||
})
|
||||
|
||||
//加载配置
|
||||
var upload = multer({
|
||||
storage: storage
|
||||
})
|
||||
|
||||
// const upload = multer({ dest: 'static/' })
|
||||
|
||||
const getUpload = (router) => {
|
||||
router.post('/api/leaseRecords/list', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const body = ctx.request.body;
|
||||
const data = db.data.leaseRecords.filter((item) => {
|
||||
let isMatch = true;
|
||||
for (let field in body) {
|
||||
if (["page", "pageSize"].includes(field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof (item[field]) == "string") {
|
||||
isMatch = item[field].indexOf(body[field]) > -1;
|
||||
} else if (typeof (item[field]) == "number") {
|
||||
isMatch = item[field] == body[field];
|
||||
}
|
||||
if (!isMatch)
|
||||
break;
|
||||
}
|
||||
return isMatch;
|
||||
});
|
||||
|
||||
const {
|
||||
page,
|
||||
pageSize
|
||||
} = body;
|
||||
let batchData = data;
|
||||
if (page && pageSize) {
|
||||
batchData = data.slice((page - 1) * pageSize, page * pageSize);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: batchData.sort((a, b) => {
|
||||
return a.sort - b.sort;
|
||||
}) || [],
|
||||
total: data.length
|
||||
};
|
||||
});
|
||||
|
||||
router.get('/api/img', async (ctx) => {
|
||||
// 设置头类型, 如果不设置,会直接下载该页面
|
||||
ctx.type = 'application/json';
|
||||
const db = await getDb();
|
||||
const data = db.data.leaseRecords;
|
||||
const query = ctx.request.query;
|
||||
console.log("参数:", query, ctx.request.body, ctx.query);
|
||||
let detail = {};
|
||||
if (query.id && data) {
|
||||
detail = data.find((item) => {
|
||||
return item.id == query.id;
|
||||
});
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: detail || {}
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 添加图片记录
|
||||
* @param {*} path
|
||||
*/
|
||||
const addImg = async (filename, path) => {
|
||||
const data = {};
|
||||
try {
|
||||
const db = await getResourceDb();
|
||||
|
||||
// You can also use this syntax if you prefer
|
||||
if (!db.data.img)
|
||||
db.data.img = [];
|
||||
|
||||
const {
|
||||
img
|
||||
} = db.data;
|
||||
|
||||
data.id = cuid();
|
||||
data.filename = filename;
|
||||
data.path = path;
|
||||
data.createTime = new Date();
|
||||
img.push(data)
|
||||
// Write db.data content to db.json
|
||||
await db.write()
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return null;
|
||||
}
|
||||
return data.id;
|
||||
|
||||
}
|
||||
|
||||
// 添加单个文件上传的路由
|
||||
router.post(
|
||||
'/api/upload/img',
|
||||
upload.single('file'),
|
||||
async (ctx) => {
|
||||
const {
|
||||
filename,
|
||||
path
|
||||
} = ctx.file;
|
||||
const res = await addImg(filename, path);
|
||||
|
||||
ctx.body = {
|
||||
code: res ? 0 : 1,
|
||||
data: {
|
||||
id: res,
|
||||
url: path
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 添加单个文件上传的路由
|
||||
router.post(
|
||||
'/api/upload/file',
|
||||
upload.single('file'),
|
||||
async (ctx) => {
|
||||
const {
|
||||
filename,
|
||||
path
|
||||
} = ctx.file;
|
||||
// const res = await addImg(filename, path);
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: {
|
||||
url: "/resource/static/"+filename
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export default getUpload;
|
||||
import cuid from "cuid";
|
||||
import multer from "@koa/multer";
|
||||
import path from "path";
|
||||
import { getDb, getResourceDb } from "funjia-server/lib/funjia-server.mjs";
|
||||
import { getTable, pickFilters, matchRow, listResponse } from "./helpers.mjs";
|
||||
|
||||
/**
|
||||
* 上传相关路由。
|
||||
*
|
||||
* ## 改造前的缺陷
|
||||
*
|
||||
* 1. **上传没有任何文件类型/大小限制**,并且用 `originalname` 的扩展名
|
||||
* 直接拼出落盘文件名——上传 `shell.php` 或超长扩展名都会被原样接受;
|
||||
* 文件目录还是相对路径 `static`,取决于进程工作目录。
|
||||
*
|
||||
* 2. **文件名扩展名取自用户输入且未做净化**,存在路径穿越 / 双扩展名风险。
|
||||
*
|
||||
* 3. **`/api/leaseRecords/list` 与 `/api/img` 是上一代业务(租赁记录)的残留**,
|
||||
* 其中 `db.data.leaseRecords.filter` 在表不存在时直接 500;
|
||||
* 这套路由在当前前端代码里已无任何调用方,保留但补上兜底。
|
||||
*
|
||||
* 4. **`multer` 实例是模块级单例、storage 是同步回调**,本身没问题;
|
||||
* 但 `path` 变量同时被用作「目录」和「数据库字段名」(`data.path = path`),
|
||||
* 语义混淆。这里显式区分 `filePath` 与存储字段。
|
||||
*/
|
||||
|
||||
/** 允许上传的扩展名白名单 */
|
||||
const ALLOWED_EXTENSIONS = new Set([".js", ".mjs", ".json", ".txt", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".pdf", ".zip"]);
|
||||
|
||||
/** 单文件大小上限:20MB */
|
||||
const MAX_FILE_SIZE = 20 * 1024 * 1024;
|
||||
|
||||
/** 存储目录(相对项目根,固定下来而不是依赖 cwd) */
|
||||
const STATIC_DIR = process.env.UPLOAD_DIR || "static";
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (_req, _file, cb) => {
|
||||
cb(null, STATIC_DIR);
|
||||
},
|
||||
filename: (_req, file, cb) => {
|
||||
// 只取扩展名,且限定为白名单内的安全字符,杜绝文件名注入
|
||||
const ext = path.extname(file.originalname || "").toLowerCase();
|
||||
const safeExt = /^\.[a-z0-9]+$/.test(ext) ? ext : "";
|
||||
cb(null, `${cuid()}${safeExt}`);
|
||||
},
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: MAX_FILE_SIZE },
|
||||
fileFilter: (_req, file, cb) => {
|
||||
const ext = path.extname(file.originalname || "").toLowerCase();
|
||||
if (!ALLOWED_EXTENSIONS.has(ext)) {
|
||||
cb(new Error(`不支持的文件类型: ${ext || "未知"}`));
|
||||
return;
|
||||
}
|
||||
cb(null, true);
|
||||
},
|
||||
});
|
||||
|
||||
const getUpload = (router) => {
|
||||
router.post("/api/leaseRecords/list", async (ctx) => {
|
||||
ctx.type = "application/json";
|
||||
const { table } = await getTable(getDb, "leaseRecords");
|
||||
|
||||
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/img", async (ctx) => {
|
||||
ctx.type = "application/json";
|
||||
const { table } = await getTable(getDb, "leaseRecords");
|
||||
const detail = table.find((item) => item.id == ctx.request.query.id);
|
||||
|
||||
ctx.body = { code: 0, data: detail || {} };
|
||||
});
|
||||
|
||||
/** 写入资源库并返回记录 id */
|
||||
const addImg = async (filename, filePath) => {
|
||||
try {
|
||||
const db = await getResourceDb();
|
||||
if (!Array.isArray(db.data.img)) db.data.img = [];
|
||||
|
||||
const record = {
|
||||
id: cuid(),
|
||||
filename,
|
||||
path: filePath,
|
||||
createTime: new Date(),
|
||||
};
|
||||
db.data.img.push(record);
|
||||
await db.write();
|
||||
return record.id;
|
||||
} catch (error) {
|
||||
console.error("写入图片资源库失败", error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** 上传图片:落盘 + 记录资源库 */
|
||||
router.post("/api/upload/img", upload.single("file"), async (ctx) => {
|
||||
if (!ctx.file) {
|
||||
ctx.body = { code: 1, msg: "未接收到文件" };
|
||||
return;
|
||||
}
|
||||
const { filename, path: filePath } = ctx.file;
|
||||
const id = await addImg(filename, filePath);
|
||||
|
||||
ctx.body = {
|
||||
code: id ? 0 : 1,
|
||||
data: { id, url: filePath },
|
||||
};
|
||||
});
|
||||
|
||||
/** 上传任意文件:仅落盘,返回可访问 url */
|
||||
router.post("/api/upload/file", upload.single("file"), async (ctx) => {
|
||||
if (!ctx.file) {
|
||||
ctx.body = { code: 1, msg: "未接收到文件" };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
data: { url: `/resource/static/${ctx.file.filename}` },
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export default getUpload;
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
/**
|
||||
* 服务端路由烟雾测试(不依赖 funjia-server / cuid / lodash)。
|
||||
*
|
||||
* 用 vm 在内存中加载路由源码,把外部依赖替换成桩,再配一个内存版 db,
|
||||
* 直接调用真实 handler 做断言。重点回归「整库被清空」这个致命缺陷。
|
||||
*
|
||||
* node smoke-test.mjs
|
||||
*
|
||||
* 退出码 0 = 全部通过,1 = 有用例失败。
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import vm from "node:vm";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// ── 沙箱内可用的桩 ────────────────────────────────────────────────────
|
||||
const sandbox = {
|
||||
console,
|
||||
Math,
|
||||
Date,
|
||||
JSON,
|
||||
Object,
|
||||
Array,
|
||||
String,
|
||||
Number,
|
||||
Boolean,
|
||||
Promise,
|
||||
Error,
|
||||
TypeError,
|
||||
setTimeout,
|
||||
__cuid: () => "id-" + Math.random().toString(36).slice(2, 10),
|
||||
__lodashMerge: (target, source) => Object.assign(target, source),
|
||||
__db: null,
|
||||
};
|
||||
sandbox.globalThis = sandbox;
|
||||
vm.createContext(sandbox);
|
||||
|
||||
/** 把路由源码的 import 改写成沙箱内的全局引用 */
|
||||
const rewrite = (src) => {
|
||||
let out = src;
|
||||
|
||||
// default 导入的第三方包
|
||||
out = out.replace(
|
||||
/import\s+cuid\s+from\s+["'][^"']*cuid["'];?/g,
|
||||
"const cuid = globalThis.__cuid;"
|
||||
);
|
||||
out = out.replace(
|
||||
/import\s+_\s+from\s+["'][^"']*lodash["'];?/g,
|
||||
"const _ = { merge: (t, s) => globalThis.__lodashMerge(t, s) };"
|
||||
);
|
||||
|
||||
// funjia-server 的具名导入(支持 `X as Y` 别名)
|
||||
out = out.replace(
|
||||
/import\s*\{([^}]*)\}\s*from\s*["']funjia-server[^"']*["'];?/g,
|
||||
(m, names) =>
|
||||
names
|
||||
.split(",")
|
||||
.map((n) => n.trim())
|
||||
.filter(Boolean)
|
||||
.map((n) => {
|
||||
const [orig, alias] = n.split(/\s+as\s+/).map((s) => s.trim());
|
||||
return `const ${alias || orig} = globalThis.__${orig};`;
|
||||
})
|
||||
.join("\n")
|
||||
);
|
||||
|
||||
// 相对导入 helpers.mjs(支持 `getTable as getTableRaw` 别名)
|
||||
out = out.replace(
|
||||
/import\s*\{([^}]*)\}\s*from\s*["'][^"']*helpers\.mjs["'];?/g,
|
||||
(m, names) =>
|
||||
names
|
||||
.split(",")
|
||||
.map((n) => n.trim())
|
||||
.filter(Boolean)
|
||||
.map((n) => {
|
||||
const [orig, alias] = n.split(/\s+as\s+/).map((s) => s.trim());
|
||||
return `const ${alias || orig} = globalThis.__helpers.${orig};`;
|
||||
})
|
||||
.join("\n")
|
||||
);
|
||||
|
||||
// export default Foo → 挂到 __mod
|
||||
out = out.replace(/export\s+default\s+([A-Za-z_$][\w$]*)\s*;?/g, "globalThis.__mod = $1;");
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
const loadModule = (relPath) => {
|
||||
sandbox.__mod = undefined;
|
||||
const src = rewrite(readFileSync(join(here, relPath), "utf8"));
|
||||
// 每个模块包一层 IIFE,避免不同文件的顶层 const 在共享沙箱里冲突
|
||||
vm.runInContext(`(function () {\n${src}\n})();`, sandbox, { filename: relPath });
|
||||
return sandbox.__mod;
|
||||
};
|
||||
|
||||
// ── 先加载 helpers.mjs ────────────────────────────────────────────────
|
||||
{
|
||||
let src = readFileSync(join(here, "routers/helpers.mjs"), "utf8");
|
||||
src = src.replace(/export\s+const\s+([A-Za-z_$][\w$]*)\s*=/g, "const $1 =");
|
||||
src += "\nglobalThis.__helpers = { getTable, pickFilters, matchRow, paginate, listResponse, omitSensitive };";
|
||||
vm.runInContext(src, sandbox, { filename: "routers/helpers.mjs" });
|
||||
}
|
||||
|
||||
// ── getDb 桩:读 sandbox.__db ─────────────────────────────────────────
|
||||
sandbox.__getDb = async () => sandbox.__db;
|
||||
|
||||
// ── 载入被测路由 ──────────────────────────────────────────────────────
|
||||
const getEmployee = loadModule("routers/anki/employee.mjs");
|
||||
const getNotice = loadModule("routers/anki/notice.mjs");
|
||||
const getDynamic = loadModule("routers/dynamic.mjs");
|
||||
|
||||
// ── 假 router:收集路由表 ─────────────────────────────────────────────
|
||||
const routes = [];
|
||||
const router = {};
|
||||
for (const m of ["get", "post", "put", "delete"]) {
|
||||
router[m] = (path, handler) => routes.push({ method: m, path, handler });
|
||||
}
|
||||
getEmployee(router);
|
||||
getNotice(router);
|
||||
getDynamic(router);
|
||||
|
||||
const find = (method, path) => {
|
||||
const r = routes.find((x) => x.method === method && x.path === path);
|
||||
if (!r) throw new Error(`路由未注册: ${method.toUpperCase()} ${path}`);
|
||||
return r.handler;
|
||||
};
|
||||
|
||||
// ── 测试工具 ──────────────────────────────────────────────────────────
|
||||
const makeDb = (seed) => ({
|
||||
data: JSON.parse(JSON.stringify(seed)),
|
||||
write: async () => {},
|
||||
});
|
||||
|
||||
const makeCtx = ({ params = {}, query = {}, body = {} } = {}) => ({
|
||||
type: "",
|
||||
body: undefined,
|
||||
params,
|
||||
request: { query, body },
|
||||
});
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
const test = async (name, fn) => {
|
||||
try {
|
||||
await fn();
|
||||
passed++;
|
||||
console.log(` PASS ${name}`);
|
||||
} catch (err) {
|
||||
failed++;
|
||||
console.log(` FAIL ${name}`);
|
||||
console.log(` ${err.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 断言是「空数组」。
|
||||
* 不能直接用 assert.deepEqual(x, []):沙箱里创建的数组与主 realm 的 `[]`
|
||||
* 原型不同,Node 会判定为「结构相同但非同一引用」。这里只校验实质语义。
|
||||
*/
|
||||
const assertEmptyArray = (value, label = "值") => {
|
||||
assert.ok(Array.isArray(value), `${label} 不是数组: ${JSON.stringify(value)}`);
|
||||
assert.equal(value.length, 0, `${label} 应为空数组,实际长度 ${value.length}`);
|
||||
};
|
||||
|
||||
const seed = {
|
||||
employee: [
|
||||
{ id: "e1", userName: "admin", pwd: "123456", realName: "管理员" },
|
||||
{ id: "e2", userName: "staff", pwd: "654321", realName: "员工甲" },
|
||||
],
|
||||
Notice: [{ id: "n1", title: "公告一", sort: 1 }],
|
||||
leaseRecords: [{ id: "l1", name: "租赁单" }],
|
||||
};
|
||||
|
||||
// ══ 用例 ══════════════════════════════════════════════════════════════
|
||||
console.log("\n=== 服务端路由烟雾测试 ===\n");
|
||||
console.log("[员工路由]");
|
||||
|
||||
await test("list 不泄漏 pwd 明文", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: {} });
|
||||
await find("post", "/api/employee/list")(ctx);
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(ctx.body.total, 2);
|
||||
for (const row of ctx.body.data) {
|
||||
assert.ok(!("pwd" in row), `pwd 泄漏: ${JSON.stringify(row)}`);
|
||||
}
|
||||
});
|
||||
|
||||
await test("list 在空表时不抛 500", async () => {
|
||||
sandbox.__db = makeDb({});
|
||||
const ctx = makeCtx({ body: {} });
|
||||
await find("post", "/api/employee/list")(ctx);
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(ctx.body.total, 0);
|
||||
assertEmptyArray(ctx.body.data, "列表数据");
|
||||
});
|
||||
|
||||
await test("login 成功返回用户但不含 pwd", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { userName: "admin", pwd: "123456" } });
|
||||
await find("post", "/api/employee/login")(ctx);
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(ctx.body.data.userName, "admin");
|
||||
assert.ok(!("pwd" in ctx.body.data));
|
||||
});
|
||||
|
||||
await test("login 失败不区分账号/密码错误(防枚举)", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const a = makeCtx({ body: { userName: "nobody", pwd: "x" } });
|
||||
const b = makeCtx({ body: { userName: "admin", pwd: "wrong" } });
|
||||
await find("post", "/api/employee/login")(a);
|
||||
await find("post", "/api/employee/login")(b);
|
||||
assert.equal(a.body.code, 1);
|
||||
assert.equal(b.body.code, 1);
|
||||
assert.equal(a.body.msg, b.body.msg);
|
||||
});
|
||||
|
||||
await test("add 拒绝重复用户名", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { userName: "admin", pwd: "x" } });
|
||||
await find("post", "/api/employee/add")(ctx);
|
||||
assert.equal(ctx.body.code, 1);
|
||||
assert.equal(sandbox.__db.data.employee.length, 2);
|
||||
});
|
||||
|
||||
await test("add 忽略请求体传入的 id / createTime", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { userName: "newbie", id: "HACKED", createTime: "1970-01-01" } });
|
||||
await find("post", "/api/employee/add")(ctx);
|
||||
const added = sandbox.__db.data.employee.find((x) => x.userName === "newbie");
|
||||
assert.ok(added, "新员工未写入");
|
||||
assert.notEqual(added.id, "HACKED");
|
||||
assert.notEqual(added.createTime, "1970-01-01");
|
||||
});
|
||||
|
||||
await test("upd 不能覆盖主键 id,且能改动业务字段", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { id: "e1", realName: "改名了", pwd: "newpwd" } });
|
||||
await find("post", "/api/employee/upd")(ctx);
|
||||
const row = sandbox.__db.data.employee.find((x) => x.id === "e1");
|
||||
assert.ok(row, "e1 丢失");
|
||||
assert.equal(row.id, "e1");
|
||||
assert.equal(row.realName, "改名了");
|
||||
});
|
||||
|
||||
await test("upd 目标不存在时返回业务错误而非 500", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { id: "not-exist", realName: "x" } });
|
||||
await find("post", "/api/employee/upd")(ctx);
|
||||
assert.equal(ctx.body.code, 1);
|
||||
});
|
||||
|
||||
await test("delete 只删指定记录并返回条数", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { ids: ["e1", "ghost"] } });
|
||||
await find("post", "/api/employee/delete")(ctx);
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(ctx.body.data.deleted, 1);
|
||||
assert.equal(sandbox.__db.data.employee.length, 1);
|
||||
});
|
||||
|
||||
await test("delete 空 ids 被拒绝", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ body: { ids: [] } });
|
||||
await find("post", "/api/employee/delete")(ctx);
|
||||
assert.equal(ctx.body.code, 1);
|
||||
});
|
||||
|
||||
console.log("\n[通知路由]");
|
||||
|
||||
await test("Notice list 不因空表崩溃", async () => {
|
||||
sandbox.__db = makeDb({});
|
||||
const ctx = makeCtx({ body: {} });
|
||||
await find("post", "/api/Notice/list")(ctx);
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assertEmptyArray(ctx.body.data, "列表数据");
|
||||
});
|
||||
|
||||
console.log("\n[★ 致命缺陷回归:整库清空]");
|
||||
|
||||
await test("dynamic.upd 目标表缺失时不清空整库", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ params: { tableName: "brandNewTable" }, body: { id: "x", name: "y" } });
|
||||
await find("post", "/api/dynamic/upd/:tableName")(ctx);
|
||||
|
||||
assert.ok(Array.isArray(sandbox.__db.data.employee), "employee 表被清空了!");
|
||||
assert.equal(sandbox.__db.data.employee.length, 2);
|
||||
assert.ok(Array.isArray(sandbox.__db.data.Notice), "Notice 表被清空了!");
|
||||
assert.equal(sandbox.__db.data.Notice.length, 1);
|
||||
assert.ok(Array.isArray(sandbox.__db.data.leaseRecords), "leaseRecords 表被清空了!");
|
||||
assertEmptyArray(sandbox.__db.data.brandNewTable, "缺失的新表");
|
||||
});
|
||||
|
||||
await test("dynamic.delete 目标表缺失时不清空整库", async () => {
|
||||
sandbox.__db = makeDb(seed);
|
||||
const ctx = makeCtx({ params: { tableName: "anotherNewTable" }, body: { ids: ["a"] } });
|
||||
await find("post", "/api/dynamic/delete/:tableName")(ctx);
|
||||
|
||||
assert.equal(sandbox.__db.data.employee.length, 2, "employee 表被清空了!");
|
||||
assert.equal(sandbox.__db.data.Notice.length, 1, "Notice 表被清空了!");
|
||||
});
|
||||
|
||||
await test("dynamic.list 空表返回空数组而非 500", async () => {
|
||||
sandbox.__db = makeDb({});
|
||||
const ctx = makeCtx({ params: { tableName: "whatever" }, body: {} });
|
||||
await find("post", "/api/dynamic/list/:tableName")(ctx);
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assertEmptyArray(ctx.body.data, "列表数据");
|
||||
assert.equal(ctx.body.total, 0);
|
||||
});
|
||||
|
||||
await test("dynamic.add 忽略请求体 id / createTime", async () => {
|
||||
sandbox.__db = makeDb({ whatever: [] });
|
||||
const ctx = makeCtx({ params: { tableName: "whatever" }, body: { id: "HACK", createTime: "0" } });
|
||||
await find("post", "/api/dynamic/add/:tableName")(ctx);
|
||||
const row = sandbox.__db.data.whatever[0];
|
||||
assert.ok(row, "未写入");
|
||||
assert.notEqual(row.id, "HACK");
|
||||
assert.notEqual(row.createTime, "0");
|
||||
});
|
||||
|
||||
await test("dynamic 分页参数生效", async () => {
|
||||
sandbox.__db = makeDb({ big: Array.from({ length: 25 }, (_, i) => ({ id: `b${i}`, n: i })) });
|
||||
const ctx = makeCtx({ params: { tableName: "big" }, body: { page: 2, pageSize: 10 } });
|
||||
await find("post", "/api/dynamic/list/:tableName")(ctx);
|
||||
assert.equal(ctx.body.total, 25);
|
||||
assert.equal(ctx.body.data.length, 10);
|
||||
assert.equal(ctx.body.data[0].id, "b10");
|
||||
});
|
||||
|
||||
// ── 汇总 ──────────────────────────────────────────────────────────────
|
||||
console.log(`\n=== 结果: ${passed} 通过 / ${failed} 失败 ===\n`);
|
||||
process.exit(failed === 0 ? 0 : 1);
|
||||
Reference in New Issue
Block a user