Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f48a02083 | ||
|
|
0f2b4d6428 | ||
|
|
06aec7f0dc | ||
|
|
172c49816e | ||
|
|
a8cd07f851 | ||
|
|
24afc42de9 | ||
|
|
6383aade98 | ||
|
|
d12877f846 | ||
|
|
c264ec6673 | ||
|
|
f437e2e5e0 | ||
|
|
ad5f7f18f5 | ||
|
|
e04d01a80c | ||
|
|
eb339ccc49 | ||
|
|
8f9dfd40e0 | ||
|
|
ee35b47f69 | ||
|
|
bc54b475cf | ||
|
|
4b51d31e9f | ||
|
|
c5c06bee13 | ||
|
|
f94a01e0a1 | ||
|
|
5ecbf2cc01 | ||
|
|
9fff8c472d | ||
|
|
187c6f6030 | ||
|
|
c99ea0e18c | ||
|
|
652b31052e | ||
|
|
ca283c6733 | ||
|
|
e8fc126fa6 | ||
|
|
d8e0095a28 |
@@ -6,27 +6,81 @@
|
||||
|
||||
```sh
|
||||
# 推荐: HTTP(任何能访问 git.zeromvc.com 的机器都能用)
|
||||
npm install git+http://git.zeromvc.com/wc24/shrimp-server.git#v0.2.0
|
||||
npm install git+http://git.zeromvc.com/wc24/shrimp-server.git#v0.5.0
|
||||
|
||||
# 也可以 SSH(需要 ssh key 配好)
|
||||
npm install git+ssh://git@git.zeromvc.com:wc24/shrimp-server.git#v0.2.0
|
||||
npm install git+ssh://git@git.zeromvc.com:wc24/shrimp-server.git#v0.5.0
|
||||
```
|
||||
|
||||
> 仓库 ship `.ts` 源码,消费方项目需要 TS 运行器(`tsx` / `ts-node`)或在打包工具(vite / webpack / esbuild)里能解析 `.ts`。
|
||||
|
||||
### 两个入口,按需选择
|
||||
### ts-node / ts-node-dev 用户:让它编译 node_modules 内的 .ts
|
||||
|
||||
包内提供了**核心**和**完整 server** 两个 entry,**peer deps 全部 optional**——你只装自己用得到的那一份:
|
||||
`ts-node` 默认会把 `node_modules/` 当成"已编译"跳过,直接把 shrimp-server 的 `.ts`
|
||||
源码丢给 Node — Node 22+ 看到 `export` 会按 ESM 加载然后炸 `Unexpected token 'export'`。
|
||||
在 `tsconfig.json` 里把 ignore 覆盖掉:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"compilerOptions": { /* ... */ },
|
||||
"ts-node": {
|
||||
// 默认是 /(?:^|/)node_modules// — 这里清空,让 ts-node 也编译 shrimp-server
|
||||
"ignore": ["(?!)"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`tsx` 用户不需要这一步(tsx 默认就编译 node_modules 内的 .ts)。
|
||||
|
||||
### TypeScript 用户:让 tsc 识别子路径
|
||||
|
||||
包用 package.json `exports` 字段划分了 `'shrimp-server'`(0 重依赖核心)、
|
||||
`'shrimp-server/expmon'`(Express + Mongoose 整合方案)和 `'shrimp-server/types'`
|
||||
(纯类型)三个入口。**TS 默认的 `moduleResolution: "node"` 不读 `exports`,会找不到子路径模块。**
|
||||
两个解法二选一:
|
||||
|
||||
```jsonc
|
||||
// 方案 A: 升 moduleResolution(配合 module: node16,严格但纯净)
|
||||
"compilerOptions": {
|
||||
"module": "node16",
|
||||
"moduleResolution": "node16"
|
||||
}
|
||||
```
|
||||
|
||||
```jsonc
|
||||
// 方案 B: 保留 commonjs,显式 paths 指过去(兼容 ts-node-dev 老版)
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"shrimp-server": ["node_modules/shrimp-server/src/main/index.ts"],
|
||||
"shrimp-server/expmon": ["node_modules/shrimp-server/src/main/expmon.ts"],
|
||||
"shrimp-server/types": ["node_modules/shrimp-server/src/main/types.ts"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Node 22+ 的 CJS 加载器 **会**读 `exports`,所以运行时不需要额外配置 — 只是 TS 的
|
||||
类型解析在 `moduleResolution: "node"` 模式下落后于 Node 实际行为,需要 paths 兜底。
|
||||
|
||||
### 三个入口,按需选择
|
||||
|
||||
包内提供**核心**、**expmon(Express+Mongo 整合)**和**纯类型**三个 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"
|
||||
// 2) expmon: Express + Mongoose + JWT 整合方案,需要装上面 4 个 peer
|
||||
import { ShrimpServer, MongoShrimpCrud, MongoShrimp } from "shrimp-server/expmon"
|
||||
|
||||
// 3) 纯类型: 只含 IShrimpType.ts(types + ShrimpCode enum + ShrimpError class)
|
||||
// 给前端 / shrimp-admin / 任何"只要协议、不要框架运行时"的消费方
|
||||
import { ShrimpCode, ShrimpError } from "shrimp-server/types"
|
||||
import type { IFieldConfig, IMenuItem, IMeResult } from "shrimp-server/types"
|
||||
```
|
||||
|
||||
只用 (1) 时,**不要**在自己的 package.json 里写 express/mongoose/bcrypt/jsonwebtoken,可以省下大量 install 时间(尤其是 mongoose 的 native binding)。需要 (2) 时按 peer 范围装齐即可。
|
||||
只用 (1) 时,**不要**在自己的 package.json 里写 express/mongoose/bcrypt/jsonwebtoken,可以省下大量 install 时间(尤其是 mongoose 的 native binding)。需要 (2) 时按 peer 范围装齐即可。(3) 完全独立,既不会拉 Shrimp 主类也不会拉 mongoose,前端 bundle 安全。
|
||||
|
||||
> bcrypt 在 core 里走的是动态 `import('bcrypt')`,不触发 Password 字段 hash / `UserModule.verifyPassword` 就完全不会去 require 它。所以即便用 core 也注册了 password 字段,只要你不真正调用 `add/edit` 写入 Password 或 `getUser` 校验密码,bcrypt 仍是可不装的。
|
||||
|
||||
@@ -42,6 +96,33 @@ import { ShrimpServer, MongoShrimpCrud } from "shrimp-server/server"
|
||||
|
||||
## 约定
|
||||
|
||||
shrimp 不是铁板一块的协议,它是**一组可选拼装件**。每个件对外有自己的契约,你用了哪个件就被哪个件的契约绑住,不用就不必遵守。盘点时按**作用域**分两层。
|
||||
|
||||
### 🌐 全局约定(只要你说"我在写 shrimp",就跑不掉)
|
||||
|
||||
| 契约 | 说明 |
|
||||
|---|---|
|
||||
| `IModuleInfo` 形状 | 任何模块声明都得这么写 — 见 [src/IShrimpType.ts](src/IShrimpType.ts) `IModuleInfo` |
|
||||
| `IFieldConfig` 形状 | 字段就这样描述(`name` / `label` / `type` / `relation` / `rules` …) |
|
||||
| Shrimp 树结构 | `parent`/`children` 嵌套、`getFullPath()` 路径语义 |
|
||||
| Power / Role 声明 | `power` 树形 + `role` 持 `powers[]` |
|
||||
| `ILabel` 多语言形态 | 见下方 §国际化 — 6 选 1 的标签类型 |
|
||||
|
||||
### 🔌 条件约定(用了某个件,才被它的契约绑住)
|
||||
|
||||
| 启用前提 | 它的契约 |
|
||||
|---|---|
|
||||
| **使用 `ShrimpTable`(前端表格组件)** | • list 响应必须是 `IPageResult` = `{ list, total, page, pageSize, totalPages }`<br>• 字段 `type` 必须落在内置枚举:`string` / `number` / `boolean` / `date` / `select` / `textarea` / `password` / `relation` / `json` / `tab` —— 或自行注册 `IFieldTypeHandler`<br>• populate 字段旁挂 `${key}_label`(数组关联挂数组) |
|
||||
| **使用 `buildShrimpRouter` / `ShrimpServer`** | • HTTP 路由形状:`GET /config`、`POST /login`、`GET /me`、`POST /<modulePath>/<event>`<br>• JWT 携带:`Authorization: Bearer <token>`<br>• 后端需实现 `IUserAccessor`(getJwtPayload / isUserActive / getUserRoleIds / isRoleSuperAdmin / getRolePowers / getUserDisplayName) — 见 [src/forExpress/types.ts](src/forExpress/types.ts) |
|
||||
| **使用 `MongoShrimp`** | • User/Role/OperationLog 的 mongoose Schema 形状<br>• `onDbConnected` 钩子时序:连接就绪后才能注册需要 DB 的模块 |
|
||||
| **挂 `OperationLogModule`** | • CRUD 动作自动写日志的字段集(operator / module / action / target / time) |
|
||||
| **使用默认 `Field*.vue` 渲染**(前端) | • 字段 `type` 必须是内置枚举之一,否则需注册 `typeHandler` 才能渲染 |
|
||||
| **使用 Shrimp 子模块机制** | • 子表 `ownerKey` 是后端注册侧独占,**不进 fields[]**<br>• 前端只发通用 `ownerId`,不感知 `ownerKey` 的实际字段名 |
|
||||
|
||||
> 替换某个件,这个件的条件契约自动失效。例如:你换掉 `ShrimpTable` 用 AG-Grid,list 响应格式和字段 type 枚举两条对你都不再生效;你不挂 `OperationLogModule`,日志契约就不存在。
|
||||
|
||||
---
|
||||
|
||||
### 国际化 (ILabel)
|
||||
|
||||
所有前端可见文本字段(`label` / `tip` / `menu.label` / `power.label` / `field.label` / `rule.message` …)统一类型 `ILabel`。**用哪种形态取决于你写在哪一层**。
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Array / Object 字段类型 —— 设计草案(暂未实现)
|
||||
|
||||
> 状态:**搁置待需求**。当前没有字段需要它(powers 已用自定义类型 `powers` 解决,dropList 用自定义 type + Mixed 解决)。
|
||||
> 等出现「既要结构化数组/对象、又要框架级递归校验 + 自动表单渲染」的真实字段时,再按本文档实现。
|
||||
|
||||
## 背景:为什么有这份文档
|
||||
|
||||
### 触发点:powers 字段类型错误
|
||||
角色权限字段 `powers` 实际存的是权限 key 数组(`string[]`),但 `roleFields` 里错标成 `type: "string"`。在「字段前置验证」(`ShrimpTableModule.validateField`)加上类型校验后,String 分支 `typeof value !== 'string'` 把数组判为类型错误。
|
||||
|
||||
### 已采用的解法(v0.6.2,已上线)
|
||||
把 powers 改成自定义类型 `type: "powers"`。原理:`validateField` 的类型校验是 switch-case,只认 string/number/boolean/date 四个内置类型,**任何自定义 type 不匹配任何 case → 自动跳过类型校验**;且未注册 typeHandler → 无 reqFilter/resFilter → 数组原样存取,不破坏前端权限树。required/rules 仍生效。
|
||||
|
||||
这是最小解,powers 问题已闭环。**本文档的 array/object 不是为 powers——powers 不需要它**。
|
||||
|
||||
## 何时才该实现本设计
|
||||
|
||||
满足以下条件之一再做,否则属于过度设计:
|
||||
- 出现一个字段,值是**结构化数组**(如 `[{itemId,count,weight}]`),且希望**框架级递归校验** + **自动按子字段渲染表单**(而非像 dropList 那样手写专属前端组件 + 跳过校验)。
|
||||
- 多个字段重复出现「对象数组」形态,自定义类型方案的手写成本变得不划算。
|
||||
|
||||
判别:需求会把"要不要去重 / 要不要嵌套 / 摘要怎么显示"这些问题自然定下来,比现在凭空猜更准。
|
||||
|
||||
## 设计要点(实现时参考)
|
||||
|
||||
### 与 multiple 的关系(关键,A 方案)
|
||||
`multiple` 与 `array` 是**两个正交维度,不合并**:
|
||||
- `multiple`:**选择基数修饰符**,依附 select/relation,含义"从固定候选集里选几个",**集合语义(不可重复)**。保持现状不动。
|
||||
- `array`:**值形态类型**,开放列表,元素类型由 `item` 定,可嵌套。
|
||||
- 判别标准:值来自**固定选项集**→ select/relation + multiple;值是**开放列表**→ array。
|
||||
|
||||
### 后端 shrimp-server
|
||||
|
||||
**1. `IShrimpType.ts`**
|
||||
```ts
|
||||
// ShrimpFieldTypes 增加
|
||||
Array: "array", Object: "object"
|
||||
// IFieldConfig 增加(复用 IFieldConfig 自身递归 —— tab 的 tabs[].fields 已有先例)
|
||||
item?: IFieldConfig // array 元素的类型定义
|
||||
fields?: IFieldConfig[] // object 的子字段定义
|
||||
unique?: boolean // array 是否去重(集合语义,默认 false)
|
||||
```
|
||||
|
||||
**2. `ShrimpTableModule.validateField` 递归校验**
|
||||
- `array` 分支:值必须是数组 → 对每个元素递归 `validateField(field.item, 元素, item)`;`unique:true` 查重报错;min/max 已支持数组长度。
|
||||
- `object` 分支:值必须是对象 → 对 `field.fields` 每个子字段递归 `validateField(子字段, value[子key], value)`。
|
||||
- **multiple 特殊处理**:`multiple:true` 字段值是数组,但元素校验走字段自己的 options/relation;在类型 switch 里 multiple 字段**跳过标量类型检查**(防止 powers 那类问题复发)。
|
||||
|
||||
**3. typeHandler**
|
||||
- array/object **不注册 resFilter**(不同于 json 会 `JSON.stringify`)——结构原样进出,前端直接拿到结构化数据。
|
||||
|
||||
### 前端 shrimp-admin
|
||||
|
||||
字段渲染机制:约定式自动注册 —— `components/fields/Field<X>.vue` → 自动注册类型 `<x>`(首字母小写)。`vueAdmin.getFieldComponent(moduleKey, type, key)` 按 type 取组件,未知 type 兜底为 string。**范本见 `FieldTab.vue`**:用 `getFieldComponent(childField.type)` 递归渲染子字段。
|
||||
|
||||
**1. `components/fields/FieldArray.vue`(新)** 类型 `array`
|
||||
- edit:列表渲染,每项 `getFieldComponent(field.item.type)` 递归 + 增/删行。
|
||||
- display:摘要(JSON 截断,或「N 项」)。
|
||||
- props 标准接口:`{field, modelValue, mode:'display'|'edit'|'filter', disabled}`。
|
||||
|
||||
**2. `components/fields/FieldObject.vue`(新)** 类型 `object`
|
||||
- edit:按 `field.fields` 逐个 `el-form-item` + 递归组件(≈ FieldTab 去掉 tab 选择层)。
|
||||
- display:摘要。
|
||||
|
||||
**递归天然支持嵌套**:array 的 `item` 可以是 `{type:"object",fields:[...]}`(对象数组),object 的某字段可以是 `{type:"array",...}`,任意层级。
|
||||
|
||||
### powers 若迁移到 array(可选,非必须)
|
||||
`{ key:"powers", type:"array", item:{type:"string"}, unique:true }`(集合去重)。但 powers 现用 `"powers"` 自定义类型已工作,**无强需求迁移**。
|
||||
|
||||
## 发版
|
||||
实现并前后端验证(后端 `tsc --noEmit`、前端 `vue-tsc`/build)通过后,shrimp-server + shrimp-admin 一起升 **0.7.0**,业务项目引用同步更新。
|
||||
|
||||
## 关联
|
||||
- 另一个已知待办:`field.validate`(字段级自定义验证函数,`IFieldConfig.validate`)在 `IShrimpType.ts` 定义了,但 `prepareAddItem`/`prepareEditItem` 只调了 `handler.validate`(typeHandler 级),**`field.validate` 从未被调用** —— 漏接,待补。
|
||||
Generated
+206
-162
File diff suppressed because it is too large
Load Diff
+23
-17
@@ -1,46 +1,52 @@
|
||||
{
|
||||
"name": "shrimp-server",
|
||||
"version": "0.3.0",
|
||||
"private": true,
|
||||
"version": "0.7.10",
|
||||
"description": "Shrimp 框架后端 — 声明式字段驱动的 Node.js 管理后台框架(Express + Mongoose + JWT)",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"main": "dist/main/index.js",
|
||||
"types": "dist/main/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/core.ts",
|
||||
"default": "./src/core.ts"
|
||||
},
|
||||
"./server": {
|
||||
"types": "./src/server/index.ts",
|
||||
"default": "./src/server/index.ts"
|
||||
"types": "./dist/main/index.d.ts",
|
||||
"default": "./dist/main/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"prepare": "tsc -p tsconfig.build.json",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bcrypt": "^5 || ^6",
|
||||
"express": "^4 || ^5",
|
||||
"mongoose": "^6 || ^7 || ^8",
|
||||
"jsonwebtoken": "^8 || ^9",
|
||||
"bcrypt": "^5 || ^6"
|
||||
"mongoose": "^6 || ^7 || ^8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"express": { "optional": true },
|
||||
"mongoose": { "optional": true },
|
||||
"jsonwebtoken": { "optional": true },
|
||||
"bcrypt": { "optional": true }
|
||||
"express": {
|
||||
"optional": true
|
||||
},
|
||||
"mongoose": {
|
||||
"optional": true
|
||||
},
|
||||
"jsonwebtoken": {
|
||||
"optional": true
|
||||
},
|
||||
"bcrypt": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.0",
|
||||
"@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",
|
||||
|
||||
+17
-3
@@ -1,6 +1,12 @@
|
||||
/**
|
||||
* Shrimp 前后端共用类型定义
|
||||
* 定义错误码、协议、通用数据格式
|
||||
* Shrimp 类型契约 — 前后端 wire protocol 定义
|
||||
*
|
||||
* @contractVersion 1.0.0
|
||||
*
|
||||
* 改动此文件需要:
|
||||
* 1. 升 @contractVersion(语义化版本)
|
||||
* 2. 同步到 shrimp-admin/src/IShrimpType.ts,更新其 @syncedFrom
|
||||
* 3. 通知消费侧对齐
|
||||
*/
|
||||
|
||||
/** 业务错误码 */
|
||||
@@ -229,8 +235,9 @@ export const ShrimpFieldTypes = {
|
||||
Textarea: "textarea" as ShrimpFieldType,
|
||||
Password: "password" as ShrimpFieldType,
|
||||
Relation: "relation" as ShrimpFieldType,
|
||||
Json: "json" as ShrimpFieldType,
|
||||
Tab: "tab" as ShrimpFieldType,
|
||||
Object: "object" as ShrimpFieldType,
|
||||
Array: "array" as ShrimpFieldType,
|
||||
}
|
||||
|
||||
/** 字段可编辑状态 */
|
||||
@@ -270,6 +277,12 @@ export interface IFieldConfig {
|
||||
rules?: IFieldRule[] // 通用验证规则(前后端共用)
|
||||
/** tab 类型专用:每个 type 对应的子字段配置 */
|
||||
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
|
||||
/** object 类型专用:嵌套字段组 */
|
||||
fields?: IFieldConfig[]
|
||||
/** array 类型专用:每个元素的字段配置(递归 IFieldConfig;元素无需 key,label 用作每项标题) */
|
||||
item?: IFieldConfig
|
||||
/** tab 类型专用:import 反序列化(把字符串还原成对象,如 xlsx 导入),默认 JSON.parse */
|
||||
parse?: (text: string) => any
|
||||
}
|
||||
|
||||
/** 通用验证规则(前后端共用) */
|
||||
@@ -306,6 +319,7 @@ export interface IPageResult<T> {
|
||||
page: number // 当前页码
|
||||
pageSize: number // 每页数量
|
||||
totalPages: number // 总页数
|
||||
refs?: Record<string, Record<string, any>> // relation 显示名字典: { moduleKey: { id: 显示名 } },前端显示时查名,替代逐行 _label
|
||||
}
|
||||
|
||||
// ============== 数据源查询协议 ==============
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ShrimpCrud } from './Shrimp'
|
||||
import type { ShrimpCrud } from './Shrimp/ShrimpCrud'
|
||||
import { IShrimpQuery, IShrimpCondition, IShrimpPopulate, IPageResult, isShrimpCondition } from './IShrimpType'
|
||||
|
||||
export class MemoryShrimpCrud<T extends { _id: string }> implements ShrimpCrud<T> {
|
||||
|
||||
-874
@@ -1,874 +0,0 @@
|
||||
/**
|
||||
* 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 { AsyncLocalStorage } from 'async_hooks'
|
||||
import { IPasswordHasher, bcryptHasher } from './PasswordHasher'
|
||||
|
||||
export class Shrimp {
|
||||
root: Shrimp = this
|
||||
modules: Map<string, ShrimpModule> = new Map()
|
||||
/** 全局 CRUD 注册表,用于 MongoShrimpCrud 自动解析 relation */
|
||||
crudRegistry: Map<string, ShrimpCrud<any>> = new Map()
|
||||
/**
|
||||
* 密码哈希器,默认 bcryptHasher(lazy import bcrypt)。
|
||||
* 消费方可在启动时替换:`Shrimp.passwordHasher = plainHasher` 或自定义实现,
|
||||
* 让 Password 字段 reqFilter / UserModule.verifyPassword 都走自定义逻辑。
|
||||
*/
|
||||
static passwordHasher: IPasswordHasher = bcryptHasher
|
||||
/** 请求级操作者上下文,通过 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 }))
|
||||
}
|
||||
|
||||
/** 菜单树,默认平铺所有模块(label 用模块注册时声明的 label),子类可覆盖为分组结构 */
|
||||
getMenuTree(): IMenuItem[] {
|
||||
const items: IMenuItem[] = []
|
||||
this.modules.forEach(module => {
|
||||
items.push({
|
||||
name: module.moduleKey,
|
||||
label: module.label,
|
||||
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 Shrimp.passwordHasher.hash(value)
|
||||
}
|
||||
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,populateItems 据此解析 relation
|
||||
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, { t: "user.menuManage" })
|
||||
this.initCrud()
|
||||
}
|
||||
|
||||
/** 校验密码,子类可覆盖。默认走 `Shrimp.passwordHasher` 上挂载的哈希器。 */
|
||||
protected async verifyPassword(storedPassword: string, plainPassword: string): Promise<boolean> {
|
||||
return Shrimp.passwordHasher.verify(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, { t: "role.menuManage" })
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,20 @@
|
||||
* OperationLogModule
|
||||
* 操作日志子表 - 挂在 userModule 下,记录"某用户做了什么"
|
||||
* - 默认只记 mutation(add/edit/delete/clear/import) + login
|
||||
* - args 自动脱敏(password/pwd/token/secret → "***") + JSON.stringify + 截断到 2000 字符
|
||||
* - args 自动脱敏 + JSON.stringify + 截断到 2000 字符
|
||||
* - 日志失败不影响主调用
|
||||
* - 只暴露 list/get,不开 add/edit/delete 防止误改
|
||||
*/
|
||||
|
||||
import { ShrimpModule, ShrimpTableModule, ShrimpCrud } from "./Shrimp"
|
||||
import { IFieldConfig, IOperationLog, WithId, ILabel } from "../IShrimpType"
|
||||
import { Shrimp } from "./Shrimp"
|
||||
import { IFieldConfig, IOperationLog, WithId, ILabel } from "./IShrimpType"
|
||||
import { ShrimpModule } from "./ShrimpModule"
|
||||
import { ShrimpTableModule } from "./ShrimpTableModule"
|
||||
import type { ShrimpCrud } from "./ShrimpCrud"
|
||||
|
||||
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" },
|
||||
@@ -25,21 +26,17 @@ const operationLogFields: IFieldConfig[] = [
|
||||
]
|
||||
|
||||
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
|
||||
@@ -47,7 +44,6 @@ export class OperationLogModule extends ShrimpTableModule<WithId<IOperationLog>>
|
||||
return this.logEvents.has(last)
|
||||
}
|
||||
|
||||
/** 深度遍历替换敏感字段值,再 JSON.stringify 并截断 */
|
||||
sanitizeArgs(args: any[]): string {
|
||||
const walk = (val: any): any => {
|
||||
if (val == null) return val
|
||||
@@ -70,7 +66,6 @@ export class OperationLogModule extends ShrimpTableModule<WithId<IOperationLog>>
|
||||
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({
|
||||
@@ -0,0 +1,126 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks'
|
||||
import {
|
||||
ShrimpCode, IShrimpResponse, IModuleInfo, IShrimpOperator, IMenuItem, ILabel,
|
||||
} from "../IShrimpType"
|
||||
import { IPasswordHasher, bcryptHasher } from '../PasswordHasher'
|
||||
import type { ShrimpModule } from "./ShrimpModule"
|
||||
import type { ShrimpCrud } from "./ShrimpCrud"
|
||||
|
||||
export class Shrimp {
|
||||
root: Shrimp = this
|
||||
modules: Map<string, ShrimpModule> = new Map()
|
||||
/** 全局 CRUD 注册表,用于自动解析 relation */
|
||||
crudRegistry: Map<string, ShrimpCrud<any>> = new Map()
|
||||
/**
|
||||
* 密码哈希器,默认 bcryptHasher(lazy import bcrypt)。
|
||||
* 消费方可在启动时替换:`Shrimp.passwordHasher = plainHasher`
|
||||
*/
|
||||
static passwordHasher: IPasswordHasher = bcryptHasher
|
||||
/** 请求级操作者上下文 */
|
||||
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.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 })
|
||||
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: module.label,
|
||||
moduleKey: module.moduleKey
|
||||
})
|
||||
})
|
||||
return items
|
||||
}
|
||||
|
||||
/** 根据权限过滤菜单树 */
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { IShrimpQuery, IShrimpPopulate, IPageResult } from "../IShrimpType"
|
||||
|
||||
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>
|
||||
populateItems(items: any[], populates: IShrimpPopulate[], crudRegistry?: Map<string, ShrimpCrud<any>>): Promise<void>
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { IFieldConfig, ILabel } from "../IShrimpType"
|
||||
import { Shrimp } from "./Shrimp"
|
||||
import { RootShrimpPower, ShrimpPower } from "./ShrimpPower"
|
||||
|
||||
type ShrimpEventHandler = (...args: any[]) => Promise<any>
|
||||
|
||||
export class ShrimpEvent {
|
||||
constructor(public name: string, public handler: ShrimpEventHandler, public power: RootShrimpPower) {
|
||||
}
|
||||
}
|
||||
|
||||
export interface IShrimpModuleOptions {
|
||||
icon?: string
|
||||
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)
|
||||
}
|
||||
}
|
||||
getFields(): IFieldConfig[] {
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ILabel } from "../IShrimpType"
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
import {
|
||||
IFieldConfig, IFieldTypeHandler, IShrimpQuery, IShrimpCondition, IShrimpPopulate,
|
||||
IPageQuery, IPageResult, ITableCrudProto, ILabel, ShrimpConfig, ShrimpError, ShrimpFieldTypes,
|
||||
} from "../IShrimpType"
|
||||
import { Shrimp } from "./Shrimp"
|
||||
import { ShrimpModule, IShrimpModuleOptions } from "./ShrimpModule"
|
||||
import type { ShrimpCrud } from "./ShrimpCrud"
|
||||
import type { RootShrimpPower } from "./ShrimpPower"
|
||||
|
||||
/** 内置字段类型处理器 */
|
||||
export const defaultTypeHandlers: Record<string, IFieldTypeHandler> = {
|
||||
[ShrimpFieldTypes.Password]: {
|
||||
reqFilter: async (value) => {
|
||||
if (typeof value === 'string' && value.length > 0) {
|
||||
return Shrimp.passwordHasher.hash(value)
|
||||
}
|
||||
return value
|
||||
},
|
||||
resFilter: () => "***",
|
||||
},
|
||||
[ShrimpFieldTypes.Date]: {
|
||||
defaultValue: () => Date.now(),
|
||||
},
|
||||
[ShrimpFieldTypes.Number]: {
|
||||
defaultValue: 0,
|
||||
},
|
||||
[ShrimpFieldTypes.Boolean]: {
|
||||
defaultValue: false,
|
||||
},
|
||||
[ShrimpFieldTypes.Tab]: {
|
||||
// tab 是结构化字段:库里/响应/编辑全程是对象,只在"给人看"的边界(import/export/label)走字符串。
|
||||
reqFilter: (value, field) => {
|
||||
if (value == null || value === "") return undefined
|
||||
if (typeof value === "string") {
|
||||
try {
|
||||
return (field.parse ?? JSON.parse)(value)
|
||||
} catch {
|
||||
throw new ShrimpError({ t: 'shrimp.invalidJson' })
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
/** 按类型递归判定"空":tab=没选type / object=所有子字段都空 / array=无元素或所有元素都空(多维递归)/ 标量=null|'' / 空数组 */
|
||||
private isEmptyValue(field: IFieldConfig, value: any): boolean {
|
||||
if (value === undefined || value === null) return true
|
||||
switch (field.type) {
|
||||
case ShrimpFieldTypes.Tab:
|
||||
return typeof value !== "object" || value.type == null
|
||||
case ShrimpFieldTypes.Object:
|
||||
if (typeof value !== "object" || !Array.isArray(field.fields)) return true
|
||||
return field.fields.every(f => this.isEmptyValue(f, value[f.key]))
|
||||
case ShrimpFieldTypes.Array:
|
||||
if (!Array.isArray(value) || value.length === 0) return true
|
||||
return field.item ? value.every(el => this.isEmptyValue(field.item!, el)) : false
|
||||
default:
|
||||
// 标量/relation/select:'' 或空数组(multiple)算空;0、false 不算空
|
||||
return value === "" || (Array.isArray(value) && value.length === 0)
|
||||
}
|
||||
}
|
||||
|
||||
/** 前置验证 */
|
||||
private async validateField(field: IFieldConfig, value: any, item: Record<string, any>): Promise<ILabel | null> {
|
||||
const isEmpty = this.isEmptyValue(field, value)
|
||||
|
||||
if (field.required && isEmpty) {
|
||||
return field.rules?.find(r => r.required)?.message || { t: 'shrimp.fieldRequired', params: { field: field.label } }
|
||||
}
|
||||
|
||||
if (isEmpty) return null
|
||||
|
||||
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 } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// multiple 字段值是数组,类型校验需逐元素进行(与上面 options 校验保持一致);
|
||||
// 非 multiple 则整体校验单值。否则数组会被标量类型分支整体判为类型错误。
|
||||
const checkType = (v: any): boolean => {
|
||||
switch (field.type) {
|
||||
case ShrimpFieldTypes.String: return typeof v === 'string'
|
||||
case ShrimpFieldTypes.Number: return typeof v === 'number' && !Number.isNaN(v)
|
||||
case ShrimpFieldTypes.Boolean: return typeof v === 'boolean'
|
||||
case ShrimpFieldTypes.Date: return typeof v === 'number' || v instanceof Date || !isNaN(Date.parse(v))
|
||||
default: return true // 非内置标量类型(relation/json/自定义等)不在此校验
|
||||
}
|
||||
}
|
||||
const typeTargets = field.multiple && Array.isArray(value) ? value : [value]
|
||||
for (const v of typeTargets) {
|
||||
if (!checkType(v)) return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
await this.validateNode(field, result[field.key], [field.key], result)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
await this.validateNode(field, result[field.key], [field.key], result)
|
||||
|
||||
if (handler?.validate) {
|
||||
const err = await handler.validate(result[field.key], field, result)
|
||||
if (err) throw new ShrimpError(err)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** 递归校验:本节点 validateField,出错即抛(带 path);再下钻复合(tab/object/array)子节点。第一版 fail-fast */
|
||||
private async validateNode(field: IFieldConfig, value: any, path: (string | number)[], rootItem: Record<string, any>): Promise<void> {
|
||||
const err = await this.validateField(field, value, rootItem)
|
||||
// 出错只发字段名(label) + i18n key 的 message,不把开发用的 path 拼进可见文案。
|
||||
// path 仍递归往下传(供将来 inline 标红按结构化方式携带,不在这里塞进 message)。
|
||||
if (err) throw new ShrimpError(err)
|
||||
// 空的复合(走到这必是非必填)→ 不下钻校验子:整个结构缺席,里面的 required 不该触发
|
||||
if (this.isEmptyValue(field, value)) return
|
||||
for (const child of this.childrenOf(field, value)) {
|
||||
await this.validateNode(child.field, child.value, [...path, child.key], rootItem)
|
||||
}
|
||||
}
|
||||
|
||||
/** 复合类型吐出子 (字段, 值) 对:tab 选中分支的 fields / object 的 fields / array 每个元素套 item。叶子或空 → [] */
|
||||
private childrenOf(field: IFieldConfig, value: any): { key: string | number; field: IFieldConfig; value: any }[] {
|
||||
if (value == null || typeof value !== "object") return []
|
||||
if (field.type === ShrimpFieldTypes.Tab && Array.isArray(field.tabs)) {
|
||||
const branch = field.tabs.find(t => t.key === value.type)
|
||||
return branch ? branch.fields.map(f => ({ key: f.key, field: f, value: value[f.key] })) : []
|
||||
}
|
||||
if (field.type === ShrimpFieldTypes.Object && Array.isArray(field.fields)) {
|
||||
return field.fields.map(f => ({ key: f.key, field: f, value: value[f.key] }))
|
||||
}
|
||||
if (field.type === ShrimpFieldTypes.Array && field.item && Array.isArray(value)) {
|
||||
return value.map((el, i) => ({ key: i as number, field: field.item!, value: el }))
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
private async prepareResponseItems(items: any[]): Promise<any[]> {
|
||||
if (items.length === 0) return items
|
||||
return Promise.all(items.map(item => this.processResItem(item)))
|
||||
}
|
||||
|
||||
private async prepareResponseItem(item: any): Promise<any> {
|
||||
if (!item) return item
|
||||
return this.processResItem(item)
|
||||
}
|
||||
|
||||
/**
|
||||
* relation 字段(含 tab 分支里的嵌套 relation)批量解析成 refs 字典: { moduleKey: { id: 显示名 } }。
|
||||
* 整页一次性、按模块各查一次 $in,去重;替代逐行注入 ${key}_label。前端显示时按 id 查名。
|
||||
*/
|
||||
private async buildRefs(rows: any[]): Promise<Record<string, Record<string, any>>> {
|
||||
if (rows.length === 0) return {}
|
||||
const buckets = new Map<string, { labelKey: string; ids: Set<string> }>()
|
||||
const add = (moduleKey: string, labelKey: string, id: any) => {
|
||||
let b = buckets.get(moduleKey)
|
||||
if (!b) buckets.set(moduleKey, (b = { labelKey, ids: new Set() }))
|
||||
b.ids.add(String(id))
|
||||
}
|
||||
for (const row of rows) {
|
||||
for (const f of this.fields) this.collectOne(f, row[f.key], add)
|
||||
}
|
||||
if (buckets.size === 0) return {}
|
||||
const refs: Record<string, Record<string, any>> = {}
|
||||
for (const [moduleKey, b] of buckets) {
|
||||
const dict: Record<string, any> = {}
|
||||
const crud = this.root.crudRegistry.get(moduleKey)
|
||||
if (crud && b.ids.size > 0) {
|
||||
const res = await crud.list({ where: { _id: { in: Array.from(b.ids) } }, limit: b.ids.size })
|
||||
for (const d of res.list as any[]) dict[String(d._id)] = d[b.labelKey]
|
||||
}
|
||||
refs[moduleKey] = dict
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
/** 递归收集 relation 引用:relation 叶子直接收;tab 按 value.type 进选中分支继续下钻(覆盖嵌套/tab套tab) */
|
||||
/** 单个 (字段,值) 收集 relation 引用,递归复合(tab/object/array)。array 的 item 无 key —— 元素即值 */
|
||||
private collectOne(f: IFieldConfig, v: any, add: (moduleKey: string, labelKey: string, id: any) => void): void {
|
||||
if (v == null) return
|
||||
if (f.type === "relation" && f.relation) {
|
||||
;(Array.isArray(v) ? v : [v]).forEach((id: any) => id != null && add(f.relation!.moduleKey, f.relation!.labelKey, id))
|
||||
} else if (f.type === ShrimpFieldTypes.Tab && Array.isArray(f.tabs) && typeof v === "object") {
|
||||
const branch = f.tabs.find(t => t.key === v.type)
|
||||
if (branch) for (const c of branch.fields) this.collectOne(c, v[c.key], add)
|
||||
} else if (f.type === ShrimpFieldTypes.Object && Array.isArray(f.fields) && typeof v === "object") {
|
||||
for (const c of f.fields) this.collectOne(c, v[c.key], add)
|
||||
} else if (f.type === ShrimpFieldTypes.Array && f.item && Array.isArray(v)) {
|
||||
for (const el of v) this.collectOne(f.item, el, add)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
// __v 是 mongoose 版本键,前端无用,统一剥掉(连同 hidden 字段)
|
||||
return this.excludeKeys(item, ["__v", ...this.fields.filter(f => f.hidden).map(f => f.key)])
|
||||
}
|
||||
|
||||
/** 递归收集标了 filterable 的字段 → 点路径(object 子 / tab 分支子)。array 暂不下钻(后续) */
|
||||
private collectFilterablePaths(fields: IFieldConfig[], base: string[], out: Map<string, IFieldConfig>): void {
|
||||
for (const f of fields) {
|
||||
const path = [...base, f.key]
|
||||
if (f.filterable) out.set(path.join("."), f)
|
||||
if (f.type === ShrimpFieldTypes.Tab && Array.isArray(f.tabs)) {
|
||||
for (const t of f.tabs) this.collectFilterablePaths(t.fields, path, out)
|
||||
} else if (f.type === ShrimpFieldTypes.Object && Array.isArray(f.fields)) {
|
||||
this.collectFilterablePaths(f.fields, path, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
if (filter && typeof filter === 'object') {
|
||||
// filterable 路径(含 object/tab 嵌套叶子,点路径如 condition.level)→ 白名单。点路径本就是 mongoose 嵌套查询,翻译逻辑不变
|
||||
const filterableFields = new Map<string, IFieldConfig>()
|
||||
this.collectFilterablePaths(this.fields, [], filterableFields)
|
||||
const stringLikeTypes = new Set(['string', 'textarea'])
|
||||
const where: Record<string, IShrimpCondition> = {}
|
||||
for (const [key, value] of Object.entries(filter)) {
|
||||
// _id 始终放行精确过滤(单项查看/relation 跳转用),无需配 filterable
|
||||
if (key === '_id') {
|
||||
if (value != null && value !== '') where['_id'] = { eq: value }
|
||||
continue
|
||||
}
|
||||
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 }
|
||||
}
|
||||
|
||||
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))
|
||||
result.refs = await this.buildRefs(result.list)
|
||||
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)
|
||||
// export 只取全量原始数据,不做序列化;结构化字段(如 tab)的字符串化交前端(生成 xlsx 时)。
|
||||
// import 端如传字符串,由各类型 reqFilter(如 tab 的 parse)还原。
|
||||
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) {
|
||||
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
|
||||
}
|
||||
}
|
||||
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" })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import {
|
||||
IFieldConfig, IUser, IRole, WithId, IRoleProto, IPageQuery, IPageResult,
|
||||
IShrimpOperator, IModuleInfo, ILabel, ShrimpError,
|
||||
} from "../IShrimpType"
|
||||
import { Shrimp } from "./Shrimp"
|
||||
import { ShrimpModule } from "./ShrimpModule"
|
||||
import { ShrimpTableModule } from "./ShrimpTableModule"
|
||||
import type { ShrimpCrud } from "./ShrimpCrud"
|
||||
|
||||
/** 用户模块扩展 - 添加登录和获取用户信息功能 */
|
||||
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: "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, { t: "user.menuManage" })
|
||||
this.initCrud()
|
||||
}
|
||||
|
||||
protected async verifyPassword(storedPassword: string, plainPassword: string): Promise<boolean> {
|
||||
return Shrimp.passwordHasher.verify(plainPassword, storedPassword)
|
||||
}
|
||||
|
||||
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: "powers" },
|
||||
{ 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, { t: "role.menuManage" })
|
||||
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()
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
/**
|
||||
* Shrimp 核心入口 — 0 重依赖
|
||||
*
|
||||
* 只暴露 Shrimp 框架本体 + 内存数据源 + 类型定义,不引入
|
||||
* express / mongoose / jsonwebtoken。bcrypt 是 lazy import,
|
||||
* 不走 Password 字段就不会触发。
|
||||
*
|
||||
* 适用场景:
|
||||
* - 只想用 Shrimp 的 RPC dispatch + 模块/字段声明 + 内存 CRUD
|
||||
* - 自己接 HTTP / 自己写存储层
|
||||
* - 跑测试 / 跑无 DB 的 demo
|
||||
*
|
||||
* 需要完整后台(Express + Mongoose + JWT)请从 'shrimp-server/server' 导入。
|
||||
*/
|
||||
|
||||
// ===== 类型 / 接口 / 枚举 =====
|
||||
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"
|
||||
|
||||
// ===== 密码哈希(可注入,默认 bcrypt lazy import) =====
|
||||
export { bcryptHasher, plainHasher } from "./PasswordHasher"
|
||||
export type { IPasswordHasher } from "./PasswordHasher"
|
||||
|
||||
// ===== 数据源(纯内存,无外部依赖) =====
|
||||
export { MemoryShrimpCrud } from "./MemoryShrimpCrud"
|
||||
|
||||
// ===== 可选模块(纯框架代码,无外部依赖) =====
|
||||
export { OperationLogModule } from "./OperationLogModule"
|
||||
@@ -5,16 +5,12 @@
|
||||
* - 数据库类型(只通过 dataSource 抽象访问)
|
||||
* - JWT(只通过 ITokenAuth 注入)
|
||||
* - 自己的字段名(通过 IUserAccessor 适配)
|
||||
*
|
||||
* 这让消费方可以:
|
||||
* - 把 JWT 换成 session(传入自己的 ITokenAuth 实现)
|
||||
* - 不用 ShrimpServer 装配体,自己拼 deps 直接调 buildShrimpRouter
|
||||
*/
|
||||
|
||||
import { Router, Request, Response, NextFunction } from "express"
|
||||
import { Shrimp } from "../Shrimp"
|
||||
import { Shrimp } from "../Shrimp/Shrimp"
|
||||
import { ShrimpCode, IMeResult, IShrimpOperator, ShrimpError } from "../IShrimpType"
|
||||
import { IShrimpRouterDeps } from "./types"
|
||||
import type { IShrimpRouterDeps } from "./types"
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
@@ -32,12 +28,10 @@ export function buildShrimpRouter(deps: IShrimpRouterDeps): Router {
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 后台配置接口(不需要鉴权)
|
||||
router.get("/config", (_req: Request, res: Response) => {
|
||||
res.json(shrimp.success(config))
|
||||
})
|
||||
|
||||
// 登录接口(不需要鉴权)
|
||||
router.post("/login", async (req: Request, res: Response) => {
|
||||
const ip = req.ip || ""
|
||||
const { username, password } = req.body
|
||||
@@ -55,7 +49,6 @@ export function buildShrimpRouter(deps: IShrimpRouterDeps): Router {
|
||||
}
|
||||
})
|
||||
|
||||
// 鉴权中间件
|
||||
router.use(async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const auth = req.headers.authorization
|
||||
@@ -82,7 +75,6 @@ export function buildShrimpRouter(deps: IShrimpRouterDeps): Router {
|
||||
}
|
||||
})
|
||||
|
||||
// 获取当前用户信息
|
||||
router.get("/me", async (req: Request, res: Response) => {
|
||||
try {
|
||||
const moduleInfo = await userModule.getModule(req.user._id, roleModule)
|
||||
@@ -97,7 +89,6 @@ export function buildShrimpRouter(deps: IShrimpRouterDeps): Router {
|
||||
? (await shrimp.allPower()).map(p => p.key)
|
||||
: roles.flatMap(r => userAccessor.getRolePowers(r))
|
||||
const filteredMenuTree = shrimp.filterMenuTree(shrimp.getMenuTree(), powers)
|
||||
// 按需收集该用户有权限的模块中引用的全局 options key(自动去重)
|
||||
const neededKeys = new Set<string>()
|
||||
for (const mod of moduleInfo) {
|
||||
for (const field of mod.fields || []) {
|
||||
@@ -135,7 +126,6 @@ export function buildShrimpRouter(deps: IShrimpRouterDeps): Router {
|
||||
}
|
||||
})
|
||||
|
||||
// 通用事件调用接口
|
||||
router.post("/*path", async (req: Request, res: Response) => {
|
||||
const raw = req.params.path
|
||||
const path = (Array.isArray(raw) ? raw.join("/") : raw).split("/").filter(Boolean)
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
import jsonwebtoken from "jsonwebtoken"
|
||||
import { ITokenAuth } from "./types"
|
||||
import type { ITokenAuth } from "./types"
|
||||
|
||||
export interface IJwtTokenAuthOptions {
|
||||
secret: string
|
||||
@@ -1,22 +1,19 @@
|
||||
/**
|
||||
* server 子层共用接口
|
||||
* forExpress 子层共用接口
|
||||
*
|
||||
* 这些接口让 buildShrimpRouter 不直接依赖 ShrimpServer 类。
|
||||
* ShrimpServer 提供默认装配体,但消费方也可以自己拼。
|
||||
* 让 buildShrimpRouter 不直接依赖 ShrimpServer 类。
|
||||
*/
|
||||
|
||||
import type { Router } from "express"
|
||||
import type { Shrimp, UserModule, RoleModule, RootShrimpPower } from "../Shrimp"
|
||||
import type { OperationLogModule } from "../OperationLogModule"
|
||||
import type { Shrimp } from "../Shrimp/Shrimp"
|
||||
import type { UserModule, RoleModule } from "../Shrimp/UserRoleModule"
|
||||
import type { OperationLogModule } from "../Shrimp/OperationLogModule"
|
||||
import type { RootShrimpPower } from "../Shrimp/ShrimpPower"
|
||||
import type { IUser, IRole, WithId } from "../IShrimpType"
|
||||
|
||||
/**
|
||||
* Token 鉴权抽象 — 替代 JWT 直接调用
|
||||
*
|
||||
* 默认实现 createJwtTokenAuth(secret) 用 jsonwebtoken;消费方可以换成
|
||||
* session / cookie / 自定义签名,只要满足:
|
||||
* - sign(payload) 产生 token 字符串
|
||||
* - verify(token) 解出 payload(失败抛错)
|
||||
* 默认 createJwtTokenAuth 用 jsonwebtoken;可换成 session / cookie / 自定义签名。
|
||||
*/
|
||||
export interface ITokenAuth {
|
||||
sign(payload: Record<string, any>): string
|
||||
@@ -24,10 +21,8 @@ export interface ITokenAuth {
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户/角色字段访问器 — 让 routes 不直接知道 user/role 的字段名
|
||||
*
|
||||
* 默认实现读 IUser / IRole 的标准字段(username, password, roleId, active,
|
||||
* isSuperAdmin, powers, nickname);消费方覆盖这些方法即可适配自己的 schema。
|
||||
* 用户/角色字段访问器 — 让 routes 不直接知道 user/role 的字段名。
|
||||
* 默认实现读 IUser / IRole 标准字段;消费方覆盖即可适配自己的 schema。
|
||||
*/
|
||||
export interface IUserAccessor {
|
||||
getJwtPayload(user: WithId<IUser>): Record<string, any>
|
||||
@@ -51,5 +46,4 @@ export interface IShrimpRouterDeps {
|
||||
userAccessor: IUserAccessor
|
||||
}
|
||||
|
||||
// 拼接 Express 时给 Router/Req 用的扩展类型(在 buildShrimpRouter 处声明 global)
|
||||
export type { Router }
|
||||
@@ -1,28 +1,24 @@
|
||||
/**
|
||||
* ShrimpServer
|
||||
* MongoShrimp — Shrimp + Mongoose 装配体(无 HTTP 层)
|
||||
*
|
||||
* 开箱即用的装配体:Express Router + JWT + Mongoose 三块拼起来,
|
||||
* 用户只关心模块声明和子类钩子,不必自己拼 Router / Auth / Store。
|
||||
* 提供:
|
||||
* - 默认 Mongoose Schema(User / Role / OperationLog),子类可覆盖
|
||||
* - Mongoose Model 工厂 + 缓存
|
||||
* - 默认 CRUD / Module 工厂,绑定 MongoShrimpCrud
|
||||
* - mongoose.connect + onDbConnected 钩子
|
||||
* - initDefaultData 默认角色/用户播种
|
||||
*
|
||||
* 想换掉其中一块(比如换 session、换 SQL Store)的高级用法:
|
||||
* - 自己造 ITokenAuth(看 createJwtTokenAuth 实现)
|
||||
* - 自己造 dataSource(实现 ShrimpCrud 接口)
|
||||
* - 直接 `buildShrimpRouter(deps)` 拼自己的 Express app,绕开本类
|
||||
* 不知道:express / jwt / 任何 HTTP 概念。
|
||||
* 上层把 HTTP 装到这之上,见 main/expmon.ts 的 ShrimpServer。
|
||||
*/
|
||||
|
||||
import { Router } from "express"
|
||||
import mongoose, { Schema, Model } from "mongoose"
|
||||
import {
|
||||
Shrimp, ShrimpCrud, UserModule, RoleModule, RootShrimpPower,
|
||||
} from "../Shrimp"
|
||||
import { MongoShrimpCrud } from "../MongoShrimpCrud"
|
||||
import { OperationLogModule } from "../OperationLogModule"
|
||||
import { Shrimp } from "../Shrimp/Shrimp"
|
||||
import { UserModule, RoleModule } from "../Shrimp/UserRoleModule"
|
||||
import { OperationLogModule } from "../Shrimp/OperationLogModule"
|
||||
import type { ShrimpCrud } from "../Shrimp/ShrimpCrud"
|
||||
import { IUser, IRole, IOperationLog, WithId } from "../IShrimpType"
|
||||
import { buildShrimpRouter } from "./buildShrimpRouter"
|
||||
import { createJwtTokenAuth } from "./jwtAuth"
|
||||
import { ITokenAuth, IUserAccessor } from "./types"
|
||||
|
||||
// ============== 默认 Mongoose Schema(可导出,也可被子类覆盖) ==============
|
||||
import { MongoShrimpCrud } from "./MongoShrimpCrud"
|
||||
|
||||
export const UserSchema = new Schema({
|
||||
username: { type: String, required: true },
|
||||
@@ -49,72 +45,33 @@ export const OperationLogSchema = new Schema({
|
||||
createdAt: { type: Number, default: () => Date.now() },
|
||||
}, { timestamps: false })
|
||||
|
||||
// ============== ShrimpServer ==============
|
||||
|
||||
export class ShrimpServer extends Shrimp implements IUserAccessor {
|
||||
export class MongoShrimp extends Shrimp {
|
||||
userModule: UserModule
|
||||
roleModule: RoleModule
|
||||
operationLogModule: OperationLogModule
|
||||
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") {
|
||||
constructor(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()
|
||||
})
|
||||
|
||||
// 路由:把所有 routes 委托给 buildShrimpRouter
|
||||
this.router = buildShrimpRouter({
|
||||
shrimp: this,
|
||||
userModule: this.userModule,
|
||||
roleModule: this.roleModule,
|
||||
operationLogModule: this.operationLogModule,
|
||||
tokenAuth: this.createTokenAuth(),
|
||||
config: this.config,
|
||||
globalOptions: this.globalOptions,
|
||||
forcedOptionAccess: this.forcedOptionAccess,
|
||||
userAccessor: this,
|
||||
})
|
||||
}
|
||||
|
||||
/** 创建 Token 鉴权,默认 JWT。子类可覆盖换成 session 之类。 */
|
||||
protected createTokenAuth(): ITokenAuth {
|
||||
return createJwtTokenAuth(this.jwtSecret)
|
||||
}
|
||||
|
||||
// ============== 可覆盖的 Schema 工厂方法 ==============
|
||||
// ============== 可覆盖的 Schema 工厂 ==============
|
||||
|
||||
protected createUserSchema(): mongoose.Schema {
|
||||
return UserSchema
|
||||
@@ -149,7 +106,7 @@ export class ShrimpServer extends Shrimp implements IUserAccessor {
|
||||
return this._operationLogModel
|
||||
}
|
||||
|
||||
// ============== 可覆盖的 Crud 工厂方法 ==============
|
||||
// ============== 可覆盖的 Crud 工厂 ==============
|
||||
|
||||
protected createUserCrud(): MongoShrimpCrud<WithId<IUser>> {
|
||||
return new MongoShrimpCrud<WithId<IUser>>(this.getUserModel())
|
||||
@@ -163,7 +120,7 @@ export class ShrimpServer extends Shrimp implements IUserAccessor {
|
||||
return new MongoShrimpCrud<WithId<IOperationLog>>(this.getOperationLogModel())
|
||||
}
|
||||
|
||||
// ============== 可覆盖的 Module 工厂方法 ==============
|
||||
// ============== 可覆盖的 Module 工厂 ==============
|
||||
|
||||
protected createUserModule(dataSource: ShrimpCrud<WithId<IUser>>): UserModule {
|
||||
return new UserModule(this, dataSource)
|
||||
@@ -177,47 +134,14 @@ export class ShrimpServer extends Shrimp implements IUserAccessor {
|
||||
return new OperationLogModule(this.userModule, dataSource)
|
||||
}
|
||||
|
||||
// ============== 可覆盖的用户/角色字段访问钩子(实现 IUserAccessor) ==============
|
||||
|
||||
/** 从用户对象生成 JWT payload,子类可覆盖 */
|
||||
getJwtPayload(user: WithId<IUser>): Record<string, any> {
|
||||
return { _id: user._id, roleId: user.roleId }
|
||||
}
|
||||
|
||||
/** 判断用户是否可用,子类可覆盖 */
|
||||
isUserActive(user: WithId<IUser>): boolean {
|
||||
return user.active === true
|
||||
}
|
||||
|
||||
/** 从用户对象提取角色 ID 列表,子类可覆盖 */
|
||||
getUserRoleIds(user: WithId<IUser>): string[] {
|
||||
return Array.isArray(user.roleId) ? user.roleId.map(String) : user.roleId ? [String(user.roleId)] : []
|
||||
}
|
||||
|
||||
/** 判断角色是否为超级管理员,子类可覆盖 */
|
||||
isRoleSuperAdmin(role: WithId<IRole> | null): boolean {
|
||||
return !!role?.isSuperAdmin
|
||||
}
|
||||
|
||||
/** 从角色对象提取权限列表,子类可覆盖 */
|
||||
getRolePowers(role: WithId<IRole> | null): string[] {
|
||||
return role?.powers || []
|
||||
}
|
||||
|
||||
/** 从用户对象提取显示名称,子类可覆盖 */
|
||||
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> {
|
||||
protected async initDefaultData(name: string = "Administrator", description: string = "System administrator with all permissions"): Promise<void> {
|
||||
const result = await this.userModule.dataSource.list({ limit: 1 })
|
||||
if (result.total > 0) return
|
||||
console.log("初始化默认数据")
|
||||
@@ -1,19 +1,17 @@
|
||||
import { Types, Model, FilterQuery } from 'mongoose';
|
||||
import { ShrimpCrud } from './Shrimp';
|
||||
import { IShrimpQuery, IShrimpCondition, IShrimpPopulate, IPageResult, ShrimpConfig, isShrimpCondition } from './IShrimpType';
|
||||
import { Model, FilterQuery } from 'mongoose'
|
||||
import type { ShrimpCrud } from "../Shrimp/ShrimpCrud"
|
||||
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) */
|
||||
/** 获取关联模块的 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
|
||||
if (!this.isCondition(cond)) return cond
|
||||
const q: any = {}
|
||||
if (cond.eq !== undefined) q.$eq = cond.eq
|
||||
if (cond.in !== undefined) q.$in = cond.in
|
||||
@@ -23,18 +21,15 @@ export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
|
||||
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 = {}
|
||||
@@ -45,7 +40,6 @@ export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
|
||||
})
|
||||
}
|
||||
|
||||
// 排序
|
||||
const sort: any = {}
|
||||
if (query?.order) {
|
||||
for (const [key, dir] of query.order) {
|
||||
@@ -75,7 +69,6 @@ export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
|
||||
|
||||
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
|
||||
@@ -111,20 +104,21 @@ export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
|
||||
}
|
||||
|
||||
async get(id: string): Promise<T | null> {
|
||||
return await this.model.findById(id).lean() as 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);
|
||||
const doc = await this.model.create(item)
|
||||
return doc.toObject() as T // 转普通对象,否则下游 {...item} 展开的是 mongoose Document 内部($__/_doc/$isNew)
|
||||
}
|
||||
async edit(id: string, item: Partial<T>): Promise<T | null> {
|
||||
return await this.model.findByIdAndUpdate(id, item, { new: true });
|
||||
return await this.model.findByIdAndUpdate(id, item, { new: true }).lean() as T | null
|
||||
}
|
||||
async delete(id: string): Promise<boolean> {
|
||||
const result = await this.model.findByIdAndDelete(id);
|
||||
return !!result;
|
||||
const result = await this.model.findByIdAndDelete(id)
|
||||
return !!result
|
||||
}
|
||||
async clear(): Promise<boolean> {
|
||||
await this.model.deleteMany({});
|
||||
return true;
|
||||
await this.model.deleteMany({})
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
/**
|
||||
* 默认入口 = 核心 (0 重依赖)
|
||||
*
|
||||
* - import ... from 'shrimp-server' => 这个文件 / src/core.ts(纯框架,无 peer)
|
||||
* - import ... from 'shrimp-server/server' => src/server.ts(再带 ShrimpServer + Mongo)
|
||||
*
|
||||
* 该文件存在的意义是兼容不识别 `package.json#exports` 的旧工具链(npm < 7、
|
||||
* 部分 bundler 的 legacy resolve),让 `main: src/index.ts` 也能正常工作。
|
||||
*/
|
||||
export * from "./core"
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Shrimp 单一入口 — 完整后端栈
|
||||
*
|
||||
* 包含框架核心 + 类型契约 + Express + Mongoose + JWT 装配体。
|
||||
*
|
||||
* 安装 peer:express / mongoose / jsonwebtoken / bcrypt。
|
||||
*
|
||||
* 前端只想要类型契约,**不要**从这里 import — 见 shrimp-admin 的
|
||||
* IShrimpType.ts(契约副本),避免把 mongoose/express 牵进前端 bundle。
|
||||
*
|
||||
* 想换掉其中一块的高级用法:
|
||||
* - 自己造 ITokenAuth(看 createJwtTokenAuth 实现)
|
||||
* - 自己造 dataSource(实现 ShrimpCrud 接口)
|
||||
* - 直接 buildShrimpRouter(deps) 拼自己的 Express app,绕开 ShrimpServer
|
||||
*/
|
||||
|
||||
import { Router } from "express"
|
||||
import { MongoShrimp } from "../forMongo/MongoShrimp"
|
||||
import { buildShrimpRouter } from "../forExpress/buildShrimpRouter"
|
||||
import { createJwtTokenAuth } from "../forExpress/jwtAuth"
|
||||
import type { ITokenAuth, IUserAccessor } from "../forExpress/types"
|
||||
import type { RootShrimpPower } from "../Shrimp/ShrimpPower"
|
||||
import type { IUser, IRole, WithId } from "../IShrimpType"
|
||||
|
||||
// ===== 类型契约 / 枚举 =====
|
||||
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 } from "../Shrimp/Shrimp"
|
||||
export { ShrimpModule, ShrimpEvent } from "../Shrimp/ShrimpModule"
|
||||
export type { IShrimpModuleOptions } from "../Shrimp/ShrimpModule"
|
||||
export { ShrimpTableModule, defaultTypeHandlers } from "../Shrimp/ShrimpTableModule"
|
||||
export { ShrimpPower, RootShrimpPower } from "../Shrimp/ShrimpPower"
|
||||
export type { ShrimpCrud } from "../Shrimp/ShrimpCrud"
|
||||
export { UserModule, RoleModule } from "../Shrimp/UserRoleModule"
|
||||
export { OperationLogModule } from "../Shrimp/OperationLogModule"
|
||||
|
||||
// ===== 密码哈希 =====
|
||||
export { bcryptHasher, plainHasher } from "../PasswordHasher"
|
||||
export type { IPasswordHasher } from "../PasswordHasher"
|
||||
|
||||
// ===== 数据源 =====
|
||||
export { MemoryShrimpCrud } from "../MemoryShrimpCrud"
|
||||
export { MongoShrimp, UserSchema, RoleSchema, OperationLogSchema } from "../forMongo/MongoShrimp"
|
||||
export { MongoShrimpCrud } from "../forMongo/MongoShrimpCrud"
|
||||
|
||||
// ===== Express 装配 =====
|
||||
export { buildShrimpRouter } from "../forExpress/buildShrimpRouter"
|
||||
export { createJwtTokenAuth } from "../forExpress/jwtAuth"
|
||||
export type { IJwtTokenAuthOptions } from "../forExpress/jwtAuth"
|
||||
export type { ITokenAuth, IUserAccessor, IShrimpRouterDeps } from "../forExpress/types"
|
||||
|
||||
// ============== ShrimpServer ==============
|
||||
|
||||
export class ShrimpServer extends MongoShrimp implements IUserAccessor {
|
||||
router: Router
|
||||
jwtSecret: string
|
||||
config: Record<string, any>
|
||||
globalOptions: Record<string, any> = {}
|
||||
forcedOptionAccess = new Map<string, RootShrimpPower>()
|
||||
|
||||
constructor(jwtSecret: string, config: Record<string, any> = {}, mongodbUri: string = "mongodb://localhost:27017/shrimp") {
|
||||
super(mongodbUri)
|
||||
this.jwtSecret = jwtSecret
|
||||
this.config = config
|
||||
|
||||
this.router = buildShrimpRouter({
|
||||
shrimp: this,
|
||||
userModule: this.userModule,
|
||||
roleModule: this.roleModule,
|
||||
operationLogModule: this.operationLogModule,
|
||||
tokenAuth: this.createTokenAuth(),
|
||||
config: this.config,
|
||||
globalOptions: this.globalOptions,
|
||||
forcedOptionAccess: this.forcedOptionAccess,
|
||||
userAccessor: this,
|
||||
})
|
||||
}
|
||||
|
||||
registerOptions(key: string, options: any, access?: RootShrimpPower) {
|
||||
this.globalOptions[key] = options
|
||||
if (access) {
|
||||
this.forcedOptionAccess.set(key, access)
|
||||
}
|
||||
}
|
||||
|
||||
/** 创建 Token 鉴权,默认 JWT。子类可覆盖换成 session 之类。 */
|
||||
protected createTokenAuth(): ITokenAuth {
|
||||
return createJwtTokenAuth(this.jwtSecret)
|
||||
}
|
||||
|
||||
// ============== 可覆盖的用户/角色字段访问钩子(实现 IUserAccessor) ==============
|
||||
|
||||
getJwtPayload(user: WithId<IUser>): Record<string, any> {
|
||||
return { _id: user._id, roleId: user.roleId }
|
||||
}
|
||||
|
||||
isUserActive(user: WithId<IUser>): boolean {
|
||||
return user.active === true
|
||||
}
|
||||
|
||||
getUserRoleIds(user: WithId<IUser>): string[] {
|
||||
return Array.isArray(user.roleId) ? user.roleId.map(String) : user.roleId ? [String(user.roleId)] : []
|
||||
}
|
||||
|
||||
isRoleSuperAdmin(role: WithId<IRole> | null): boolean {
|
||||
return !!role?.isSuperAdmin
|
||||
}
|
||||
|
||||
getRolePowers(role: WithId<IRole> | null): string[] {
|
||||
return role?.powers || []
|
||||
}
|
||||
|
||||
getUserDisplayName(user: WithId<IUser>): string {
|
||||
return user.nickname || ""
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* Shrimp 服务端入口 — 包含 Express + Mongoose + JWT 实现
|
||||
*
|
||||
* 在 core 之上额外暴露:
|
||||
* - ShrimpServer:Express Router + JWT 鉴权 + Mongo 连接(开箱即用装配体)
|
||||
* - buildShrimpRouter / ITokenAuth / IUserAccessor:自己拼路由的低阶 API
|
||||
* - createJwtTokenAuth:默认 JWT 适配器(也可换成 session 实现)
|
||||
* - MongoShrimpCrud:Mongoose 数据源
|
||||
* - 内置 User/Role/OperationLog 的 Mongoose Schema
|
||||
*
|
||||
* 这一入口需要消费方安装 peer 依赖:express / mongoose / jsonwebtoken / bcrypt。
|
||||
* 不需要这些时请改从 'shrimp-server' 导入,不会触发任何 peer。
|
||||
*/
|
||||
|
||||
// 再导出所有 core 的符号,'shrimp-server/server' 单一入口就够用
|
||||
export * from "../core"
|
||||
|
||||
// ===== 服务端装配体 =====
|
||||
export {
|
||||
ShrimpServer,
|
||||
UserSchema,
|
||||
RoleSchema,
|
||||
OperationLogSchema,
|
||||
} from "./ShrimpServer"
|
||||
|
||||
// ===== 低阶 API:自己拼路由时用 =====
|
||||
export { buildShrimpRouter } from "./buildShrimpRouter"
|
||||
export { createJwtTokenAuth } from "./jwtAuth"
|
||||
export type { IJwtTokenAuthOptions } from "./jwtAuth"
|
||||
export type { ITokenAuth, IUserAccessor, IShrimpRouterDeps } from "./types"
|
||||
|
||||
// ===== Mongoose 数据源 =====
|
||||
export { MongoShrimpCrud } from "../MongoShrimpCrud"
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { ShrimpError, ShrimpCode } from "../src"
|
||||
import type { ILabel } from "../src"
|
||||
import { ShrimpError, ShrimpCode } from "../src/main"
|
||||
import type { ILabel } from "../src/main"
|
||||
|
||||
describe("ILabel", () => {
|
||||
it("ShrimpError 接受字面量 string", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest"
|
||||
import { MemoryShrimpCrud } from "../src"
|
||||
import { MemoryShrimpCrud } from "../src/main"
|
||||
|
||||
interface IItem {
|
||||
_id: string
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest"
|
||||
import { Shrimp, plainHasher, bcryptHasher, UserModule, MemoryShrimpCrud, ShrimpFieldTypes } from "../src"
|
||||
import type { IPasswordHasher } from "../src"
|
||||
import { Shrimp, plainHasher, bcryptHasher, UserModule, MemoryShrimpCrud, ShrimpFieldTypes } from "../src/main"
|
||||
import type { IPasswordHasher } from "../src/main"
|
||||
|
||||
describe("PasswordHasher 抽象", () => {
|
||||
const original = Shrimp.passwordHasher
|
||||
|
||||
@@ -20,10 +20,10 @@ import {
|
||||
RoleModule,
|
||||
OperationLogModule,
|
||||
plainHasher,
|
||||
} from "../src/core"
|
||||
import { buildShrimpRouter } from "../src/server/buildShrimpRouter"
|
||||
import type { ITokenAuth, IUserAccessor } from "../src/server/types"
|
||||
import type { WithId, IUser, IRole } from "../src/core"
|
||||
} from "../src/main"
|
||||
import { buildShrimpRouter } from "../src/forExpress/buildShrimpRouter"
|
||||
import type { ITokenAuth, IUserAccessor } from "../src/forExpress/types"
|
||||
import type { WithId, IUser, IRole } from "../src/main"
|
||||
|
||||
function makeFakeTokenAuth(): ITokenAuth {
|
||||
const store = new Map<string, Record<string, any>>()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, ShrimpFieldTypes } from "../src"
|
||||
import type { IFieldConfig } from "../src"
|
||||
import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, ShrimpFieldTypes } from "../src/main"
|
||||
import type { IFieldConfig } from "../src/main"
|
||||
|
||||
describe("crudRegistry 自动登记", () => {
|
||||
it("ShrimpTableModule 构造时自动把 dataSource 登记到 root.crudRegistry", () => {
|
||||
@@ -34,6 +34,7 @@ describe("crudRegistry 自动登记", () => {
|
||||
await productCrud.add({ code: "P001", tagIds: [t1._id, t2._id] } as any)
|
||||
|
||||
const result = await productModule.list({})
|
||||
expect((result.list[0] as any).tagIds_label).toEqual(["热门", "促销"])
|
||||
// _label 逐行机制已退场:relation 显示名走整页 refs 字典(refs[moduleKey][id])
|
||||
expect((result as any).refs?.tag).toEqual({ [t1._id]: "热门", [t2._id]: "促销" })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, UserModule, RoleModule } from "../src"
|
||||
import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, UserModule, RoleModule } from "../src/main"
|
||||
|
||||
describe("Shrimp.getMenuTree", () => {
|
||||
it("返回的 label 等于模块注册时声明的 label", () => {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "./src"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "test"]
|
||||
}
|
||||
Reference in New Issue
Block a user