# shrimp-server 声明式字段驱动的 Node.js 后台管理框架(Express + Mongoose + JWT)。后台只声明"表 + 字段",前端自动渲染表格、表单、搜索、菜单。 ## 在你的项目里用 ```sh # 推荐: HTTP(任何能访问 git.zeromvc.com 的机器都能用) npm install git+http://git.zeromvc.com/wc24/shrimp-server.git#v0.2.0 # 也可以 SSH(需要 ssh key 配好) npm install git+ssh://git@git.zeromvc.com:wc24/shrimp-server.git#v0.2.0 ``` > 仓库 ship `.ts` 源码,消费方项目需要 TS 运行器(`tsx` / `ts-node`)或在打包工具(vite / webpack / esbuild)里能解析 `.ts`。 ### 两个入口,按需选择 包内提供了**核心**和**完整 server** 两个 entry,**peer deps 全部 optional**——你只装自己用得到的那一份: ```ts // 1) 核心: 0 重依赖(只需 node + tsx),适合自己接 HTTP / 只用内存 CRUD / 嵌入其它框架 import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, ShrimpFieldTypes } from "shrimp-server" // 2) 完整 server: 自带 Express Router + Mongoose + JWT,需要装上面 4 个 peer import { ShrimpServer, MongoShrimpCrud } from "shrimp-server/server" ``` 只用 (1) 时,**不要**在自己的 package.json 里写 express/mongoose/bcrypt/jsonwebtoken,可以省下大量 install 时间(尤其是 mongoose 的 native binding)。需要 (2) 时按 peer 范围装齐即可。 > bcrypt 在 core 里走的是动态 `import('bcrypt')`,不触发 Password 字段 hash / `UserModule.verifyPassword` 就完全不会去 require 它。所以即便用 core 也注册了 password 字段,只要你不真正调用 `add/edit` 写入 Password 或 `getUser` 校验密码,bcrypt 仍是可不装的。 --- # 使用指南 本文按"想做什么"组织,每个场景给你最短的可工作代码。 > Memory:Shrimp 在 list/get 时把 relation 字段的关联标签旁挂为 `${key}_label`(数组关联挂数组)。这是有意设计,读写对称,不要改成 `{_id, label}` 嵌套对象。 --- ## 约定 ### 国际化 (ILabel) 所有前端可见文本字段(`label` / `tip` / `menu.label` / `power.label` / `field.label` / `rule.message` …)统一类型 `ILabel`。**用哪种形态取决于你写在哪一层**。 #### 框架层(`lib/shrimp/`) 框架是可复用组件,内置文案要支持翻译,**必须用对象形态**: ```ts { t: 'shrimp.fieldRequired', params: { field: field.label } } // 翻译 + 模板参数 { tc: 'shrimp.itemCount', count: n } // 复数 { d: createdAt, format: 'short' } // 日期格式化 { n: amount, format: 'currency' } // 数字/货币格式化 ``` #### 业务层(`src/`) 当前项目独有内容,**直接写中文字面量**: ```ts label: '方案管理' throw new ShrimpError('余额不足') this.addEvent('changeState', '更改状态') { name: 'matter', label: '物资管理', children: [...] } ``` 业务层后续若要做多语言,把对应处改成 `{ t: 'app.xxx' }` 即可,类型已经支持,不必改动框架代码。 #### `ILabel` 完整形态(类型上 6 选 1) ```ts type ILabel = | string // 1. 字面量,前端原样显示 | { t: string; params?: Record } // 2. 翻译(vue-i18n t) | { tc: string; count: number; params?: ... } // 3. 复数(vue-i18n tc) | { d: number | Date; format?: string } // 4. 日期格式化 | { n: number; format?: string } // 5. 数字/货币格式化 | Record // 6. 内联多语言 { zh, en } ``` `params` 值本身也是 `ILabel`,前端递归翻译。 #### 反模式 ```ts label: 'user.username' // ❌ 看着像 i18n key 但是 string,前端按字面量原样显示 label: { t: 'user.username' } // ✅ 框架场景:显式翻译 label: '用户名' // ✅ 业务场景:直接字面量 ``` ## 1. 起一个后台(5 分钟) ```ts // src/MyAdmin.ts import { ShrimpServer } from '../lib/shrimp/ShrimpServer' export class MyAdmin extends ShrimpServer { protected async onDbConnected() { await this.initDefaultData('超级管理员', 'Built-in admin') } } ``` ```ts // index.ts import express from 'express' import { MyAdmin } from './src/MyAdmin' const admin = new MyAdmin('jwt-secret', { title: '我的后台' }, 'mongodb://localhost:27017/myapp') const app = express() app.use(express.json()) app.use('/admin-api', admin.router) app.listen(3001) ``` 启动后访问前端,默认账号 `admin / admin`。 --- ## 2. 加一张 CRUD 表 ```ts // src/MyAdmin.ts import mongoose, { Schema } from 'mongoose' import { ShrimpTableModule } from '../lib/shrimp/Shrimp' import { MongoShrimpCrud } from '../lib/shrimp/MongoShrimpCrud' import { IFieldConfig } from '../lib/shrimp/IShrimpType' const ItemSchema = new Schema({ code: { type: String, required: true }, name: { type: String, required: true }, description: { type: String, default: '' }, }, { timestamps: true }) const itemFields: IFieldConfig[] = [ { key: 'code', label: 'item.code', type: 'string', required: true, searchable: true, editable: 'addOnly' }, { key: 'name', label: 'item.name', type: 'string', required: true, searchable: true }, { key: 'description', label: 'item.description', type: 'textarea' }, { key: 'createdAt', label: 'item.createdAt', type: 'date', editable: 'readonly', sortable: true }, ] export class MyAdmin extends ShrimpServer { constructor(jwtSecret: string, config: any, mongoUri: string) { super(jwtSecret, config, mongoUri) const itemModel = mongoose.model('items', ItemSchema) new ShrimpTableModule( this, 'item', new MongoShrimpCrud(itemModel), itemFields, '物品管理' ).initCrud() } } ``` 到这一步,前端管理界面就出现"物品管理"菜单 + 表格 + 新增/编辑表单 + 删除按钮,完全自动渲染。 **字段配置常用项:** - `searchable: true` — 出现在搜索框 - `sortable: true` — 表头点击排序 - `filterable: true` — 出现在筛选栏(精确匹配) - `editable: 'addOnly'` — 新增可填,编辑禁改(如 `code`) - `editable: 'readonly'` — 永远只读(如 `createdAt`) - `tableHide: true` — 表格不显示这一列但仍返回数据 - `hidden: true` — 数据完全不下发到前端 - `required: true` — 表单必填 - `defaultValue: ...` — 新增时的默认值 **字段 type 选这些:** `string` / `number` / `boolean` / `date` / `textarea` / `password` / `select` / `relation` / `json` / `tab` --- ## 3. 关联其他表 ```ts const orderFields: IFieldConfig[] = [ { key: 'no', label: 'order.no', type: 'string', required: true }, { key: 'itemId', label: 'order.itemId', type: 'relation', relation: { moduleKey: 'item', labelKey: 'name' }, // 关联 item 表,显示 name filterable: true, }, // 数组关联(多选) { key: 'tagIds', label: 'order.tagIds', type: 'relation', relation: { moduleKey: 'tag', labelKey: 'name' }, multiple: true, defaultValue: [], }, ] ``` `list / get` 返回的数据会自动多一个 `itemId_label`(单值)或 `tagIds_label`(数组)字段,前端表格直接显示标签,无需另发请求。 > 自动 populate 走 `root.crudRegistry`,你不需要手动登记 — `ShrimpTableModule` 构造时自动登记。 --- ## 4. 定义自定义业务事件(不止 CRUD) `initCrud()` 注册了 5 个标准事件,如果你需要更多,自己加。 ```ts class OrderTable extends ShrimpTableModule { constructor(parent, dataSource) { super(parent, 'order', dataSource, orderFields, '订单管理') this.initCrud() this.addEvent('ship', '发货') // 新增 ship 事件,业务直接写中文 this.addEvent('refund', '退款') } async ship(id: string) { return this.dataSource.edit(id, { status: 'shipped', shippedAt: Date.now() } as any) } async refund(id: string, reason: string) { // 业务逻辑... return true } } ``` 前端 HTTP 直接调: - `POST /admin-api/order/ship`,body `[id]` - `POST /admin-api/order/refund`,body `[id, reason]` > body 永远是参数数组,框架按位置解构。前端 `vueAdmin.getModule('order').ship(id)` 自动包装。 --- ## 5. 改默认行为(钩子) ### 拦截新增/编辑 ```ts class UserTable extends ShrimpTableModule { async edit(id: string, item: Partial) { if (item.role === 'admin' && !this.root.operator?.isSuperAdmin) { throw new ShrimpError('不能将用户提升为管理员') } return super.edit(id, item) } } ``` ### 字段级 reqFilter / validate 通过 `registerTypeHandler` 注册自定义 type 的处理器: ```ts import { ShrimpTableModule, ShrimpError } from '../lib/shrimp/Shrimp' ShrimpTableModule.registerTypeHandler('phone', { reqFilter: (value) => String(value).replace(/\s+/g, ''), validate: (value) => /^\d{11}$/.test(value) ? null : 'myapp.invalidPhone', }) ``` 字段配置写 `type: 'phone'`,框架自动应用。 ### 自定义 type 的前端渲染 后端只声明 `type: 'fieldGoodsPicker'` 即可,前端在 `hand-admin/src/module/fields/` 放一个 `FieldGoodsPicker.vue`,会按命名约定自动注册(`Field*.vue` → `'field' + *`)。 --- ## 6. 用 operator 拿到当前登录用户 `AsyncLocalStorage` 维护的请求级上下文,事件 handler 里随时可取: ```ts class TaskTable extends ShrimpTableModule { async add(item) { const op = this.root.operator return super.add({ ...item, ownerId: op?.userId } as any) } async list(query) { const op = this.root.operator // 非超管只看自己的 if (!op?.isSuperAdmin) { query = { ...query, filter: { ...query?.filter, ownerId: op?.userId } } } return super.list(query) } } ``` --- ## 7. 权限怎么走通 每个模块和事件都自动有 power key,角色 `IRole.powers` 存放被授权的 key: | 注册位置 | 生成的 power key | | --- | --- | | `new ShrimpTableModule(root, 'item', ...)` | `item`(模块访问权,涵盖 list/get) | | `.addEvent('add', '新增')` | `item.add` | | `.addEvent('edit', '编辑')` | `item.edit` | | 子模块 `new ShrimpModule(parentModule, 'sub', ...)` | `parent.sub`(子模块详见第 9 节) | 授权流程: 1. 进角色管理界面,新建角色,在 PowerTree 勾对应 key,保存 2. 进用户管理,给用户绑这个角色 3. 用户重新登录(或刷新 token),`/me` 自动按权限过滤模块和菜单 `isSuperAdmin: true` 的角色绕开所有检查。 --- ## 8. 菜单分组 默认顶层模块平铺。要把多个模块归到一个菜单组,覆盖 `getMenuTree()`: ```ts import { IMenuItem } from '../lib/shrimp/IShrimpType' class MyAdmin extends ShrimpServer { getMenuTree(): IMenuItem[] { const labelMap: Record = { matter_item: '物品', matter_scheme: '方案', matter_dropGroup: '掉落组', matter_point: '物资点', } const matterKeys = Object.keys(labelMap) const matterChildren = matterKeys .filter(k => this.modules.has(k)) .map(k => ({ name: k, label: labelMap[k], moduleKey: k })) const grouped = new Set(matterChildren.map(c => c.moduleKey)) const rest: IMenuItem[] = [] this.modules.forEach(m => { if (grouped.has(m.moduleKey)) return rest.push({ name: m.moduleKey, label: m.moduleKey, moduleKey: m.moduleKey }) }) return [...rest, { name: 'matter', label: '物资管理', children: matterChildren }] } } ``` 要点: - 分组节点 **不要** 带 `moduleKey`,只用 `children` - 叶子节点带 `moduleKey`,路由就是 `/` - `filterMenuTree` 会按权限自动剔除整组没权限的分支 - 分组支持**任意层嵌套**: `children` 里继续放带 `children` 的分组节点即可,前端菜单/面包屑递归渲染,无限层级 --- ## 9. 子模块(行内跳转的从属页面) 主模块上的每一行经常需要一个独立的二级编辑页(比如"方案"的物资点配置)。子模块就是这种场景的官方表达:挂在主模块下、不进菜单、按行跳转、独立鉴权。 ### 注册 ```ts const schemeModule = new ShrimpTableModule(server, 'matter_scheme', crud, schemeFields, '方案管理').initCrud() new ShrimpModule(schemeModule, 'pointDrops', '物资点配置', undefined, { icon: 'Setting' }) ``` 参数顺序: `(parent, moduleKey, label, power?, options?)`。`options.icon` 用于前端操作栏跳转按钮(element-plus icon 名,大写驼峰)。 子模块也可以再挂子模块,**嵌套任意层**: `parent` 传入上一层 `ShrimpModule` 即可。 ```ts const project = new ShrimpTableModule(server, 'project', ..., '项目管理').initCrud() const task = new ShrimpTableModule(project, 'task', ..., '任务', undefined, { ownerKey: 'projectId' }).initCrud() const subtask = new ShrimpTableModule(task, 'subtask', ..., '子任务步骤', undefined, { ownerKey: 'taskId' }).initCrud() ``` 效果: - 路由自动注册为 `/project` → `/project/task` → `/project/task/subtask` - 前端 Vue 组件按目录嵌套: `src/module/project.vue` / `src/module/project/task.vue` / `src/module/project/task/subtask.vue` - Power key 链: `project` / `project.task` / `project.task.subtask` - 面包屑递归显示并可点击逐级返回 (`物资管理 / 项目管理 / 任务 / 子任务步骤`),顶栏额外提供"返回"按钮走浏览器历史(回退时保留父 id 的 `?id=` 查询) #### 多级父 id 在 URL 中的传递 子表页面的 `ownerId` 来自 `?id=`(immediate parent 的记录 id)。多级嵌套时,**祖先级**的 id 也要带上,否则用户点面包屑回到中间层就丢失了过滤条件。 约定: - `?id=` — 当前页 ownerId - `?pids=,<...>,` — 祖先链(root → immediate-parent 之前的所有 id,逗号分隔) 例: - `/project/task?id=projA` — task 的 ownerId 是 projA - `/project/task/subtask?id=taskB&pids=projA` — subtask 的 ownerId 是 taskB,上一层(task)需要 projA - `/a/b/c/d?id=cId&pids=aId,bId` — 4 层嵌套 `ShrimpTable.handleSubJump` 跳子模块时自动把 `?id` 推入 `pids`,row._id 写到新 `?id`;`topbar` 面包屑按每个层级所需的 `id`/`pids` 重建 `:to` 链接;`useTableUrlSync` 白名单只同步 `page/pageSize/keyword/sort/filter`,`id` 和 `pids` 自动保留。 ### 权限 子模块复用现有的 power 树,不引入新机制: - 模块自身 power key 自动是 `parent.sub`(例: `matter_scheme.pointDrops`) - 用户角色没勾这个 key → `/me` 返回的 moduleInfo 里不会出现该子模块 → 前端按钮和路由都不存在 - 子模块上 `addEvent` 的事件 power 是 `parent.sub.event`,层级继续延伸 ### 前端约定 子模块的 moduleInfo 是**扁平**的,与主模块同列,靠 `parent` 字段关联: ```ts { moduleKey: 'pointDrops', parent: 'matter_scheme', icon: 'Setting', ... } ``` `ShrimpClient` 自动: - 注册路由 `//`(嵌套层级按 parent 链拼接) - 把对应 Vue 组件文件期望放在 `src/module//.vue` - `ShrimpTable` 检测 `moduleInfo.parent === currentModuleKey` 的项,在操作栏每行加一个图标按钮,点击跳到 `//?id=` 子模块页面通常**不需要自己的 CRUD**——它操作的是主模块的某条记录,直接调主模块 API: ```vue ``` 只有当子模块需要自己的事件(如批量同步、独立列表)时,才把它做成 `ShrimpTableModule` 并 `initCrud()`。 ### 真子表: `ownerKey` 自动过滤 当子模块有**独立的记录集合**(master-detail,如"用户的操作日志"),需要按父记录 id 过滤,这通过 `options.ownerKey` 声明: ```ts new OperationLogModule(userModule, crud, fields, label, undefined, { icon: 'Tickets', ownerKey: 'operatorId', // 子表记录中指向父记录(user._id)的字段名 }) ``` #### 前后端各做什么 约定的语义是: 前端只发一个通用 `ownerId`(父记录 id),后端按自己 `ownerKey` 配置翻译成具体字段名。`ownerKey` **只活在后端**,前端不知道(也不必知道)子表记录里那一列叫什么名字。 - **后端 `ShrimpTableModule`**: - `list/clear/export`: `buildQuery` 读 `query.ownerId`,如果 `this.ownerKey` 已配置,强制注入 `where[ownerKey] = { eq: ownerId }`(放在用户 filter 之后,用户绕不过) - `add(item, ownerId?)` / `import(data, ownerId?)`: 第二参数是 ownerId,自动写入 `item[ownerKey]`,前端不需要在 payload 里放业务字段名 - **前端 `ShrimpTable`**: - 通过 `moduleInfo.parent` 判断当前模块是子模块,从 `route.query.id` 取父 id 作为 `ownerId` - 所有 RPC(list/clear/export/add/import)自动带上 `ownerId`,不混入 filter #### ownerKey 字段不进 fields[] 子表里 ownerKey 对应的列(如 operationLog 的 `operatorId`)语义上就是"父记录外键",所有行都同值,不属于 UI 关心范围: ```ts // OperationLogModule.ts const operationLogFields: IFieldConfig[] = [ // 注意: operatorId 不在 fields 里 — 纯数据库字段,框架按 ownerKey 自动注入 filter { key: "ip", ... }, { key: "method", ... }, ... ] ``` 效果: 子表页面不渲染 ownerKey 列、筛选抽屉里没这一项、表单里也没这一项,但数据库照常存。如果某天需要做"顶层操作日志列表"(显示全部用户的日志,按操作者筛选),那是另一个模块/另一份 fields 配置的事。 子模块页面写法极简: ```vue ``` 如需在某场景下手动追加额外过滤(例如二级筛选),可继续传 `:baseFilter`,它会**覆盖**用户的筛选选择,但不影响 `ownerId` 注入: ```vue ``` #### URL 参数保留 `useTableUrlSync` 把 `page/pageSize/keyword/sortBy/sortOrder/filter` 同步到 URL,但**保留**其它已有的 query 参数(如 `?id=`),不会被 sort/filter 操作清掉。子表页面的父 id 因此不会在用户排序后消失。 ### 不要做的事 - 别把子模块塞进 `getMenuTree()`,它不应出现在菜单里 - 别给子模块单独建一个无关 power(`new ShrimpPower(...)` 覆盖默认),会破坏 `parent.sub` 的继承语义 - 别在 `moduleInfo` 上找 `subModules` 数组——结构已经扁平化,用 `parent` 字段过滤 --- ## 10. 替换内置 User/Role 最常见场景:你已经有用户表,字段名跟 Shrimp 不一样,或想加额外字段。 ```ts class MyAdmin extends ShrimpServer { // 1. 改 schema protected createUserSchema() { return new Schema({ account: { type: String, required: true }, // 重命名 username → account password: { type: String, required: true }, displayName: String, roleId: { type: [Schema.Types.ObjectId], default: [] }, active: { type: Boolean, default: true }, phone: String, // 额外字段 }, { timestamps: true }) } // 2. 改字段访问钩子(让框架认得你的字段名) protected getUserDisplayName(user: any) { return user.displayName || '' } protected isUserActive(user: any) { return user.active === true } protected getUserRoleIds(user: any) { return Array.isArray(user.roleId) ? user.roleId.map(String) : [] } // 3. (可选)替换模块类,加自定义字段配置 protected createUserModule(dataSource) { return new UserModule(this, dataSource, [ { key: 'account', label: 'user.account', type: 'string', required: true, editable: 'addOnly' }, { key: 'password', label: 'user.password', type: 'password', tableHide: true }, { key: 'displayName', label: 'user.displayName', type: 'string' }, { key: 'phone', label: 'user.phone', type: 'string' }, // ... ]) } } ``` 登录接口 `POST /login` 仍然收 `username`,框架内部走的是 `userModule.getUser(username, password)`。如果你想让登录接口用 `account`,override `UserModule.getUser`: ```ts class MyUserModule extends UserModule { async getUser(account: string, password: string) { const user = await this.dataSource.findOne({ account, active: true }) if (!user || !(await bcrypt.compare(password, user.password))) { throw new ShrimpError({ t: 'shrimp.loginFailed' }) // 复用框架已有的 i18n key,沿用其翻译 } return user } } ``` --- ## 11. 初始化默认数据 ```ts protected async onDbConnected() { await this.initDefaultData('超级管理员', '内置') // 没有用户时自动创建 admin/admin // 也可以直接用 dataSource 灌业务表 const itemCrud = (this.modules.get('item') as any).dataSource if ((await itemCrud.list({ limit: 1 })).total === 0) { await itemCrud.add({ code: 'gold', name: '金币' }) } } ``` --- ## 12. 报业务错 ```ts import { ShrimpError, ShrimpCode } from '../lib/shrimp/IShrimpType' // 业务直接写中文(推荐) throw new ShrimpError('余额不足') throw new ShrimpError('账号已被封禁', ShrimpCode.FORBIDDEN) // 需要多语言或模板参数时,用对象形态 throw new ShrimpError({ t: 'myapp.notEnoughBalance', params: { need, current } }) ``` 框架自动把 `ShrimpError.tip`(`ILabel`)透传给前端,前端按 `ILabel` 形态解析:string 字面输出,`{t}` 走 i18n。 --- ## 13. 用全局 options 复用枚举 ```ts class MyAdmin extends ShrimpServer { constructor(...) { super(...) this.globalOptions['gameType'] = [ { label: 'shrimp.gameA', value: 'A' }, { label: 'shrimp.gameB', value: 'B' }, ] } } ``` 字段引用: ```ts { key: 'game', label: 'task.game', type: 'select', options: 'gameType' } ``` `/me` 只下发当前用户能访问的模块用到的 options key,自动去重。 --- ## 14. 常见踩坑 - **`relation.moduleKey` 必须能在 crudRegistry 找到。** 如果改成了非默认数据源,确认 `(dataSource as any).model` 存在,否则自动 populate 不生效。 - **`searchable` 只对字符串型字段生效。** 关键词搜索走 LIKE,数字/布尔字段加了也没用,要做精确筛选用 `filterable`。 - **`editable: 'addOnly'` 字段在编辑时直接被 `prepareEditItem` 丢弃。** 不需要前端自己处理。 - **嵌套模块也走 `Shrimp.call` 递归。** URL `/admin-api/parent/child/event` 会自动逐层路由。`getModuleInfo` 会扁平输出所有有权限的模块(含子模块),子模块通过 `parent` 字段关联,详见第 9 节。 - **子模块 moduleKey 在前端是全局查找的。** 扁平 `moduleInfo` 通过 `find(m.moduleKey === key)` 定位,如果不同主模块下挂同名子模块(`config`、`detail` 这种通用名容易撞),会找到第一个匹配项导致字段/RPC 错位。子模块名**建议带主模块前缀或语义化命名**(如 `pointDrops` 而非 `config`)。 - **`ShrimpModule` 身兼三职:RPC 容器 / 权限节点 / 纯 UI 导航占位。** 当前子模块允许完全没有 `addEvent`,只作为导航锚点和权限节点存在(如 `pointDrops`,所有数据操作走主模块 API)。如果子模块需要独立的列表/操作,改用 `ShrimpTableModule` 并 `initCrud()`。 - **`add` 当前返回 Mongoose Document 包装(含 `_doc`、`$__`)而非 lean 对象。** 这是 `MongoShrimpCrud.add` 的预存行为,前端通常只看 `_id`。