init: 从 cs-hand/hand-server-2/lib/shrimp 抽出独立仓

- 6 个框架源文件搬到 src/, 加 src/index.ts barrel 作为公共 API 入口
- package.json 标 private, main/types 指 src/index.ts (ts-node 消费方编译)
- 加 vitest + 22 条单元测试 (ILabel / MemoryShrimpCrud) 全通过
- examples/basic-admin/ 用 MemoryShrimpCrud 跑零 Mongo 依赖 demo

待办: ShrimpServer 强耦合 Mongo+JWT+Express, crudRegistry 用
.model 判断数据源, 这两个问题在 demo 中已暴露, 计划后续重构补到 90 分。
This commit is contained in:
2026-05-23 15:07:55 +08:00
commit 8548a1760a
19 changed files with 9033 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
node_modules/
dist/
.DS_Store
*.log
.env
.env.local
coverage/
.vscode/
.idea/
+613
View File
@@ -0,0 +1,613 @@
# shrimp-server
声明式字段驱动的 Node.js 后台管理框架(Express + Mongoose + JWT)。后台只声明"表 + 字段",前端自动渲染表格、表单、搜索、菜单。
## 快速跑通(不需要 MongoDB)
```sh
git clone http://git.zeromvc.com/wc24/shrimp-server.git
cd shrimp-server
npm install
cd examples/basic-admin && npm install && npm start
# 另一窗口 curl http://localhost:3100/api/product/list -X POST -d '[{}]' -H 'content-type: application/json'
```
## 在你的项目里用
```sh
npm install git+ssh://git@git.zeromvc.com:wc24/shrimp-server.git#v0.1.0
```
```ts
import { ShrimpServer, ShrimpTableModule, MongoShrimpCrud, ShrimpFieldTypes } from "shrimp-server"
// ↓ 详见下面"想做什么"指南
```
---
# 使用指南
本文按"想做什么"组织,每个场景给你最短的可工作代码。
> 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<string, ILabel | any> } // 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<string, string> // 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<IOrder> {
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<IOrderProto>('order').ship(id)` 自动包装。
---
## 5. 改默认行为(钩子)
### 拦截新增/编辑
```ts
class UserTable extends ShrimpTableModule<IUser> {
async edit(id: string, item: Partial<IUser>) {
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<ITask> {
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<string, string> = {
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`,路由就是 `/<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=<immediate_parent_id>` — 当前页 ownerId
- `?pids=<root>,<...>,<grandparent>` — 祖先链(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>/<sub>`(嵌套层级按 parent 链拼接)
- 把对应 Vue 组件文件期望放在 `src/module/<parent>/<sub>.vue`
- `ShrimpTable` 检测 `moduleInfo.parent === currentModuleKey` 的项,在操作栏每行加一个图标按钮,点击跳到 `/<parent>/<sub>?id=<row._id>`
子模块页面通常**不需要自己的 CRUD**——它操作的是主模块的某条记录,直接调主模块 API:
```vue
<!-- src/module/matter_scheme/pointDrops.vue -->
<script setup lang="ts">
import { useRoute } from 'vue-router'
import { vueAdmin } from '@/VueAdmin'
const route = useRoute()
const api = vueAdmin.getModule<any>('matter_scheme')
const id = route.query.id as string
// await api.get(id) / api.edit(id, { ... })
</script>
```
只有当子模块需要自己的事件(如批量同步、独立列表)时,才把它做成 `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
<!-- src/module/user/operationLog.vue -->
<ShrimpTable moduleKey="operationLog" />
```
如需在某场景下手动追加额外过滤(例如二级筛选),可继续传 `:baseFilter`,它会**覆盖**用户的筛选选择,但不影响 `ownerId` 注入:
```vue
<ShrimpTable moduleKey="operationLog" :baseFilter="{ success: false }" />
```
#### 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. 完整接入示例
参考本仓库:
- [examples/basic-admin/index.ts](examples/basic-admin/index.ts) — 零 Mongo 依赖,用 MemoryShrimpCrud 跑起一个 admin
- [examples/basic-admin/README.md](examples/basic-admin/README.md) — curl 示例 + 跑法
---
## 15. 常见踩坑
- **`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`。
+52
View File
@@ -0,0 +1,52 @@
# basic-admin demo
零外部依赖的 Shrimp demo,**只用内存 CRUD,不依赖 MongoDB**。
证明:Shrimp 的核心(模块注册 / RPC dispatch / 字段配置)在没有 mongoose、没有 JWT、没有用户表的情况下也能跑。
## 起服务
从 demo 目录起(本地链 shrimp-server):
```sh
cd examples/basic-admin
npm install
npm start
```
或者从仓库根目录直接 `npm run demo`(由根 package.json 提供)。
服务起在 `http://localhost:3100`。
## 试一下
```sh
# 列商品
curl -s -X POST http://localhost:3100/api/product/list \
-H 'content-type: application/json' -d '[{}]' | jq
# 列标签
curl -s -X POST http://localhost:3100/api/tag/list \
-H 'content-type: application/json' -d '[{}]' | jq
# 新增商品
curl -s -X POST http://localhost:3100/api/product/add \
-H 'content-type: application/json' \
-d '[{"code":"P003","name":"橙子","price":4,"tagIds":[]}]' | jq
# 改某个商品
curl -s -X POST http://localhost:3100/api/product/edit \
-H 'content-type: application/json' -d '["1",{"price":99}]' | jq
# 删除商品
curl -s -X POST http://localhost:3100/api/product/delete \
-H 'content-type: application/json' -d '["1"]' | jq
```
请求体永远是参数数组,按位置传给事件 handler。
## 这个 demo 暴露了哪些 70→90 的问题
- **`Shrimp.ts:322` 的 `if ((dataSource as any).model)`** 让 MemoryShrimpCrud 不能注册到 `crudRegistry`,relation populate 自动联表对内存数据源不生效
- **没有现成的 RPC mount helper** — 这段 `app.post("/api/*splat", ...)` 应该是框架提供的,而不是 demo 里手写
- **要登录 / 鉴权要么自己写,要么用 ShrimpServer 强吃 Mongo+JWT**,中间没有"我只想要 RPC + 模块,自己接 auth"这条路径
+89
View File
@@ -0,0 +1,89 @@
/**
* Shrimp basic-admin demo
*
* 用 MemoryShrimpCrud 跑一个零依赖的 admin server,展示:
* - Shrimp 核心(模块注册 / RPC dispatch / 权限树)
* - ShrimpTableModule + MemoryShrimpCrud 的 CRUD 自动事件
* - 通过 Express 暴露成 HTTP RPC
*
* 不使用 ShrimpServer/Mongoose/JWT,刻意暴露 ShrimpServer 把太多东西耦合在
* Express+Mongo+Auth 一起的事实,作为后续重构的对照样本。
*/
import express from "express"
import {
Shrimp,
ShrimpTableModule,
MemoryShrimpCrud,
ShrimpFieldTypes,
ShrimpError,
ShrimpCode,
} from "shrimp-server"
import type { IFieldConfig, WithId } from "shrimp-server"
interface ITag { _id: string; name: string }
interface IProduct { _id: string; code: string; name: string; price: number; tagIds: string[] }
const tagFields: IFieldConfig[] = [
{ key: "name", label: "标签名", type: ShrimpFieldTypes.String, required: true, searchable: true },
]
const productFields: IFieldConfig[] = [
{ key: "code", label: "编码", type: ShrimpFieldTypes.String, required: true, editable: "addOnly" },
{ key: "name", label: "名称", type: ShrimpFieldTypes.String, required: true, searchable: true },
{ key: "price", label: "价格", type: ShrimpFieldTypes.Number, required: true },
{
key: "tagIds", label: "标签", type: ShrimpFieldTypes.Relation,
relation: { moduleKey: "tag", labelKey: "name" }, multiple: true, defaultValue: [],
},
]
async function bootstrap() {
const shrimp = new Shrimp()
const tagCrud = new MemoryShrimpCrud<WithId<ITag>>()
new ShrimpTableModule(shrimp, "tag", tagCrud, tagFields, "标签管理").initCrud()
const productCrud = new MemoryShrimpCrud<WithId<IProduct>>()
new ShrimpTableModule(shrimp, "product", productCrud, productFields, "商品管理").initCrud()
// 种子数据
const t1 = await tagCrud.add({ name: "热门" } as any)
const t2 = await tagCrud.add({ name: "促销" } as any)
await productCrud.add({ code: "P001", name: "苹果", price: 5, tagIds: [t1._id] } as any)
await productCrud.add({ code: "P002", name: "香蕉", price: 3, tagIds: [t1._id, t2._id] } as any)
const app = express()
app.use(express.json())
// 简化的 RPC dispatch: POST /api/<...path> body 是参数数组
app.post(/^\/api\/.+/, async (req, res) => {
const path = req.path.replace(/^\/api\//, "").split("/").filter(Boolean)
const args = Array.isArray(req.body) ? req.body : []
try {
const data = await shrimp.call(path, ...args)
res.json({ code: ShrimpCode.OK, data })
} catch (e: any) {
if (e instanceof ShrimpError) {
res.json({ code: e.code, tip: e.tip })
} else {
console.error(e)
res.json({ code: ShrimpCode.SERVER_ERROR, log: String(e?.message || e) })
}
}
})
const port = 3100
app.listen(port, () => {
console.log(`Shrimp basic-admin demo: http://localhost:${port}`)
console.log("")
console.log("# 试试:")
console.log(` curl -s -X POST http://localhost:${port}/api/product/list -H 'content-type: application/json' -d '[{}]' | jq`)
console.log(` curl -s -X POST http://localhost:${port}/api/tag/list -H 'content-type: application/json' -d '[{}]' | jq`)
console.log(` curl -s -X POST http://localhost:${port}/api/product/add -H 'content-type: application/json' -d '[{"code":"P003","name":"橙子","price":4,"tagIds":[]}]' | jq`)
})
}
bootstrap().catch(err => {
console.error("bootstrap failed:", err)
process.exit(1)
})
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
{
"name": "shrimp-basic-admin-example",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "tsx index.ts"
},
"dependencies": {
"shrimp-server": "file:../..",
"express": "^4.19.0"
},
"devDependencies": {
"@types/express": "^4.17.21",
"tsx": "^4.7.0",
"typescript": "^5.3.0"
}
}
+4465
View File
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
{
"name": "shrimp-server",
"version": "0.1.0",
"private": true,
"description": "Shrimp 框架后端 — 声明式字段驱动的 Node.js 管理后台框架(Express + Mongoose + JWT)",
"main": "src/index.ts",
"types": "src/index.ts",
"files": [
"src",
"README.md"
],
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit",
"demo": "tsx examples/basic-admin/index.ts"
},
"peerDependencies": {
"express": "^4 || ^5",
"mongoose": "^6 || ^7 || ^8",
"jsonwebtoken": "^8 || ^9",
"bcrypt": "^5 || ^6"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/jsonwebtoken": "^9.0.0",
"@types/bcrypt": "^5.0.0",
"@types/node": "^20.0.0",
"bcrypt": "^5.1.1",
"express": "^4.19.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.0",
"tsx": "^4.7.0",
"typescript": "^5.3.0",
"vitest": "^1.4.0"
}
}
+367
View File
@@ -0,0 +1,367 @@
/**
* Shrimp 前后端共用类型定义
* 定义错误码、协议、通用数据格式
*/
/** 业务错误码 */
export enum ShrimpCode {
OK = 0,
FAIL = 1,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
SERVER_ERROR = 500,
}
/** 业务错误 - tip 展示给用户 */
export class ShrimpError extends Error {
code: ShrimpCode
tip: ILabel
constructor(tip: ILabel, code: ShrimpCode = ShrimpCode.FAIL) {
super(extractILabelText(tip))
this.code = code
this.tip = tip
this.name = 'ShrimpError'
}
}
/** 抽取 ILabel 的字符串形态用于 Error.message / 日志(非展示) */
function extractILabelText(v: ILabel): string {
if (typeof v === 'string') return v
if (v && typeof v === 'object') {
const o = v as any
if ('t' in o) return o.t
if ('tc' in o) return o.tc
if ('d' in o) return String(o.d)
if ('n' in o) return String(o.n)
}
return '[ILabel]'
}
/** 统一响应格式 */
export interface IShrimpResponse<T = any> {
code: ShrimpCode
data?: T
tip?: ILabel // 给用户看的提示
log?: string // 给开发者看的日志
}
/** 模块信息(结构元数据,扁平表示:子模块与主模块同列,通过 parent 关联) */
export interface IModuleInfo {
moduleKey: string
events: string[]
label: ILabel
fields: IFieldConfig[]
icon?: string // 子模块跳转按钮图标(element-plus icon 名称)
parent?: string // 父模块 moduleKey;存在即为子模块(不进菜单、路径嵌套)
}
/** 登录结果(仅 token) */
export interface ILoginResult {
token: string
}
/** 当前用户信息 */
export interface IMeResult {
nickname?: string
moduleInfo: IModuleInfo[]
menuTree: IMenuItem[]
options?: Record<string, any>
}
// ============== 通用类型 ==============
/**
* 通用国际化标签 - 所有前端可见文本字段统一类型
*
* 形态:
* - string 字面量,前端原样显示
* - { t: 'i18n.key', params?: ... } 翻译(vue-i18n t)
* - { tc: 'i18n.key', count, params?: ... } 复数(vue-i18n tc)
* - { d: Date|number, format? } 日期格式化(vue-i18n d)
* - { n: number, format? } 数字/货币格式化(vue-i18n n)
* - { zh: '提交', en: 'Submit' } 内联多语言
*
* params 值本身可以是 ILabel,前端递归解析
*/
export type ILabel =
| string
| { t: string; params?: Record<string, ILabel | any> }
| { tc: string; count: number; params?: Record<string, ILabel | any> }
| { d: number | Date; format?: string }
| { n: number; format?: string }
| Record<string, string>
/** 菜单项 */
export interface IMenuItem {
name: string
icon?: string
label: ILabel // 菜单显示名称
path?: string
moduleKey?: string
children?: IMenuItem[]
}
// ============== Proto 协议定义 ==============
/** 标准 Table CRUD 协议(前端可见) */
export interface ITableProto<T> {
list(query?: IPageQuery & any): Promise<IPageResult<T>>
get(id: string): Promise<T | null>
add(item: Omit<T, '_id'>, ownerId?: string): Promise<T>
edit(id: string, item: Partial<T>): Promise<T | null>
delete(id: string): Promise<boolean>
}
/** 完整 Table 协议(后端可用,含管理操作) */
export interface ITableCrudProto<T> extends ITableProto<T> {
clear(query?: IPageQuery & any): Promise<boolean>
export(query?: IPageQuery & any): Promise<T[]>
import(data?: T[], ownerId?: string): Promise<void>
}
// ============== 预制数据模型 ==============
/** 用户 */
export interface IUser {
username: string
password: string
nickname: string
roleId: string[]
active: boolean
createdAt: number
updatedAt: number
}
/** 角色 */
export interface IRole {
name: string
description: string
isSuperAdmin: boolean
powers: string[]
createdAt: number
updatedAt: number
}
/** 操作日志 */
export interface IOperationLog {
operatorId: string | null // 操作者 userId,登录失败等场景为 null
ip: string // 来源 IP
method: string // RPC 路径,如 "user.edit"、"login"
args: string // 参数(已脱敏 + JSON.stringify + 截断)
success: boolean
errorMsg: string // success=false 时填错误信息
createdAt: number
}
/** 为数据模型注入 _id 的泛型工具类型 */
export type WithId<T> = T & { _id: string }
/** 操作者契约 - 框架层通用操作者上下文,不依赖具体用户模型 */
export interface IShrimpOperator {
userId: string
roleId: string[]
isSuperAdmin: boolean
}
/** 权限 */
export interface IShrimpPowerData {
_id: string
powerKey: string
}
// ============== 前端客户端接口 ==============
/** 底层请求函数类型 */
export type ShrimpRequestFn = (path: string[], ...args: any[]) => Promise<IShrimpResponse>
/** Shrimp 客户端接口(前端实现) */
export interface IShrimpClient {
shrimpRequest: ShrimpRequestFn
hasEvent(moduleKey: string, eventName: string): boolean
}
// ============== 字段配置 ==============
//
// 【功能说明 - 给前端】
//
// IFieldConfig 是 Shrimp 框架的动态字段配置系统。
// 后端模块定义 fields 后,前端通过 GET /me 获取 moduleInfo[].fields,
// 即可自动生成表格列、搜索栏、新增/编辑表单,无需硬编码页面结构。
//
// 注意: _id 由框架自动注入(tableHide=true), 不需要在 fields 中配置, 数据返回但表格不显示。
//
// 使用流程:
// 1. 调用 GET /me → 拿到 moduleInfo 数组
// 2. 每个 moduleInfo 包含: moduleKey(模块名), events(可调用接口), fields(字段配置)
// 3. 根据 fields 渲染:
// - 表格列: 非 hidden 且非 tableHide 的字段 → 列标题=label, 数据=key
// - 搜索栏: searchable=true 的字段 → 渲染对应类型的搜索输入
// - 表单: 非 hidden 且 editable≠"readonly" 的字段, 根据 editable 决定:
// editable="always" 或缺省 → 新增/编辑都可编辑
// editable="readonly" → 新增/编辑都不可编辑(只读,如createdAt)
// editable="addOnly" → 新增可编辑, 编辑时不可编辑(如username)
// required=true 的字段标记必填, defaultValue 填入默认值
// - 排序: sortable=true 的字段 → 表头可点击排序
//
// type 与前端控件映射建议:
// string → Input 文本框
// number → InputNumber 数字框
// boolean → Switch 开关
// date → DatePicker 日期选择器
// select → Select 下拉框, 选项由 options 提供
// textarea → Input.TextArea 多行文本
// password → Input.Password 密码框
// relation → Select 下拉框, 选项从 moduleKey 指定的模块 list 接口获取,
// 显示字段为 labelKey, 值为 _id
//
/** 字段类型(string 基础类型,前端可自由扩展自定义类型) */
export type ShrimpFieldType = string
/** 框架内置字段类型常量(前端可直接使用或在此基础上扩展) */
export const ShrimpFieldTypes = {
String: "string" as ShrimpFieldType,
Number: "number" as ShrimpFieldType,
Boolean: "boolean" as ShrimpFieldType,
Date: "date" as ShrimpFieldType,
Select: "select" as ShrimpFieldType,
Textarea: "textarea" as ShrimpFieldType,
Password: "password" as ShrimpFieldType,
Relation: "relation" as ShrimpFieldType,
Json: "json" as ShrimpFieldType,
Tab: "tab" as ShrimpFieldType,
}
/** 字段可编辑状态 */
export type FieldEditable = "always" | "readonly" | "addOnly"
/** 字段类型处理器:定义每种 type 在请求/响应时的转换、验证、默认值 */
export interface IFieldTypeHandler {
/** 请求过滤:前端提交 → 保存前转换(如密码哈希、trim) */
reqFilter?: (value: any, field: IFieldConfig, item: Record<string, any>) => any | Promise<any>
/** 响应过滤:数据库取出 → 返回前端前转换(如密码脱敏为 ***、日期格式化) */
resFilter?: (value: any, field: IFieldConfig, item: Record<string, any>) => any
/** 验证:保存前校验,返回错误 ILabel 或 null(可直接返回字面字符串、{t}、{tc} 等) */
validate?: (value: any, field: IFieldConfig, item: Record<string, any>) => ILabel | null | Promise<ILabel | null>
/** 新增时的默认值(静态值或工厂函数) */
defaultValue?: any | (() => any)
}
/** 字段配置 */
export interface IFieldConfig {
key: string // 字段名(对应数据对象的属性名)
label: ILabel // 显示名称(表格列标题、表单标签)
type: ShrimpFieldType // 字段类型(决定前端渲染哪种控件)
required?: boolean // 是否必填(表单校验)
hidden?: boolean // 数据不返回给前端
tableHide?: boolean // 表格中不显示此列,但数据仍返回(如 _id)
editable?: FieldEditable // 可编辑状态: always(默认,始终可编辑) | readonly(始终只读,如createdAt) | addOnly(仅添加可编辑,编辑时只读,如username)
searchable?: boolean // 是否可搜索(出现在搜索栏)
sortable?: boolean // 是否可排序(表头可点击排序)
filterable?: boolean // 是否可筛选(出现在筛选栏,用于 filter 精确匹配)
options?: { label: ILabel; value: any }[] | string // select 类型的可选项,或全局 options key
relation?: { // relation 类型的关联配置
moduleKey: string // 关联模块名(从该模块的 list 接口获取选项)
labelKey: string // 关联模块中用作显示的字段名
}
defaultValue?: any // 新增时的默认值(优先级高于 typeHandler.defaultValue)
multiple?: boolean // 是否支持多选(relation、select 等)
rules?: IFieldRule[] // 通用验证规则(前后端共用)
/** tab 类型专用:每个 type 对应的子字段配置 */
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
}
/** 通用验证规则(前后端共用) */
export interface IFieldRule {
required?: boolean
min?: number
max?: number
pattern?: string
message?: ILabel
}
// ============== 预制协议 ==============
/** 分页查询参数 */
export interface IPageQuery {
page?: number // 页码,从 1 开始
pageSize?: number // 每页数量,默认 ShrimpConfig.defaultPageSize
keyword?: string // 关键词搜索,按 searchable 字段模糊匹配
sortBy?: string // 排序字段(对应 field.key)
sortOrder?: 'asc' | 'desc' // 排序方向
filter?: Record<string, any> // 字段精确匹配条件(AND 关系)
ownerId?: string // 子表场景: 父记录 _id。后端按模块 ownerKey 配置翻译为 filter 注入(用户无法绕过)
}
/** Shrimp 全局配置 */
export class ShrimpConfig {
static defaultPageSize: number = 100000
}
/** 分页结果 */
export interface IPageResult<T> {
list: T[] // 当前页数据
total: number // 总记录数
page: number // 当前页码
pageSize: number // 每页数量
totalPages: number // 总页数
}
// ============== 数据源查询协议 ==============
//
// IShrimpQuery 是数据源无关的查询协议。
// ShrimpTableModule 负责将前端参数(IPageQuery)翻译为 IShrimpQuery,
// 各 ShrimpCrud 实现(MemoryCrud/MongoShrimpCrud)负责执行。
//
// 查询语义:
// WHERE (where 全部满足) AND (orWhere 至少一组满足)
// ORDER BY order
// LIMIT limit OFFSET offset
//
/** 查询条件运算符 */
export interface IShrimpCondition {
eq?: any // 精确匹配 (=)
in?: any[] // IN 查询
like?: string // 模糊匹配 (不区分大小写)
gte?: any // 大于等于 (>=)
lte?: any // 小于等于 (<=)
}
/** 判断值是否为 IShrimpCondition 对象 */
export function isShrimpCondition(val: any): val is IShrimpCondition {
return val != null && typeof val === 'object' && !Array.isArray(val)
&& ('eq' in val || 'in' in val || 'like' in val || 'gte' in val || 'lte' in val)
}
/** 关联填充指令 */
export interface IShrimpPopulate {
key: string // 当前模块的字段名 (如 roleId)
moduleKey: string // 关联模块名 (如 role)
labelKey: string // 关联模块中用作显示的字段 (如 name)
}
/** 通用查询协议 (数据源无关) */
export interface IShrimpQuery {
where?: Record<string, IShrimpCondition | any> // AND 条件 (原始值=eq简写)
orWhere?: Record<string, IShrimpCondition>[] // OR 条件组 (用于 keyword)
order?: [string, 'asc' | 'desc'][] // 排序
offset?: number // 偏移量
limit?: number // 限制数量
populate?: IShrimpPopulate[] // 关联填充 (输出 {key}_label)
}
/** 权限项 */
export interface IPowerItem {
key: string
label: ILabel
}
/** 用户模块协议 */
export interface IUserProto extends ITableCrudProto<WithId<IUser>> { }
/** 角色模块协议 */
export interface IRoleProto extends ITableCrudProto<WithId<IRole>> {
allPower(): Promise<IPowerItem[]>
}
+127
View File
@@ -0,0 +1,127 @@
import { ShrimpCrud } from './Shrimp'
import { IShrimpQuery, IShrimpCondition, IShrimpPopulate, IPageResult, isShrimpCondition } from './IShrimpType'
export class MemoryShrimpCrud<T extends { _id: string }> implements ShrimpCrud<T> {
private data: Map<string, T> = new Map()
private autoId: number = 1
/** 获取关联模块的数据源(用于 populate) */
getRelatedCrud?: (moduleKey: string) => ShrimpCrud<any> | undefined
private isCondition = isShrimpCondition
private matchCondition(item: any, key: string, cond: IShrimpCondition | any): boolean {
const v = item[key]
if (this.isCondition(cond)) {
if (cond.eq !== undefined && v !== cond.eq) return false
if (cond.in !== undefined && !cond.in.includes(v)) return false
if (cond.like !== undefined && !String(v ?? '').toLowerCase().includes(String(cond.like).toLowerCase())) return false
if (cond.gte !== undefined && v < cond.gte) return false
if (cond.lte !== undefined && v > cond.lte) return false
return true
}
return v === cond
}
async findOne(query?: any): Promise<T | null> {
if (!query) return null
for (const item of this.data.values()) {
if (Object.keys(query).every(key => (item as any)[key] === query[key])) {
return item
}
}
return null
}
async list(query?: IShrimpQuery): Promise<IPageResult<T>> {
let items = Array.from(this.data.values())
// where 条件 (AND)
if (query?.where) {
for (const [key, cond] of Object.entries(query.where)) {
items = items.filter(item => this.matchCondition(item, key, cond))
}
}
// orWhere 条件 (OR 组之间)
if (query?.orWhere && query.orWhere.length > 0) {
items = items.filter(item =>
query.orWhere!.some(group =>
Object.entries(group).every(([key, cond]) => this.matchCondition(item, key, cond))
)
)
}
const total = items.length
// 排序
if (query?.order) {
for (const [key, dir] of query.order) {
const d = dir === 'desc' ? -1 : 1
items.sort((a, b) => {
const va = (a as any)[key], vb = (b as any)[key]
if (va == null && vb == null) return 0
if (va == null) return 1
if (vb == null) return -1
if (va < vb) return -d
if (va > vb) return d
return 0
})
}
}
// 分页
const offset = query?.offset || 0
const limit = query?.limit ?? items.length
const list = items.slice(offset, offset + limit)
const page = Math.floor(offset / limit) + 1
const pageSize = limit
const totalPages = Math.ceil(total / pageSize)
return { list, total, page, pageSize, totalPages }
}
async populateItems(items: any[], populates: IShrimpPopulate[]): Promise<void> {
for (const pop of populates) {
const relatedCrud = this.getRelatedCrud?.(pop.moduleKey)
if (!relatedCrud) continue
const allRelated = (await relatedCrud.list({})).list
const labelMap = new Map(allRelated.map(item => [String(item._id), (item as any)[pop.labelKey]]))
for (const item of items) {
const val = (item as any)[pop.key]
if (Array.isArray(val)) {
(item as any)[`${pop.key}_label`] = val.map((id: any) => labelMap.get(String(id)) ?? null)
} else if (val != null) {
(item as any)[`${pop.key}_label`] = labelMap.get(String(val)) ?? null
}
}
}
}
async get(id: string): Promise<T | null> {
return this.data.get(id) || null
}
async add(item: Omit<T, '_id'>): Promise<T> {
const id = (this.autoId++).toString()
const newItem = { _id: id, ...item } as T
this.data.set(id, newItem)
return newItem
}
async edit(id: string, item: Partial<T>): Promise<T | null> {
const old = this.data.get(id)
if (!old) return null
const updated = { ...old, ...item }
this.data.set(id, updated)
return updated
}
async delete(id: string): Promise<boolean> {
return this.data.delete(id)
}
async clear(): Promise<boolean> {
this.data.clear()
return true
}
}
+130
View File
@@ -0,0 +1,130 @@
import { Types, Model, FilterQuery } from 'mongoose';
import { ShrimpCrud } from './Shrimp';
import { IShrimpQuery, IShrimpCondition, IShrimpPopulate, IPageResult, ShrimpConfig, isShrimpCondition } from './IShrimpType';
export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
constructor(private model: Model<any>) { }
/** 获取关联模块的 Mongoose Model(用于 populate / $lookup) */
getRelatedModel?: (moduleKey: string) => Model<any> | undefined
/** 判断值是否为 IShrimpCondition 对象 */
private isCondition = isShrimpCondition
/** 将 IShrimpCondition 翻译为 MongoDB 查询片段 */
private translateCondition(cond: IShrimpCondition | any): any {
if (!this.isCondition(cond)) return cond // 简写: 原始值 = eq
const q: any = {}
if (cond.eq !== undefined) q.$eq = cond.eq
if (cond.in !== undefined) q.$in = cond.in
if (cond.like !== undefined) q.$regex = cond.like, q.$options = 'i'
if (cond.gte !== undefined) q.$gte = cond.gte
if (cond.lte !== undefined) q.$lte = cond.lte
return q
}
/** 将 IShrimpQuery 翻译为 Mongoose 查询 */
private buildMongooseQuery(query?: IShrimpQuery): { filter: FilterQuery<T>, sort: any, skip: number, limit: number } {
const filter: FilterQuery<T> = {}
// where → AND 条件
if (query?.where) {
for (const [key, cond] of Object.entries(query.where)) {
(filter as any)[key] = this.translateCondition(cond)
}
}
// orWhere → $or
if (query?.orWhere && query.orWhere.length > 0) {
filter.$or = query.orWhere.map(group => {
const obj: any = {}
for (const [key, cond] of Object.entries(group)) {
obj[key] = this.translateCondition(cond)
}
return obj
})
}
// 排序
const sort: any = {}
if (query?.order) {
for (const [key, dir] of query.order) {
sort[key] = dir === 'desc' ? -1 : 1
}
}
return {
filter,
sort,
skip: query?.offset || 0,
limit: query?.limit ?? ShrimpConfig.defaultPageSize,
}
}
async list(query?: IShrimpQuery): Promise<IPageResult<T>> {
const { filter, sort, skip, limit } = this.buildMongooseQuery(query)
const [docs, total] = await Promise.all([
this.model.find(filter).sort(sort).skip(skip).limit(limit).lean(),
this.model.countDocuments(filter),
])
const page = Math.floor(skip / limit) + 1
const totalPages = Math.ceil(total / limit)
return { list: docs, total, page, pageSize: limit, totalPages }
}
async populateItems(items: any[], populates: IShrimpPopulate[], crudRegistry?: Map<string, any>): Promise<void> {
for (const pop of populates) {
// 优先用 getRelatedModel,其次用 crudRegistry(自动解析 relation)
let relatedModel = this.getRelatedModel?.(pop.moduleKey)
if (!relatedModel && crudRegistry) {
const relatedCrud = crudRegistry.get(pop.moduleKey) as any
relatedModel = relatedCrud?.model
}
if (!relatedModel) continue
const allRefIds = new Set<string>()
for (const item of items) {
const val = (item as any)[pop.key]
if (Array.isArray(val)) {
val.forEach((id: any) => { if (id != null) allRefIds.add(String(id)) })
} else if (val != null) {
allRefIds.add(String(val))
}
}
if (allRefIds.size === 0) continue
const docs = await relatedModel.find({ _id: { $in: Array.from(allRefIds) } }).select(`${pop.labelKey} _id`)
const labelMap = new Map(docs.map(doc => [String(doc._id), (doc as any)[pop.labelKey]]))
for (const item of items) {
const val = (item as any)[pop.key]
if (Array.isArray(val)) {
(item as any)[`${pop.key}_label`] = val.map((id: any) => labelMap.get(String(id)) ?? null)
} else if (val != null) {
(item as any)[`${pop.key}_label`] = labelMap.get(String(val)) ?? null
}
}
}
}
async findOne(query?: any): Promise<T | null> {
return await this.model.findOne(query || {}).lean() as T | null
}
async get(id: string): Promise<T | null> {
return await this.model.findById(id).lean() as T | null;
}
async add(item: Omit<T, '_id'>): Promise<T> {
return await this.model.create(item);
}
async edit(id: string, item: Partial<T>): Promise<T | null> {
return await this.model.findByIdAndUpdate(id, item, { new: true });
}
async delete(id: string): Promise<boolean> {
const result = await this.model.findByIdAndDelete(id);
return !!result;
}
async clear(): Promise<boolean> {
await this.model.deleteMany({});
return true;
}
}
+89
View File
@@ -0,0 +1,89 @@
/**
* OperationLogModule
* 操作日志子表 - 挂在 userModule 下,记录"某用户做了什么"
* - 默认只记 mutation(add/edit/delete/clear/import) + login
* - args 自动脱敏(password/pwd/token/secret → "***") + JSON.stringify + 截断到 2000 字符
* - 日志失败不影响主调用
* - 只暴露 list/get,不开 add/edit/delete 防止误改
*/
import { ShrimpModule, ShrimpTableModule, ShrimpCrud } from "./Shrimp"
import { Shrimp } from "./Shrimp"
import { IFieldConfig, IOperationLog, WithId, ILabel } from "./IShrimpType"
const SENSITIVE_KEY_RE = /(password|pwd|token|secret)/i
const ARGS_MAX_LEN = 2000
// operatorId 是子表→父记录(user)的外键,纯数据库字段,不进 fields(框架按 ownerKey 自动注入 filter)
const operationLogFields: IFieldConfig[] = [
{ key: "ip", label: { t: "operationLog.ip" }, type: "string", searchable: true, editable: "readonly" },
{ key: "method", label: { t: "operationLog.method" }, type: "string", searchable: true, filterable: true, editable: "readonly" },
{ key: "args", label: { t: "operationLog.args" }, type: "textarea", editable: "readonly" },
{ key: "success", label: { t: "operationLog.success" }, type: "boolean", filterable: true, editable: "readonly" },
{ key: "errorMsg", label: { t: "operationLog.errorMsg" }, type: "string", editable: "readonly" },
{ key: "createdAt", label: { t: "operationLog.createdAt" }, type: "date", editable: "readonly", sortable: true, filterable: true },
]
export class OperationLogModule extends ShrimpTableModule<WithId<IOperationLog>> {
/** 触发记录的事件名集合,可被外部 add/delete 扩展 */
logEvents: Set<string> = new Set(['add', 'edit', 'delete', 'clear', 'import', 'login'])
constructor(parent: Shrimp | ShrimpModule, dataSource: ShrimpCrud<WithId<IOperationLog>>, fields?: IFieldConfig[], label?: ILabel) {
super(parent, "operationLog", dataSource, fields || operationLogFields, label || { t: "user.operationLog" }, undefined, {
icon: "Tickets",
// 声明 operatorId 是父记录(user)的归属字段,框架据此自动做子表过滤
ownerKey: "operatorId",
})
// 只挂只读事件 — 不暴露 add/edit/delete,防止外部改日志
this.addEvent("list", this.power)
this.addEvent("get", this.power)
}
/** 路径最后一段在 logEvents 内,且不是 operationLog 自身的调用(防递归) */
shouldLog(path: string[]): boolean {
if (path.length === 0) return false
if (path.includes('operationLog')) return false
const last = path[path.length - 1]
return this.logEvents.has(last)
}
/** 深度遍历替换敏感字段值,再 JSON.stringify 并截断 */
sanitizeArgs(args: any[]): string {
const walk = (val: any): any => {
if (val == null) return val
if (Array.isArray(val)) return val.map(walk)
if (typeof val === 'object') {
const out: Record<string, any> = {}
for (const [k, v] of Object.entries(val)) {
out[k] = SENSITIVE_KEY_RE.test(k) ? '***' : walk(v)
}
return out
}
return val
}
let str: string
try {
str = JSON.stringify(walk(args))
} catch {
str = '[unserializable]'
}
return str.length > ARGS_MAX_LEN ? str.substring(0, ARGS_MAX_LEN) + '...' : str
}
/** 写一条日志,内部吞错(日志失败不能搞挂主流程)。operatorId 强制 String 化,避免 ObjectId 与字符串查询不匹配 */
async record(operatorId: any, ip: string, path: string[], args: any[], success: boolean, errorMsg: string = ''): Promise<void> {
try {
await this.dataSource.add({
operatorId: operatorId == null ? null : String(operatorId),
ip,
method: path.join('.'),
args: this.sanitizeArgs(args),
success,
errorMsg,
createdAt: Date.now(),
} as Omit<WithId<IOperationLog>, '_id'>)
} catch (e: any) {
console.warn('[OperationLog] record failed', e?.message || e)
}
}
}
+870
View File
@@ -0,0 +1,870 @@
/**
* Shrimp
* 后台管理系统快速开发框架
*/
import { ShrimpCode, IShrimpResponse, ITableCrudProto, IModuleInfo, IUser, IRole, WithId, IRoleProto, IPageQuery, IPageResult, IFieldConfig, IFieldRule, IFieldTypeHandler, IShrimpQuery, IShrimpCondition, IShrimpPopulate, ShrimpConfig, IShrimpOperator, IMenuItem, ShrimpError, ShrimpFieldTypes, ILabel } from "./IShrimpType"
import * as bcrypt from "bcrypt"
import { AsyncLocalStorage } from 'async_hooks'
export class Shrimp {
root: Shrimp = this
modules: Map<string, ShrimpModule> = new Map()
/** 全局 CRUD 注册表,用于 MongoShrimpCrud 自动解析 relation */
crudRegistry: Map<string, ShrimpCrud<any>> = new Map()
/** 请求级操作者上下文,通过 AsyncLocalStorage 避免并发覆盖 */
static asyncLocalStorage = new AsyncLocalStorage<IShrimpOperator | null>()
get operator(): IShrimpOperator | null {
return Shrimp.asyncLocalStorage.getStore() ?? null
}
async call(path: string[], ...args: any[]): Promise<any> {
let module = this.modules.get(path[0])
if (module == null) {
throw new Error(`Module "${path[0]}" not found`)
}
return await module.call(path.slice(1), ...args)
}
checkEvent(powers: Set<string>, path: string[]): boolean {
let module = this.modules.get(path[0])
if (module == null) return false
return module.checkEvent(powers, path.slice(1))
}
getModuleInfo(powers: Set<string>): IModuleInfo[] {
const list: IModuleInfo[] = []
this.collectModuleInfo(this.modules, powers, undefined, list)
return list
}
private collectModuleInfo(modules: Map<string, ShrimpModule>, powers: Set<string>, parent: string | undefined, out: IModuleInfo[]) {
modules.forEach(module => {
if (!powers.has(module.power.key)) return
const info: IModuleInfo = {
moduleKey: module.moduleKey,
events: module.getEventInfo(powers),
label: module.label,
fields: module instanceof ShrimpTableModule ? module.getFields() : [],
}
if (module.icon) info.icon = module.icon
if (parent) info.parent = parent
out.push(info)
if (module.modules.size > 0) {
this.collectModuleInfo(module.modules, powers, module.moduleKey, out)
}
})
}
/** 成功响应 */
success<T>(data: T, tip?: ILabel, log?: string): IShrimpResponse<T> {
const r: IShrimpResponse<T> = { code: ShrimpCode.OK, data }
if (tip) r.tip = tip
if (log) r.log = log
return r
}
/** 失败响应 */
fail<T = any>(code: ShrimpCode, tip?: ILabel, log?: string): IShrimpResponse<T> {
const r: IShrimpResponse<T> = { code }
if (tip) r.tip = tip
if (log) r.log = log
return r
}
async allPower(): Promise<{ key: string; label: ILabel }[]> {
const powers: { key: string; label: ILabel }[] = []
const collect = (module: any) => {
// 模块权限
powers.push({ key: module.power.key, label: module.power.label })
// 事件权限(children 已有 key 和 label)
powers.push(...module.power.children)
// 递归子模块
module.modules.forEach(collect)
}
this.root.modules.forEach(collect)
// 去重
const map = new Map<string, ILabel>()
powers.forEach(p => map.set(p.key, p.label))
return Array.from(map.entries()).map(([key, label]) => ({ key, label }))
}
/** 菜单树,默认平铺所有模块,子类可覆盖为分组结构 */
getMenuTree(): IMenuItem[] {
const items: IMenuItem[] = []
this.modules.forEach(module => {
items.push({
name: module.moduleKey,
label: { t: module.moduleKey + '.menuManage' },
moduleKey: module.moduleKey
})
})
return items
}
/** 根据权限过滤菜单树(递归处理 children;children 全部被过滤后,分组节点也一并剔除) */
filterMenuTree(fullMenuTree: IMenuItem[], rolePower: string[]): IMenuItem[] {
const allowedModules = new Set(rolePower.map(p => p.split('.')[0]))
const filter = (nodes: IMenuItem[]): IMenuItem[] => {
const result: IMenuItem[] = []
for (const node of nodes) {
if (node.moduleKey) {
if (allowedModules.has(node.moduleKey)) {
result.push(node)
}
continue
}
if (!node.children || node.children.length === 0) {
continue
}
const filteredChildren = filter(node.children)
if (filteredChildren.length === 0) continue
result.push({ ...node, children: filteredChildren })
}
return result
}
return filter(fullMenuTree)
}
}
type ShrimpEventHandler = (...args: any[]) => Promise<any>
export class ShrimpEvent {
constructor(public name: string, public handler: ShrimpEventHandler, public power: RootShrimpPower) {
}
}
export interface IShrimpModuleOptions {
icon?: string // 前端子模块跳转按钮图标(element-plus icon 名)
ownerKey?: string // 子表→父记录归属字段名(子模块专用,语义: 主人/上级/归属)。前端据此自动过滤和回填默认值
}
export class ShrimpModule<P extends Record<string, any> = Record<string, any>> {
power: RootShrimpPower
root: Shrimp
modules: Map<string, ShrimpModule> = new Map()
events: Map<string, ShrimpEvent> = new Map()
icon?: string
ownerKey?: string
constructor(public parent: Shrimp | ShrimpModule, public moduleKey: string, public label: ILabel, power?: RootShrimpPower, options?: IShrimpModuleOptions) {
if (power == null) {
if (parent instanceof Shrimp) {
power = new RootShrimpPower(moduleKey, label)
}
else {
power = new ShrimpPower(parent.power, moduleKey, label)
}
}
this.power = power
this.icon = options?.icon
this.ownerKey = options?.ownerKey
parent.modules.set(this.moduleKey, this)
this.root = parent.root
}
addEvent<K extends keyof P & string>(name: K, label: ILabel): this
addEvent<K extends keyof P & string>(name: K, power: RootShrimpPower): this
addEvent<K extends keyof P & string>(name: K, powerOrLabel: RootShrimpPower | ILabel) {
const handler = (this as any)[name]
if (typeof handler !== 'function') {
throw new Error(`Method "${name}" not found on ${this.moduleKey}`)
}
let power: RootShrimpPower
if (powerOrLabel instanceof RootShrimpPower) {
power = powerOrLabel
} else {
power = new ShrimpPower(this.power, name, powerOrLabel)
}
this.events.set(name, new ShrimpEvent(name, handler.bind(this), power))
return this
}
async call(path: string[], ...args: any[]): Promise<any> {
if (path.length > 1) {
let module = this.modules.get(path[0])
if (module == null) {
throw new Error(`Module "${path[0]}" not found`)
}
return await module.call(path.slice(1), ...args)
} else {
const event = this.events.get(path[0])
if (event == null) {
throw new Error(`Event "${path[0]}" not found`)
}
return await event.handler(...args)
}
}
getEventInfo(powers: Set<string>): string[] {
let events: string[] = []
this.events.forEach(event => {
if (powers.has(event.power.key)) {
events.push(event.name)
}
})
return events
}
checkEvent(powers: Set<string>, path: string[]): boolean {
if (path.length > 1) {
let module = this.modules.get(path[0])
if (module == null) return false
return module.checkEvent(powers, path.slice(1))
} else {
const event = this.events.get(path[0])
if (event == null) return false
return powers.has(event.power.key)
}
}
}
export class RootShrimpPower {
children: ShrimpPower[] = []
constructor(public powerKey: string, public label: ILabel) {
}
get key(): string {
return this.powerKey
}
}
export class ShrimpPower extends RootShrimpPower {
constructor(public parent: RootShrimpPower, public powerKey: string, public label: ILabel) {
super(powerKey, label)
parent.children.push(this)
}
get key(): string {
return this.parent.key + "." + this.powerKey
}
}
// CRUD 接口
export interface ShrimpCrud<T> {
findOne(query?: any): Promise<T | null>
list(query?: IShrimpQuery): Promise<IPageResult<T>>
get(id: string): Promise<T | null>
add(item: Omit<T, '_id'>): Promise<T>
edit(id: string, item: Partial<T>): Promise<T | null>
delete(id: string): Promise<boolean>
clear(): Promise<boolean>
/** 为记录填充关联 _label 字段 */
populateItems(items: any[], populates: IShrimpPopulate[], crudRegistry?: Map<string, ShrimpCrud<any>>): Promise<void>
}
/** 内置字段类型处理器 */
export const defaultTypeHandlers: Record<string, IFieldTypeHandler> = {
[ShrimpFieldTypes.Password]: {
reqFilter: async (value) => {
if (typeof value === 'string' && value.length > 0) {
return bcrypt.hash(value, 10)
}
return value
},
resFilter: () => "***",
},
[ShrimpFieldTypes.Date]: {
defaultValue: () => Date.now(),
},
[ShrimpFieldTypes.Number]: {
defaultValue: 0,
},
[ShrimpFieldTypes.Boolean]: {
defaultValue: false,
},
[ShrimpFieldTypes.Json]: {
reqFilter: (value) => {
if (value == null || value === "") return undefined
if (typeof value === "string") {
try {
return JSON.parse(value)
} catch {
throw new ShrimpError({ t: 'shrimp.invalidJson' })
}
}
return value
},
resFilter: (value) => {
if (value == null) return value
if (typeof value === "object") {
return JSON.stringify(value)
}
return value
},
},
[ShrimpFieldTypes.Tab]: {
reqFilter: (value) => {
if (value == null || value === "") return undefined
if (typeof value === "string") {
try {
return JSON.parse(value)
} catch {
throw new ShrimpError({ t: 'shrimp.invalidJson' })
}
}
return value
},
resFilter: (value) => {
if (value == null) return value
if (typeof value === "object") {
return JSON.stringify(value)
}
return value
},
},
}
export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto<T>> extends ShrimpModule<P> implements ITableCrudProto<T> {
fields: IFieldConfig[] = []
constructor(public parent: Shrimp | ShrimpModule, moduleKey: string, public dataSource: ShrimpCrud<T>, fields?: IFieldConfig[], label?: ILabel, power?: RootShrimpPower, options?: IShrimpModuleOptions) {
super(parent, moduleKey, label || { t: moduleKey }, power, options)
if (fields) {
this.fields = fields
}
// 自动注册 CRUD 到 root.crudRegistry,供 MongoShrimpCrud.populateItems 自动解析 relation
if ((dataSource as any).model) {
this.root.crudRegistry.set(moduleKey, dataSource)
}
}
getFields(): IFieldConfig[] {
return this.fields
}
static typeHandlers: Map<string, IFieldTypeHandler> = new Map(Object.entries(defaultTypeHandlers))
static registerTypeHandler(type: string, handler: IFieldTypeHandler) {
this.typeHandlers.set(type, handler)
}
private getTypeHandler(field: IFieldConfig): IFieldTypeHandler | undefined {
return ShrimpTableModule.typeHandlers.get(field.type)
}
/** 前置验证:基于 IFieldConfig 的通用校验 */
private async validateField(field: IFieldConfig, value: any, item: Record<string, any>): Promise<ILabel | null> {
const isEmpty = value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)
// 1. required
if (field.required && isEmpty) {
return field.rules?.find(r => r.required)?.message || { t: 'shrimp.fieldRequired', params: { field: field.label } }
}
if (isEmpty) return null
// 2. options 校验
if (Array.isArray(field.options)) {
const validValues = new Set(field.options.map(o => o.value))
const values = field.multiple && Array.isArray(value) ? value : [value]
for (const v of values) {
if (!validValues.has(v)) {
return field.rules?.find(r => r.message)?.message || { t: 'shrimp.fieldInvalid', params: { field: field.label } }
}
}
}
// 3. type 基础校验
switch (field.type) {
case ShrimpFieldTypes.String:
if (typeof value !== 'string') return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
case ShrimpFieldTypes.Number:
if (typeof value !== 'number' || Number.isNaN(value)) return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
case ShrimpFieldTypes.Boolean:
if (typeof value !== 'boolean') return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
case ShrimpFieldTypes.Date:
if (typeof value !== 'number' && !(value instanceof Date) && isNaN(Date.parse(value))) {
return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
}
break
}
// 4. rules 校验
if (field.rules) {
for (const rule of field.rules) {
const msg = rule.message || { t: 'shrimp.fieldInvalid', params: { field: field.label } }
if (rule.min !== undefined) {
if (typeof value === 'number' && value < rule.min) return { t: 'shrimp.fieldMin', params: { field: field.label, min: rule.min } }
if (typeof value === 'string' && value.length < rule.min) return { t: 'shrimp.fieldMinLength', params: { field: field.label, min: rule.min } }
if (Array.isArray(value) && value.length < rule.min) return { t: 'shrimp.fieldMinLength', params: { field: field.label, min: rule.min } }
}
if (rule.max !== undefined) {
if (typeof value === 'number' && value > rule.max) return { t: 'shrimp.fieldMax', params: { field: field.label, max: rule.max } }
if (typeof value === 'string' && value.length > rule.max) return { t: 'shrimp.fieldMaxLength', params: { field: field.label, max: rule.max } }
if (Array.isArray(value) && value.length > rule.max) return { t: 'shrimp.fieldMaxLength', params: { field: field.label, max: rule.max } }
}
if (rule.pattern) {
const regex = new RegExp(rule.pattern)
if (!regex.test(String(value))) return msg
}
}
}
return null
}
/** 准备新增数据:过滤 readonly → 默认值 → reqFilter → validate */
private async prepareAddItem(item: Record<string, any>): Promise<Record<string, any>> {
const result = { ...item }
for (const field of this.fields) {
if (field.editable === "readonly") {
delete result[field.key]
continue
}
const handler = this.getTypeHandler(field)
if (result[field.key] === undefined) {
const dv = field.defaultValue !== undefined ? field.defaultValue : handler?.defaultValue
if (dv !== undefined) {
result[field.key] = typeof dv === 'function' ? (dv as () => any)() : dv
}
}
if (handler?.reqFilter && result[field.key] !== undefined) {
result[field.key] = await handler.reqFilter(result[field.key], field, result)
}
const fieldErr = await this.validateField(field, result[field.key], result)
if (fieldErr) throw new ShrimpError(fieldErr)
if (handler?.validate && result[field.key] !== undefined) {
const err = await handler.validate(result[field.key], field, result)
if (err) throw new ShrimpError(err)
}
}
return result
}
/** 准备编辑数据:过滤 readonly/addOnly → reqFilter → validate */
private async prepareEditItem(item: Record<string, any>): Promise<Record<string, any>> {
const result = { ...item }
for (const field of this.fields) {
if (field.editable === "readonly" || field.editable === "addOnly") {
delete result[field.key]
continue
}
// 编辑时 undefined 表示未修改,跳过校验并从结果中移除
if (result[field.key] === undefined) {
delete result[field.key]
continue
}
const handler = this.getTypeHandler(field)
if (handler?.reqFilter) {
result[field.key] = await handler.reqFilter(result[field.key], field, result)
}
const fieldErr = await this.validateField(field, result[field.key], result)
if (fieldErr) throw new ShrimpError(fieldErr)
if (handler?.validate) {
const err = await handler.validate(result[field.key], field, result)
if (err) throw new ShrimpError(err)
}
}
return result
}
/** 处理响应数据:resFilter */
private async processResItem(item: Record<string, any>): Promise<Record<string, any>> {
const result = { ...item }
for (const field of this.fields) {
const handler = this.getTypeHandler(field)
if (handler?.resFilter && result[field.key] !== undefined) {
result[field.key] = await handler.resFilter(result[field.key], field, result)
}
}
return result
}
/** 填充关联 _label 并应用 resFilter(多条) */
private async prepareResponseItems(items: any[]): Promise<any[]> {
if (items.length === 0) return items
const populates = this.getRelationPopulates()
if (populates.length > 0 && this.dataSource.populateItems) {
await this.dataSource.populateItems(items, populates, this.root.crudRegistry)
}
return Promise.all(items.map(item => this.processResItem(item)))
}
/** 填充关联 _label 并应用 resFilter(单条) */
private async prepareResponseItem(item: any): Promise<any> {
if (!item) return item
const populates = this.getRelationPopulates()
if (populates.length > 0 && this.dataSource.populateItems) {
await this.dataSource.populateItems([item], populates, this.root.crudRegistry)
}
return this.processResItem(item)
}
private excludeKeys(item: any, keys: string[]): any {
if (keys.length === 0) return item
const result = { ...item }
for (const key of keys) {
delete result[key]
}
return result
}
private filterHidden(item: any): any {
return this.excludeKeys(item, this.fields.filter(f => f.hidden).map(f => f.key))
}
private getRelationFields(): IFieldConfig[] {
return this.fields.filter(f => f.type === "relation" && f.relation)
}
private getRelationPopulates(): IShrimpPopulate[] {
return this.getRelationFields().map(f => ({
key: f.key,
moduleKey: f.relation!.moduleKey,
labelKey: f.relation!.labelKey,
}))
}
/** 将前端 IPageQuery 翻译为数据源 IShrimpQuery */
private buildQuery(query?: IPageQuery & any): IShrimpQuery {
const { keyword, page, pageSize, sortBy, sortOrder, filter, ownerId } = query || {}
const p = page || 1
const ps = pageSize || ShrimpConfig.defaultPageSize
const shrimpQuery: IShrimpQuery = {
offset: (p - 1) * ps,
limit: ps,
}
// filter → where
if (filter && typeof filter === 'object') {
const filterableFields = new Map(this.fields.filter(f => f.filterable).map(f => [f.key, f]))
const stringLikeTypes = new Set(['string', 'textarea'])
const where: Record<string, IShrimpCondition> = {}
for (const [key, value] of Object.entries(filter)) {
const field = filterableFields.get(key)
if (!field) continue
if (value == null) continue
if (Array.isArray(value) && value.length === 0) continue
if (typeof value === 'string' && value === '') continue
const obj = value as any
if (typeof obj === 'object' && !Array.isArray(obj) && obj.min === undefined && obj.max === undefined) continue
if (Array.isArray(value)) {
where[key] = { in: value }
} else if (typeof value === 'object') {
const cond: IShrimpCondition = {}
if (obj.min !== undefined) cond.gte = obj.min
if (obj.max !== undefined) cond.lte = obj.max
where[key] = cond
} else if (typeof value === 'boolean') {
where[key] = { eq: value }
} else if (typeof value === 'string' && stringLikeTypes.has(field.type)) {
where[key] = { like: value }
} else {
where[key] = { eq: value }
}
}
if (Object.keys(where).length > 0) shrimpQuery.where = where
}
// 子表场景: ownerId + 模块 ownerKey 配置 → 强制注入过滤(用户无法绕过)
if (ownerId != null && ownerId !== '' && this.ownerKey) {
shrimpQuery.where = shrimpQuery.where || {}
shrimpQuery.where[this.ownerKey] = { eq: ownerId }
}
// keyword → orWhere(仅对字符串类型字段做模糊匹配)
if (keyword) {
const stringLikeTypes = new Set(['string', 'textarea'])
const searchFields = this.fields
.filter(f => f.searchable && stringLikeTypes.has(f.type))
.map(f => f.key)
if (searchFields.length > 0) {
shrimpQuery.orWhere = searchFields.map(key => ({ [key]: { like: keyword } }))
}
}
// 排序
if (sortBy) {
shrimpQuery.order = [[sortBy, sortOrder === 'desc' ? 'desc' : 'asc']]
}
return shrimpQuery
}
async list(query?: IPageQuery & any): Promise<IPageResult<T>> {
const shrimpQuery = this.buildQuery(query)
const result = await this.dataSource.list(shrimpQuery)
result.list = await this.prepareResponseItems(result.list)
result.list = result.list.map(item => this.filterHidden(item))
return result
}
async get(id: string): Promise<T | null> {
const item = await this.dataSource.get(id)
if (item) {
const processed = await this.prepareResponseItem(item)
return this.filterHidden(processed) as T
}
return item
}
async add(item: Omit<T, '_id'>, ownerId?: string): Promise<T> {
if (ownerId && this.ownerKey) {
(item as any)[this.ownerKey] = ownerId
}
const prepared = await this.prepareAddItem(item as any)
const result = await this.dataSource.add(prepared as Omit<T, '_id'>)
const processed = await this.prepareResponseItem(result)
return this.filterHidden(processed) as T
}
async edit(id: string, item: Partial<T>): Promise<T | null> {
const prepared = await this.prepareEditItem(item as any)
const result = await this.dataSource.edit(id, prepared as Partial<T>)
if (result) {
const processed = await this.prepareResponseItem(result)
return this.filterHidden(processed) as T
}
return result
}
async delete(id: string): Promise<boolean> {
return await this.dataSource.delete(id)
}
async clear(query?: IPageQuery & any): Promise<boolean> {
const hasFilter = query && (
(query.keyword) ||
(query.filter && typeof query.filter === 'object' && Object.keys(query.filter).length > 0)
)
if (hasFilter) {
const shrimpQuery = this.buildQuery(query)
delete shrimpQuery.offset
delete shrimpQuery.limit
const result = await this.dataSource.list(shrimpQuery)
for (const item of result.list as any[]) {
await this.dataSource.delete(item._id)
}
return true
}
return await this.dataSource.clear()
}
async export(query?: IPageQuery & any): Promise<T[]> {
const shrimpQuery = this.buildQuery(query)
delete shrimpQuery.offset
delete shrimpQuery.limit
const result = await this.dataSource.list(shrimpQuery)
result.list = await this.prepareResponseItems(result.list)
return result.list.map(item => this.filterHidden(item))
}
async import(data?: T[], ownerId?: string): Promise<void> {
if (!data || data.length === 0) return
for (const raw of data) {
const item = { ...raw } as Record<string, any>
if (ownerId && this.ownerKey) item[this.ownerKey] = ownerId
const id = item._id ? String(item._id) : undefined
if (id) {
// 有 _id 且数据库里已存在 → 编辑覆盖
const existing = await this.dataSource.get(id)
if (existing) {
const prepared = await this.prepareEditItem(item)
await this.dataSource.edit(id, prepared as Partial<T>)
continue
}
}
// 无 _id,或 _id 在库里找不到 → 当作新增
const prepared = await this.prepareAddItem(item)
await this.dataSource.add(prepared as Omit<T, '_id'>)
}
}
initCrud() {
return this
.addEvent("list", this.power)
.addEvent("get", this.power)
.addEvent("add", { t: "power.add" })
.addEvent("edit", { t: "power.edit" })
.addEvent("delete", { t: "power.delete" })
}
}
/** 用户模块扩展 - 添加登录和获取用户信息功能 */
const userFields: IFieldConfig[] = [
{ key: "username", label: { t: "user.username" }, type: "string", required: true, searchable: true, editable: "addOnly" },
{ key: "password", label: { t: "user.password" }, type: "password", tableHide: true },
{ key: "nickname", label: { t: "user.nickname" }, type: "string", searchable: true },
{ key: "roleId", label: { t: "user.roleId" }, type: "relation", relation: { moduleKey: "role", labelKey: "name" }, filterable: true, multiple: true, defaultValue: [] },
// { key: "status", label: { t: "user.status" }, type: "select", options: [{ label: { t: "base.disabled" }, value: 0 }, { label: { t: "base.enabled" }, value: 1 }], filterable: true, defaultValue: 1 },
{ key: "active", label: { t: "user.active" }, type: "boolean", filterable: true, defaultValue: true },
{ key: "createdAt", label: { t: "user.createdAt" }, type: "date", editable: "readonly", sortable: true, filterable: true },
{ key: "updatedAt", label: { t: "user.updatedAt" }, type: "date", editable: "readonly", sortable: true },
]
export class UserModule extends ShrimpTableModule<WithId<IUser>> {
constructor(public parent: Shrimp | ShrimpModule, dataSource: ShrimpCrud<WithId<IUser>>, fields?: IFieldConfig[]) {
super(parent, "user", dataSource, fields || userFields)
this.initCrud()
}
/** 校验密码,子类可覆盖 */
protected async verifyPassword(storedPassword: string, plainPassword: string): Promise<boolean> {
return bcrypt.compare(plainPassword, storedPassword)
}
/** 从用户对象提取角色 ID 列表,子类可覆盖 */
protected getUserRoleIds(user: WithId<IUser>): string[] {
return Array.isArray(user.roleId) ? user.roleId.map(String) : user.roleId ? [String(user.roleId)] : []
}
/** 用户登录 */
async getUser(username: string, password: string): Promise<WithId<IUser>> {
const user = await this.dataSource.findOne({ username, active: true })
if (!user || !(await this.verifyPassword(user.password, password))) {
throw new ShrimpError({ t: 'shrimp.loginFailed' })
}
return user
}
/** 获取当前用户信息 */
async getModule(userId: string, roleModule: RoleModule): Promise<IModuleInfo[]> {
const user = await this.dataSource.get(userId)
if (!user) {
throw new ShrimpError({ t: 'shrimp.userNotFound' })
}
const roleIds = this.getUserRoleIds(user)
const roles = await Promise.all(roleIds.map(id => roleModule.dataSource.get(id)))
const isSuperAdmin = roles.some(r => r?.isSuperAdmin)
const powerKeys = isSuperAdmin
? (await this.root.allPower()).map(p => p.key)
: roles.flatMap(r => r?.powers || [])
return this.root.getModuleInfo(new Set(powerKeys))
}
/** 覆盖编辑 - 禁止禁用自己、禁止修改自己的角色 */
async edit(id: string, item: Partial<IUser>): Promise<WithId<IUser> | null> {
const op = this.root.operator
if (op && String(op.userId) === String(id)) {
if (item.active === false) {
throw new ShrimpError({ t: 'shrimp.cannotDisableSelf' })
}
if (item.roleId != null) {
const newRoleIds = Array.isArray(item.roleId) ? item.roleId.map(String) : [String(item.roleId)]
const oldUser = await this.dataSource.get(id)
const oldRoleIds = oldUser ? this.getUserRoleIds(oldUser) : []
if (JSON.stringify([...newRoleIds].sort()) !== JSON.stringify([...oldRoleIds].sort())) {
throw new ShrimpError({ t: 'shrimp.cannotChangeOwnRole' })
}
}
}
return super.edit(id, item)
}
/** 覆盖删除 - 禁止删除自己 */
async delete(id: string): Promise<boolean> {
const op = this.root.operator
if (op && String(op.userId) === String(id)) {
throw new ShrimpError({ t: 'shrimp.cannotDeleteSelf' })
}
return super.delete(id)
}
/** 覆盖清空 - 禁止清空所有用户 */
async clear(): Promise<boolean> {
if (this.root.operator) {
throw new ShrimpError({ t: 'shrimp.cannotClearAllUsers' })
}
return super.clear()
}
}
/** 角色模块 */
const roleFields: IFieldConfig[] = [
{ key: "name", label: { t: "role.name" }, type: "string", required: true, searchable: true },
{ key: "description", label: { t: "role.description" }, type: "textarea" },
{ key: "isSuperAdmin", label: { t: "role.isSuperAdmin" }, type: "boolean" },
{ key: "powers", label: { t: "role.powers" }, type: "string" },
{ key: "createdAt", label: { t: "role.createdAt" }, type: "date", editable: "readonly", sortable: true },
{ key: "updatedAt", label: { t: "role.updatedAt" }, type: "date", editable: "readonly", sortable: true },
]
export class RoleModule extends ShrimpTableModule<WithId<IRole>, IRoleProto> {
constructor(public parent: Shrimp | ShrimpModule, dataSource: ShrimpCrud<WithId<IRole>>, fields?: IFieldConfig[]) {
super(parent, "role", dataSource, fields || roleFields)
this.initCrud()
this.addEvent("clear", { t: "power.clear" })
this.addEvent("export", { t: "power.export" })
this.addEvent("import", { t: "power.import" })
this.addEvent("allPower", this.power)
}
async allPower(): Promise<{ key: string; label: ILabel }[]> {
return this.root.allPower()
}
/** 从操作者上下文提取角色 ID 列表,子类可覆盖 */
protected getOperatorRoleIds(op: IShrimpOperator): string[] {
return Array.isArray(op.roleId) ? op.roleId.map(String) : op.roleId ? [String(op.roleId)] : []
}
/** 覆盖编辑 - 禁止编辑自己的任一角色(防止锁死自己) */
async edit(id: string, item: Partial<IRole>): Promise<WithId<IRole> | null> {
const op = this.root.operator
if (op) {
const opRoleIds = this.getOperatorRoleIds(op)
if (opRoleIds.includes(String(id))) {
throw new ShrimpError({ t: 'shrimp.cannotEditOwnRole' })
}
}
return super.edit(id, item)
}
/** 填充超级管理员权限(展示用) */
private async fillSuperAdminPowers(role: WithId<IRole> | null): Promise<WithId<IRole> | null> {
if (role && role.isSuperAdmin) {
const allPowers = await this.allPower()
role.powers = allPowers.map(p => p.key)
}
return role
}
async list(query?: IPageQuery & any): Promise<IPageResult<WithId<IRole>>> {
const result = await super.list(query)
for (const item of result.list) {
if (item.isSuperAdmin) {
const allPowers = await this.allPower()
item.powers = allPowers.map(p => p.key)
}
}
return result
}
async get(id: string): Promise<WithId<IRole> | null> {
const result = await super.get(id)
return this.fillSuperAdminPowers(result)
}
/** 覆盖删除 - 禁止删除自己的任一角色 */
async delete(id: string): Promise<boolean> {
const op = this.root.operator
if (op) {
const opRoleIds = this.getOperatorRoleIds(op)
if (opRoleIds.includes(String(id))) {
throw new ShrimpError({ t: 'shrimp.cannotDeleteOwnRole' })
}
}
return super.delete(id)
}
/** 覆盖清空 - 禁止清空所有角色 */
async clear(): Promise<boolean> {
if (this.root.operator) {
throw new ShrimpError({ t: 'shrimp.cannotClearAllRoles' })
}
return super.clear()
}
}
+362
View File
@@ -0,0 +1,362 @@
/**
* ShrimpServer
* Shrimp 的服务端实现,接入 express + mongoose + JWT
* 提供通用的后台管理 API(登录、鉴权、菜单、事件调度)
*/
import { Router, Request, Response } from "express"
import jsonwebtoken from "jsonwebtoken"
import mongoose, { Schema, Model } from "mongoose"
import { Shrimp, ShrimpCrud, UserModule, RoleModule, RootShrimpPower } from "./Shrimp"
import { MongoShrimpCrud } from "./MongoShrimpCrud"
import { OperationLogModule } from "./OperationLogModule"
import { ShrimpCode, IMeResult, IUser, IRole, IOperationLog, WithId, IMenuItem, IShrimpOperator, ShrimpError } from "./IShrimpType"
declare global {
namespace Express {
interface Request {
user: { _id: string; name: string; power: Set<string>; roleId: string[]; isSuperAdmin: boolean }
}
}
}
// ============== 默认 Mongoose Schema(可导出,也可被子类覆盖) ==============
export const UserSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
nickname: { type: String, default: '' },
roleId: { type: [Schema.Types.ObjectId], ref: 'Role', default: [] },
active: { type: Boolean, default: true }
}, { timestamps: true })
export const RoleSchema = new Schema({
name: { type: String, required: true },
description: { type: String, default: '' },
isSuperAdmin: { type: Boolean, default: false },
powers: { type: [String], default: [] },
}, { timestamps: true })
export const OperationLogSchema = new Schema({
operatorId: { type: String, default: null },
ip: { type: String, default: '' },
method: { type: String, required: true },
args: { type: String, default: '' },
success: { type: Boolean, default: true },
errorMsg: { type: String, default: '' },
createdAt: { type: Number, default: () => Date.now() },
}, { timestamps: false })
// ============== ShrimpServer ==============
export class ShrimpServer extends Shrimp {
userModule: UserModule
roleModule: RoleModule
operationLogModule: OperationLogModule
router: Router = Router()
jwtSecret: string
config: Record<string, any>
globalOptions: Record<string, any> = {}
forcedOptionAccess = new Map<string, RootShrimpPower>()
registerOptions(key: string, options: any, access?: RootShrimpPower) {
this.globalOptions[key] = options
if (access) {
this.forcedOptionAccess.set(key, access)
}
}
/** 缓存的 Mongoose Model,避免重复注册 */
protected _userModel?: Model<IUser>
protected _roleModel?: Model<IRole>
protected _operationLogModel?: Model<IOperationLog>
constructor(jwtSecret: string, config: Record<string, any> = {}, mongodbUri: string = 'mongodb://localhost:27017/shrimp') {
super()
this.jwtSecret = jwtSecret
this.config = config
// 初始化数据源
const userCrud = this.createUserCrud()
const roleCrud = this.createRoleCrud()
const operationLogCrud = this.createOperationLogCrud()
// 初始化模块
this.userModule = this.createUserModule(userCrud)
this.roleModule = this.createRoleModule(roleCrud)
this.operationLogModule = this.createOperationLogModule(operationLogCrud)
// 连接数据库
mongoose.connect(mongodbUri).then(() => {
console.log(mongodbUri + ' MongoDB connected')
this.onDbConnected()
})
// ---- 路由 ----
// 后台配置接口(不需要鉴权)
this.router.get('/config', (_req: Request, res: Response) => {
res.json(this.success(this.config))
})
// 登录接口(不需要鉴权)
this.router.post('/login', async (req: Request, res: Response) => {
const ip = req.ip || ''
const { username, password } = req.body
const args = [{ username, password }]
try {
const user = await this.userModule.getUser(username, password)
const token = jsonwebtoken.sign(this.getJwtPayload(user), this.jwtSecret, { expiresIn: '7d' })
this.operationLogModule.record(user._id, ip, ['login'], args, true)
res.json(this.success({ token }))
} catch (error: any) {
const msg = error instanceof ShrimpError ? error.tip : { t: 'shrimp.loginFailed' }
const errMsg = error instanceof ShrimpError ? JSON.stringify(error.tip) : (error?.message || '')
this.operationLogModule.record(null, ip, ['login'], args, false, errMsg)
res.json(this.fail(ShrimpCode.FAIL, msg))
}
})
// 鉴权中间件
this.router.use(async (req: Request, res: Response, next) => {
try {
const auth = req.headers.authorization
if (!auth || !auth.startsWith('Bearer ')) {
return res.json(this.fail(ShrimpCode.UNAUTHORIZED, { t: 'shrimp.relogin' }, 'No token'))
}
const token = auth.split(' ')[1]
const decoded = jsonwebtoken.verify(token, this.jwtSecret) as any
const user = await this.userModule.dataSource.get(decoded._id)
if (!user || !this.isUserActive(user)) {
return res.json(this.fail(ShrimpCode.UNAUTHORIZED, { t: 'shrimp.userDisabled' }, 'User disabled'))
}
const roleIds = this.getUserRoleIds(user)
const roles = await Promise.all(roleIds.map(id => this.roleModule.dataSource.get(id)))
const isSuperAdmin = roles.some(r => this.isRoleSuperAdmin(r))
const powers = isSuperAdmin
? new Set((await this.allPower()).map(p => p.key))
: new Set(roles.flatMap(r => this.getRolePowers(r)))
req.user = { _id: user._id, name: this.getUserDisplayName(user), power: powers, roleId: roleIds, isSuperAdmin }
next()
} catch (error: any) {
const msg = error instanceof ShrimpError ? error.tip : { t: 'shrimp.relogin' }
return res.json(this.fail(ShrimpCode.UNAUTHORIZED, msg))
}
})
// 获取当前用户信息
this.router.get('/me', async (req: Request, res: Response) => {
try {
const moduleInfo = await this.userModule.getModule(req.user._id, this.roleModule)
const user = await this.userModule.dataSource.get(req.user._id)
if (!user) {
return res.json(this.fail(ShrimpCode.NOT_FOUND, { t: 'shrimp.userNotFound' }))
}
const roleIds = this.getUserRoleIds(user)
const roles = await Promise.all(roleIds.map(id => this.roleModule.dataSource.get(id)))
const isSuperAdmin = roles.some(r => this.isRoleSuperAdmin(r))
const powers = isSuperAdmin
? (await this.allPower()).map(p => p.key)
: roles.flatMap(r => this.getRolePowers(r))
const filteredMenuTree = this.filterMenuTree(this.getMenuTree(), powers)
// 按需收集该用户有权限的模块中引用的全局 options key(自动去重)
const neededKeys = new Set<string>()
for (const mod of moduleInfo) {
for (const field of mod.fields || []) {
if (typeof field.options === 'string') {
neededKeys.add(field.options)
}
}
}
const filteredOptions: Record<string, any> = {}
for (const key of neededKeys) {
if (this.globalOptions[key] != null) {
filteredOptions[key] = this.globalOptions[key]
}
}
for (const [key, access] of this.forcedOptionAccess) {
if (this.globalOptions[key] != null) {
if (isSuperAdmin || powers.includes(access.powerKey)) {
filteredOptions[key] = this.globalOptions[key]
}
}
}
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
res.json(this.success<IMeResult>({
nickname: this.getUserDisplayName(user),
moduleInfo,
menuTree: filteredMenuTree,
options: filteredOptions
}))
} catch (error: any) {
if (error instanceof ShrimpError) {
res.json(this.fail(error.code, error.tip))
} else {
res.json(this.fail(ShrimpCode.FAIL, { t: 'shrimp.serverError' }, error.message))
}
}
})
// 通用事件调用接口
this.router.post('/*path', async (req: Request, res: Response) => {
const raw = req.params.path
const path = (Array.isArray(raw) ? raw.join('/') : raw).split('/').filter(Boolean)
const args = Array.isArray(req.body) ? req.body : [req.body]
const ip = req.ip || ''
const shouldLog = this.operationLogModule.shouldLog(path)
try {
if (path.length === 0) {
return res.json(this.fail(ShrimpCode.FAIL, { t: 'shrimp.emptyPath' }))
}
const powers = req.user.power
if (!this.checkEvent(powers, path)) {
return res.json(this.fail(ShrimpCode.FORBIDDEN, { t: 'shrimp.forbidden' }))
}
const operator: IShrimpOperator = {
userId: req.user._id,
roleId: req.user.roleId,
isSuperAdmin: req.user.isSuperAdmin
}
const result = await Shrimp.asyncLocalStorage.run(operator, () => this.call(path, ...args))
if (shouldLog) this.operationLogModule.record(req.user._id, ip, path, args, true)
res.json(this.success(result))
} catch (error: any) {
if (shouldLog) {
const errMsg = error instanceof ShrimpError ? JSON.stringify(error.tip) : (error?.message || '')
this.operationLogModule.record(req.user?._id ?? null, ip, path, args, false, errMsg)
}
if (error instanceof ShrimpError) {
res.json(this.fail(error.code, error.tip))
} else {
res.json(this.fail(ShrimpCode.SERVER_ERROR, { t: 'shrimp.serverError' }, error.message))
}
}
})
}
// ============== 可覆盖的 Schema 工厂方法 ==============
protected createUserSchema(): mongoose.Schema {
return UserSchema
}
protected createRoleSchema(): mongoose.Schema {
return RoleSchema
}
protected createOperationLogSchema(): mongoose.Schema {
return OperationLogSchema
}
protected getUserModel(): Model<IUser> {
if (!this._userModel) {
this._userModel = mongoose.model<IUser>('shrimp_users', this.createUserSchema())
}
return this._userModel
}
protected getRoleModel(): Model<IRole> {
if (!this._roleModel) {
this._roleModel = mongoose.model<IRole>('shrimp_roles', this.createRoleSchema())
}
return this._roleModel
}
protected getOperationLogModel(): Model<IOperationLog> {
if (!this._operationLogModel) {
this._operationLogModel = mongoose.model<IOperationLog>('shrimp_operation_logs', this.createOperationLogSchema())
}
return this._operationLogModel
}
// ============== 可覆盖的 Crud 工厂方法 ==============
protected createUserCrud(): MongoShrimpCrud<WithId<IUser>> {
return new MongoShrimpCrud<WithId<IUser>>(this.getUserModel())
}
protected createRoleCrud(): MongoShrimpCrud<WithId<IRole>> {
return new MongoShrimpCrud<WithId<IRole>>(this.getRoleModel())
}
protected createOperationLogCrud(): MongoShrimpCrud<WithId<IOperationLog>> {
return new MongoShrimpCrud<WithId<IOperationLog>>(this.getOperationLogModel())
}
// ============== 可覆盖的 Module 工厂方法 ==============
protected createUserModule(dataSource: ShrimpCrud<WithId<IUser>>): UserModule {
return new UserModule(this, dataSource)
}
protected createRoleModule(dataSource: ShrimpCrud<WithId<IRole>>): RoleModule {
return new RoleModule(this, dataSource)
}
protected createOperationLogModule(dataSource: ShrimpCrud<WithId<IOperationLog>>): OperationLogModule {
return new OperationLogModule(this.userModule, dataSource)
}
// ============== 可覆盖的用户/角色字段访问钩子 ==============
/** 从用户对象生成 JWT payload,子类可覆盖 */
protected getJwtPayload(user: WithId<IUser>): Record<string, any> {
return { _id: user._id, roleId: user.roleId }
}
/** 判断用户是否可用,子类可覆盖 */
protected isUserActive(user: WithId<IUser>): boolean {
return user.active === true
}
/** 从用户对象提取角色 ID 列表,子类可覆盖 */
protected getUserRoleIds(user: WithId<IUser>): string[] {
return Array.isArray(user.roleId) ? user.roleId.map(String) : user.roleId ? [String(user.roleId)] : []
}
/** 判断角色是否为超级管理员,子类可覆盖 */
protected isRoleSuperAdmin(role: WithId<IRole> | null): boolean {
return !!role?.isSuperAdmin
}
/** 从角色对象提取权限列表,子类可覆盖 */
protected getRolePowers(role: WithId<IRole> | null): string[] {
return role?.powers || []
}
/** 从用户对象提取显示名称,子类可覆盖 */
protected getUserDisplayName(user: WithId<IUser>): string {
return user.nickname || ''
}
/** 数据库连接后的回调,子类可覆盖以执行连接后的逻辑 */
protected async onDbConnected(): Promise<void> {
}
/** 初始化默认数据(如默认角色、用户),子类可覆盖 */
protected async initDefaultData(name: string = "Administrator", description: "System administrator with all permissions"): Promise<void> {
const result = await this.userModule.dataSource.list({ limit: 1 })
if (result.total > 0) return
console.log("初始化默认数据")
const adminRole = await this.roleModule.dataSource.add({
name: name,
description: description,
isSuperAdmin: true,
powers: [],
createdAt: Date.now(),
updatedAt: Date.now()
})
await this.userModule.add({
username: "admin",
password: "admin",
nickname: "Administrator",
roleId: [adminRole._id],
active: true,
createdAt: Date.now(),
updatedAt: Date.now()
})
}
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Shrimp Server — 公共 API
*
* 内部实现细节(如 ShrimpEvent)未在此处导出,业务请只依赖本文件再导出的符号。
*/
// ===== 类型 / 接口 / 枚举 =====
export {
ShrimpCode,
ShrimpError,
ShrimpFieldTypes,
ShrimpConfig,
isShrimpCondition,
} from "./IShrimpType"
export type {
ILabel,
IShrimpResponse,
IModuleInfo,
ILoginResult,
IMeResult,
IMenuItem,
ITableProto,
ITableCrudProto,
IUser,
IRole,
IOperationLog,
WithId,
IShrimpOperator,
IShrimpPowerData,
ShrimpRequestFn,
IShrimpClient,
ShrimpFieldType,
FieldEditable,
IFieldTypeHandler,
IFieldConfig,
IFieldRule,
IPageQuery,
IPageResult,
IShrimpCondition,
IShrimpPopulate,
IShrimpQuery,
IPowerItem,
IUserProto,
IRoleProto,
} from "./IShrimpType"
// ===== 框架核心 =====
export {
Shrimp,
ShrimpModule,
ShrimpTableModule,
ShrimpPower,
RootShrimpPower,
UserModule,
RoleModule,
defaultTypeHandlers,
} from "./Shrimp"
export type {
IShrimpModuleOptions,
ShrimpCrud,
} from "./Shrimp"
// ===== 服务端实现(Express + Mongoose + JWT) =====
export {
ShrimpServer,
UserSchema,
RoleSchema,
OperationLogSchema,
} from "./ShrimpServer"
// ===== 数据源 =====
export { MongoShrimpCrud } from "./MongoShrimpCrud"
export { MemoryShrimpCrud } from "./MemoryShrimpCrud"
// ===== 可选模块 =====
export { OperationLogModule } from "./OperationLogModule"
+59
View File
@@ -0,0 +1,59 @@
import { describe, it, expect } from "vitest"
import { ShrimpError, ShrimpCode } from "../src"
import type { ILabel } from "../src"
describe("ILabel", () => {
it("ShrimpError 接受字面量 string", () => {
const e = new ShrimpError("余额不足")
expect(e.tip).toBe("余额不足")
expect(e.message).toBe("余额不足")
expect(e.code).toBe(ShrimpCode.FAIL)
})
it("ShrimpError 接受 {t} 翻译键", () => {
const tip: ILabel = { t: "myapp.notEnough", params: { need: 100 } }
const e = new ShrimpError(tip)
expect(e.tip).toEqual(tip)
// message 用 i18n key 作为日志友好的字符串
expect(e.message).toBe("myapp.notEnough")
})
it("ShrimpError 接受 {tc} 复数键", () => {
const tip: ILabel = { tc: "myapp.items", count: 3 }
const e = new ShrimpError(tip)
expect(e.tip).toEqual(tip)
expect(e.message).toBe("myapp.items")
})
it("ShrimpError 接受 {d} 日期形态", () => {
const now = Date.now()
const tip: ILabel = { d: now, format: "short" }
const e = new ShrimpError(tip)
expect(e.message).toBe(String(now))
})
it("ShrimpError 接受 {n} 数字/货币形态", () => {
const tip: ILabel = { n: 99.5, format: "currency" }
const e = new ShrimpError(tip)
expect(e.message).toBe("99.5")
})
it("ShrimpError 接受内联多语言对象", () => {
const tip: ILabel = { zh: "提交", en: "Submit" }
const e = new ShrimpError(tip)
// 对内联多语言 extractILabelText 没有特殊处理,返回 fallback
expect(e.message).toBe("[ILabel]")
expect(e.tip).toEqual(tip)
})
it("ShrimpError 支持自定义 code", () => {
const e = new ShrimpError("权限不足", ShrimpCode.FORBIDDEN)
expect(e.code).toBe(ShrimpCode.FORBIDDEN)
})
it("ShrimpError 是 Error 的子类", () => {
const e = new ShrimpError("err")
expect(e).toBeInstanceOf(Error)
expect(e.name).toBe("ShrimpError")
})
})
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, beforeEach } from "vitest"
import { MemoryShrimpCrud } from "../src"
interface IItem {
_id: string
name: string
price: number
tags?: string[]
}
describe("MemoryShrimpCrud", () => {
let crud: MemoryShrimpCrud<IItem>
beforeEach(() => {
crud = new MemoryShrimpCrud<IItem>()
})
it("add 返回带 _id 的新记录", async () => {
const item = await crud.add({ name: "苹果", price: 5 } as any)
expect(item._id).toBeDefined()
expect(item.name).toBe("苹果")
expect(item.price).toBe(5)
})
it("get 按 id 取记录", async () => {
const a = await crud.add({ name: "A", price: 1 } as any)
const fetched = await crud.get(a._id)
expect(fetched).toEqual(a)
})
it("get 不存在返回 null", async () => {
expect(await crud.get("missing")).toBeNull()
})
it("edit 部分更新", async () => {
const a = await crud.add({ name: "A", price: 1 } as any)
const updated = await crud.edit(a._id, { price: 99 })
expect(updated?.price).toBe(99)
expect(updated?.name).toBe("A")
})
it("delete 删除返回 true,再次删返回 false", async () => {
const a = await crud.add({ name: "A", price: 1 } as any)
expect(await crud.delete(a._id)).toBe(true)
expect(await crud.delete(a._id)).toBe(false)
expect(await crud.get(a._id)).toBeNull()
})
it("list 全量返回 + 分页字段", async () => {
await crud.add({ name: "A", price: 1 } as any)
await crud.add({ name: "B", price: 2 } as any)
const result = await crud.list()
expect(result.total).toBe(2)
expect(result.list).toHaveLength(2)
})
it("list where eq 过滤", async () => {
await crud.add({ name: "A", price: 1 } as any)
await crud.add({ name: "B", price: 2 } as any)
const result = await crud.list({ where: { name: { eq: "B" } } })
expect(result.total).toBe(1)
expect(result.list[0].name).toBe("B")
})
it("list where like 模糊匹配", async () => {
await crud.add({ name: "apple-juice", price: 1 } as any)
await crud.add({ name: "orange", price: 2 } as any)
const result = await crud.list({ where: { name: { like: "APP" } } })
expect(result.total).toBe(1)
expect(result.list[0].name).toBe("apple-juice")
})
it("list where gte/lte 范围过滤", async () => {
for (let i = 1; i <= 5; i++) await crud.add({ name: `n${i}`, price: i } as any)
const result = await crud.list({ where: { price: { gte: 2, lte: 4 } } })
expect(result.total).toBe(3)
})
it("list order 排序", async () => {
await crud.add({ name: "B", price: 2 } as any)
await crud.add({ name: "A", price: 1 } as any)
await crud.add({ name: "C", price: 3 } as any)
const asc = await crud.list({ order: [["price", "asc"]] })
expect(asc.list.map(i => i.price)).toEqual([1, 2, 3])
const desc = await crud.list({ order: [["price", "desc"]] })
expect(desc.list.map(i => i.price)).toEqual([3, 2, 1])
})
it("list offset/limit 分页", async () => {
for (let i = 1; i <= 10; i++) await crud.add({ name: `n${i}`, price: i } as any)
const page2 = await crud.list({ offset: 3, limit: 3, order: [["price", "asc"]] })
expect(page2.list.map(i => i.price)).toEqual([4, 5, 6])
expect(page2.total).toBe(10)
expect(page2.totalPages).toBe(4)
})
it("findOne 按字段查找", async () => {
await crud.add({ name: "alice", price: 1 } as any)
await crud.add({ name: "bob", price: 2 } as any)
const found = await crud.findOne({ name: "bob" })
expect(found?.price).toBe(2)
})
it("clear 清空所有记录", async () => {
await crud.add({ name: "A", price: 1 } as any)
await crud.add({ name: "B", price: 2 } as any)
await crud.clear()
const result = await crud.list()
expect(result.total).toBe(0)
})
it("populateItems 旁挂 _label", async () => {
const tagCrud = new MemoryShrimpCrud<{ _id: string; name: string }>()
await tagCrud.add({ name: "热门" } as any)
await tagCrud.add({ name: "促销" } as any)
const itemCrud = new MemoryShrimpCrud<IItem>()
itemCrud.getRelatedCrud = (key) => key === "tag" ? tagCrud as any : undefined
const a = await itemCrud.add({ name: "苹果", price: 5, tags: ["1", "2"] } as any)
const items = [{ ...a }] as any[]
await itemCrud.populateItems(items, [{ moduleKey: "tag", key: "tags", labelKey: "name" }])
expect(items[0].tags_label).toEqual(["热门", "促销"])
})
})
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"moduleResolution": "node",
"lib": ["ES2020"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./",
"types": ["node"]
},
"include": ["src/**/*", "test/**/*", "examples/**/*"],
"exclude": ["node_modules", "dist"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["test/**/*.test.ts"],
environment: "node",
},
})