Compare commits

...
18 Commits
Author SHA1 Message Date
wc24 6383aade98 fix(crud): 响应统一剥掉 mongoose 版本键 __v
filterHidden 出口加剥 __v(连同 hidden 字段),list/get/add/edit 全覆盖。
前端无用的 __v 不再下发。
2026-06-30 14:09:44 +08:00
wc24 d12877f846 fix(crud): add/edit 返回普通对象(toObject/lean),不再抖出 mongoose Document 内部
add 用 create 返回 Document、edit 用 findByIdAndUpdate 返回 Document,下游 processResItem
的 {...item} 会把 $__/_doc/$isNew 等内部属性展开、真数据埋进 _doc。改:add 转 toObject、
edit 加 .lean()(与 list/get 一致)。响应回归干净 POJO。
2026-06-30 14:06:40 +08:00
wc24 c264ec6673 feat!: 去掉 json 类型(object 取代) + 版本统一 0.7.0
- object 字段已能声明式表达嵌套结构,freeform 的 json 类型不再需要:
  删 ShrimpFieldTypes.Json + defaultTypeHandlers[Json](reqFilter/resFilter)。
- 源码无任何 type:json 使用,安全移除。
- 前后端版本自此统一:一起推的版本用相同版本号,本批 = 0.7.0。
2026-06-29 22:25:58 +08:00
wc24 f437e2e5e0 feat(composite): 新增 object/array 字段类型(refs 下钻 + 类型常量/配置)
- ShrimpFieldTypes 加 Object/Array
- IFieldConfig 加 fields(object 嵌套字段) + item(array 元素配置,递归)
- collectRefs 重构成 collectOne(单字段+值),加 object(遍历 fields)/array(遍历元素套 item)
  分支 → refs 下钻覆盖 object/array 里的嵌套 relation。
显示/编辑组件在 shrimp-admin。第一版从简:无 min/max、无排序、无递归校验引擎。
2026-06-29 22:21:26 +08:00
wc24 ad5f7f18f5 refactor(export): 去掉后端可逆序列化(resLabel + export stringify),序列化交前端
export 只返回原始数据;结构化字段的字符串化交前端(生成 xlsx 时)。
删: tab resLabel、IFieldTypeHandler.resLabel、processResItem 的 _label 段、
export() 的 stringify 折叠、IFieldConfig.format/stringify。保留 tab reqFilter(import parse)
+ IFieldConfig.parse。彻底清掉 tab 显示搬前端后那个 _label 遗留。
2026-06-29 21:47:08 +08:00
wc24 e04d01a80c feat(refs): buildRefs 递归下钻 tab,覆盖嵌套 relation
collectRefs 递归收集:relation 叶子直接收,tab 按 value.type 进选中分支继续下钻
(顺带覆盖 tab 套 tab)。refs 字典现含嵌套关联名(如 sellType.goods),
为 tab 显示搬前端(子组件渲染 + relation 查 refs)铺好地基。
2026-06-29 21:28:32 +08:00
wc24 eb339ccc49 feat(filter): buildQuery 放行 _id 精确过滤(单项查看/relation 跳转)
filter 原本只认 filterable 字段,_id 会被丢弃。新增: key==='_id' 时始终以 eq 放行,
让 ?filter={_id} 能过滤到单条。_id 是主键精确匹配、用户已有列表权限,无安全顾虑。
2026-06-29 20:40:28 +08:00
wc24 8f9dfd40e0 feat(relation): 用整页 refs 字典替代逐行 _label
list 响应新增 refs: { moduleKey: { id: 显示名 } },整页一次性按模块批量查、去重;
去掉 relation 的 populateItems→${key}_label 逐行注入。前端显示时按 id 查 refs。
tab 的 resLabel/_label 不动(留待复合那步)。这是嵌套引用的地基:collectRefs 以后加
tab 的 children() 下钻即可覆盖任意深度。
2026-06-29 20:17:26 +08:00
wc24 ee35b47f69 revert(tab): 撤回 v0.6.5 嵌套 relation 解析,回到 format 纯展示
populateTabRelations / format 第二参是 tab 专属特例,太狭隘(object/array 同类问题未覆盖),
通用复合解析另当专门事做。嵌套关联名(如商品名)的展示需求改放业务侧(模块重写 list/get)。
框架只保留: format(同步纯展示) + stringify/parse(可逆往返)。
2026-06-29 17:33:52 +08:00
wc24 bc54b475cf feat(tab): format 可拿到子 relation 解析名(批量,无 N+1)
tab 字段的 relation 子字段(如 sellType.goods)原只有 id,format 显示不了关联名。
新增 populateTabRelations:批量(每个关联模块一次 $in via crud.list)解析子 relation 的
labelKey 名,挂到 item.__tabRel[fieldKey][childKey],作为 format 第二参 relLabels 传入;
不污染 tab 本体(避免回灌进库),响应末尾删除 __tabRel。
2026-06-29 16:56:45 +08:00
wc24 4b51d31e9f feat(tab): 拆开展示与序列化 — field.format(展示) vs stringify/parse(可逆往返)
v0.6.3 用同一个 stringify 同时扛表格展示和 export 序列化,二者诉求冲突:
展示要好看可有损,export 要可逆完整。现拆为:
- field.format → _label 展示文本(给人看,可有损),默认 JSON.stringify
- field.stringify/parse → export/import 可逆对(机器往返),默认 JSON
export 改用 stringify(可逆)而非 _label,import 的 parse 能还原。
2026-06-29 16:42:11 +08:00
wc24 c5c06bee13 feat(tab): 结构化字段端到端传对象,给人看的边界走 _label/stringify
tab 字段原把对象 JSON.stringify 成字符串下发(复用 json 的 resFilter),
导致前端 FieldTab 收到字符串:表格 display 显示 '-'、编辑回退默认值。

改为:
- 库/响应/编辑全程对象(去掉 tab 的 resFilter stringify)
- 新增 resLabel 钩子 → 写入 ${key}_label,承载给人看的字符串文本
- export 边界用 _label 文本替换对象列(可读且可被 import 的 parse 还原)
- 字段级可配 stringify/parse,默认 JSON
2026-06-29 15:45:58 +08:00
wc24 f94a01e0a1 fix(shrimp): 修复 multiple 字段类型校验逻辑 2026-06-15 14:34:36 +08:00
wc24 5ecbf2cc01 docs: array/object 字段类型设计草案(搁置待需求,含前后端方案) 2026-06-10 15:47:57 +08:00
wc24 9fff8c472d v0.6.2: powers 字段改自定义类型,绕过前置验证的标量类型校验 2026-06-08 19:22:56 +08:00
wc24 187c6f6030 v0.6.1: 改为编译 ship,通过 npm prepare hook 自动构建
- 加 tsconfig.build.json,排除 test,rootDir 设为 src
- package.json: main/types/exports 指向 dist/main/index.{js,d.ts}
- prepare hook: 消费侧 git 安装后自动 tsc,产物不进 git
- 解决消费侧 "tsc + 裸 node" 链路 (theseus-server 等) 找不到 .js 的问题
2026-06-01 19:32:48 +08:00
wc24 c99ea0e18c v0.6.0: 收单入口
- 类型契约/Express 装配/MongoShrimp 全部合并进 src/main/index.ts
- 删 src/main/expmon.ts、src/main/types.ts
- package.json exports 收成只剩 "."(和 ./package.json)
- IShrimpType.ts 头加 @contractVersion 1.0.0(供 shrimp-admin 副本对照)

未上生产,直接断掉 shrimp-server/expmon、shrimp-server/types 两个子入口。
2026-05-23 22:27:36 +08:00
wc24 652b31052e docs(README): 约定按作用域分层(全局 vs 条件)
shrimp 不是单体协议而是可拼装件集合,每个件有自己的契约。
作用域 = 你用了哪个件就遵守哪个件的契约,不用不必遵守。

- 🌐 全局约定:IModuleInfo / IFieldConfig / Shrimp 树 / Power-Role / ILabel
- 🔌 条件约定:按宿主件分组(ShrimpTable / ShrimpServer / MongoShrimp /
  OperationLogModule / 默认 Field*.vue / 子模块机制)

这一层概念是 shrimp-admin 抽包前要先共识的:shrimp-admin 不是框架,
是"消费 ShrimpServer + ShrimpTable 这两套条件契约"的经典前端实现。
2026-05-23 20:47:35 +08:00
11 changed files with 305 additions and 205 deletions
+27
View File
@@ -96,6 +96,33 @@ import type { IFieldConfig, IMenuItem, IMeResult } from "shrimp-server/types"
## 约定 ## 约定
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) ### 国际化 (ILabel)
所有前端可见文本字段(`label` / `tip` / `menu.label` / `power.label` / `field.label` / `rule.message` …)统一类型 `ILabel`。**用哪种形态取决于你写在哪一层**。 所有前端可见文本字段(`label` / `tip` / `menu.label` / `power.label` / `field.label` / `rule.message` …)统一类型 `ILabel`。**用哪种形态取决于你写在哪一层**。
+74
View File
@@ -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` 从未被调用** —— 漏接,待补。
+8 -14
View File
@@ -1,30 +1,24 @@
{ {
"name": "shrimp-server", "name": "shrimp-server",
"version": "0.5.0", "version": "0.7.2",
"private": true,
"description": "Shrimp 框架后端 — 声明式字段驱动的 Node.js 管理后台框架(Express + Mongoose + JWT)", "description": "Shrimp 框架后端 — 声明式字段驱动的 Node.js 管理后台框架(Express + Mongoose + JWT)",
"main": "src/main/index.ts", "main": "dist/main/index.js",
"types": "src/main/index.ts", "types": "dist/main/index.d.ts",
"exports": { "exports": {
".": { ".": {
"types": "./src/main/index.ts", "types": "./dist/main/index.d.ts",
"default": "./src/main/index.ts" "default": "./dist/main/index.js"
},
"./expmon": {
"types": "./src/main/expmon.ts",
"default": "./src/main/expmon.ts"
},
"./types": {
"types": "./src/main/types.ts",
"default": "./src/main/types.ts"
}, },
"./package.json": "./package.json" "./package.json": "./package.json"
}, },
"files": [ "files": [
"dist",
"src", "src",
"README.md" "README.md"
], ],
"scripts": { "scripts": {
"build": "tsc -p tsconfig.build.json",
"prepare": "tsc -p tsconfig.build.json",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
+17 -3
View File
@@ -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, Textarea: "textarea" as ShrimpFieldType,
Password: "password" as ShrimpFieldType, Password: "password" as ShrimpFieldType,
Relation: "relation" as ShrimpFieldType, Relation: "relation" as ShrimpFieldType,
Json: "json" as ShrimpFieldType,
Tab: "tab" as ShrimpFieldType, Tab: "tab" as ShrimpFieldType,
Object: "object" as ShrimpFieldType,
Array: "array" as ShrimpFieldType,
} }
/** 字段可编辑状态 */ /** 字段可编辑状态 */
@@ -270,6 +277,12 @@ export interface IFieldConfig {
rules?: IFieldRule[] // 通用验证规则(前后端共用) rules?: IFieldRule[] // 通用验证规则(前后端共用)
/** tab 类型专用:每个 type 对应的子字段配置 */ /** tab 类型专用:每个 type 对应的子字段配置 */
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[] 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 // 当前页码 page: number // 当前页码
pageSize: number // 每页数量 pageSize: number // 每页数量
totalPages: number // 总页数 totalPages: number // 总页数
refs?: Record<string, Record<string, any>> // relation 显示名字典: { moduleKey: { id: 显示名 } },前端显示时查名,替代逐行 _label
} }
// ============== 数据源查询协议 ============== // ============== 数据源查询协议 ==============
+72 -65
View File
@@ -27,45 +27,19 @@ export const defaultTypeHandlers: Record<string, IFieldTypeHandler> = {
[ShrimpFieldTypes.Boolean]: { [ShrimpFieldTypes.Boolean]: {
defaultValue: false, 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]: { [ShrimpFieldTypes.Tab]: {
reqFilter: (value) => { // tab 是结构化字段:库里/响应/编辑全程是对象,只在"给人看"的边界(import/export/label)走字符串。
reqFilter: (value, field) => {
if (value == null || value === "") return undefined if (value == null || value === "") return undefined
if (typeof value === "string") { if (typeof value === "string") {
try { try {
return JSON.parse(value) return (field.parse ?? JSON.parse)(value)
} catch { } catch {
throw new ShrimpError({ t: 'shrimp.invalidJson' }) throw new ShrimpError({ t: 'shrimp.invalidJson' })
} }
} }
return value return value
}, },
resFilter: (value) => {
if (value == null) return value
if (typeof value === "object") {
return JSON.stringify(value)
}
return value
},
}, },
} }
@@ -114,21 +88,20 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
} }
} }
switch (field.type) { // multiple 字段值是数组,类型校验需逐元素进行(与上面 options 校验保持一致);
case ShrimpFieldTypes.String: // 非 multiple 则整体校验单值。否则数组会被标量类型分支整体判为类型错误。
if (typeof value !== 'string') return { t: 'shrimp.fieldTypeError', params: { field: field.label } } const checkType = (v: any): boolean => {
break switch (field.type) {
case ShrimpFieldTypes.Number: case ShrimpFieldTypes.String: return typeof v === 'string'
if (typeof value !== 'number' || Number.isNaN(value)) return { t: 'shrimp.fieldTypeError', params: { field: field.label } } case ShrimpFieldTypes.Number: return typeof v === 'number' && !Number.isNaN(v)
break case ShrimpFieldTypes.Boolean: return typeof v === 'boolean'
case ShrimpFieldTypes.Boolean: case ShrimpFieldTypes.Date: return typeof v === 'number' || v instanceof Date || !isNaN(Date.parse(v))
if (typeof value !== 'boolean') return { t: 'shrimp.fieldTypeError', params: { field: field.label } } default: return true // 非内置标量类型(relation/json/自定义等)不在此校验
break }
case ShrimpFieldTypes.Date: }
if (typeof value !== 'number' && !(value instanceof Date) && isNaN(Date.parse(value))) { const typeTargets = field.multiple && Array.isArray(value) ? value : [value]
return { t: 'shrimp.fieldTypeError', params: { field: field.label } } for (const v of typeTargets) {
} if (!checkType(v)) return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
} }
if (field.rules) { if (field.rules) {
@@ -232,22 +205,59 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
private async prepareResponseItems(items: any[]): Promise<any[]> { private async prepareResponseItems(items: any[]): Promise<any[]> {
if (items.length === 0) return items 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))) return Promise.all(items.map(item => this.processResItem(item)))
} }
private async prepareResponseItem(item: any): Promise<any> { private async prepareResponseItem(item: any): Promise<any> {
if (!item) return item 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) 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 { private excludeKeys(item: any, keys: string[]): any {
if (keys.length === 0) return item if (keys.length === 0) return item
const result = { ...item } const result = { ...item }
@@ -258,19 +268,8 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
} }
private filterHidden(item: any): any { private filterHidden(item: any): any {
return this.excludeKeys(item, this.fields.filter(f => f.hidden).map(f => f.key)) // __v 是 mongoose 版本键,前端无用,统一剥掉(连同 hidden 字段)
} return this.excludeKeys(item, ["__v", ...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,
}))
} }
private buildQuery(query?: IPageQuery & any): IShrimpQuery { private buildQuery(query?: IPageQuery & any): IShrimpQuery {
@@ -287,6 +286,11 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
const stringLikeTypes = new Set(['string', 'textarea']) const stringLikeTypes = new Set(['string', 'textarea'])
const where: Record<string, IShrimpCondition> = {} const where: Record<string, IShrimpCondition> = {}
for (const [key, value] of Object.entries(filter)) { 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) const field = filterableFields.get(key)
if (!field) continue if (!field) continue
if (value == null) continue if (value == null) continue
@@ -341,6 +345,7 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
const result = await this.dataSource.list(shrimpQuery) const result = await this.dataSource.list(shrimpQuery)
result.list = await this.prepareResponseItems(result.list) result.list = await this.prepareResponseItems(result.list)
result.list = result.list.map(item => this.filterHidden(item)) result.list = result.list.map(item => this.filterHidden(item))
result.refs = await this.buildRefs(result.list)
return result return result
} }
@@ -397,6 +402,8 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
delete shrimpQuery.limit delete shrimpQuery.limit
const result = await this.dataSource.list(shrimpQuery) const result = await this.dataSource.list(shrimpQuery)
result.list = await this.prepareResponseItems(result.list) result.list = await this.prepareResponseItems(result.list)
// export 只取全量原始数据,不做序列化;结构化字段(如 tab)的字符串化交前端(生成 xlsx 时)。
// import 端如传字符串,由各类型 reqFilter(如 tab 的 parse)还原。
return result.list.map(item => this.filterHidden(item)) return result.list.map(item => this.filterHidden(item))
} }
async import(data?: T[], ownerId?: string): Promise<void> { async import(data?: T[], ownerId?: string): Promise<void> {
+1 -1
View File
@@ -94,7 +94,7 @@ const roleFields: IFieldConfig[] = [
{ key: "name", label: { t: "role.name" }, type: "string", required: true, searchable: true }, { key: "name", label: { t: "role.name" }, type: "string", required: true, searchable: true },
{ key: "description", label: { t: "role.description" }, type: "textarea" }, { key: "description", label: { t: "role.description" }, type: "textarea" },
{ key: "isSuperAdmin", label: { t: "role.isSuperAdmin" }, type: "boolean" }, { key: "isSuperAdmin", label: { t: "role.isSuperAdmin" }, type: "boolean" },
{ key: "powers", label: { t: "role.powers" }, type: "string" }, { key: "powers", label: { t: "role.powers" }, type: "powers" },
{ key: "createdAt", label: { t: "role.createdAt" }, type: "date", editable: "readonly", sortable: true }, { key: "createdAt", label: { t: "role.createdAt" }, type: "date", editable: "readonly", sortable: true },
{ key: "updatedAt", label: { t: "role.updatedAt" }, type: "date", editable: "readonly", sortable: true }, { key: "updatedAt", label: { t: "role.updatedAt" }, type: "date", editable: "readonly", sortable: true },
] ]
+3 -2
View File
@@ -107,10 +107,11 @@ export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
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> { 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> { 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> { async delete(id: string): Promise<boolean> {
const result = await this.model.findByIdAndDelete(id) const result = await this.model.findByIdAndDelete(id)
-99
View File
@@ -1,99 +0,0 @@
/**
* Shrimp expmon 入口 — Express + Mongoose 整合方案
*
* 在 core 之上把 forMongo(MongoShrimp + 数据源)和 forExpress(buildShrimpRouter
* + JWT)拼起来,导出开箱即用的 ShrimpServer 装配体。
*
* 这一入口需要消费方安装 peer:express / mongoose / jsonwebtoken / bcrypt。
* 不需要时改从 'shrimp-server' 导入,不会触发任何 peer。
*
* 想换掉其中一块的高级用法:
* - 自己造 ITokenAuth(看 createJwtTokenAuth 实现)
* - 自己造 dataSource(实现 ShrimpCrud 接口)
* - 直接 buildShrimpRouter(deps) 拼自己的 Express app,绕开本类
*/
import { Router } from "express"
import { MongoShrimp, UserSchema, RoleSchema, OperationLogSchema } 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"
// 再导出所有 core 的符号,'shrimp-server/expmon' 单一入口就够用
export * from "./index"
// ===== forMongo / forExpress 公开符号 =====
export { MongoShrimp, UserSchema, RoleSchema, OperationLogSchema } from "../forMongo/MongoShrimp"
export { MongoShrimpCrud } from "../forMongo/MongoShrimpCrud"
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 || ""
}
}
+95 -12
View File
@@ -1,19 +1,28 @@
/** /**
* Shrimp 核心入口 — 0 重依赖 * Shrimp 单一入口 — 完整后端栈
* *
* 只暴露 Shrimp 框架本体 + 内存数据源 + 类型定义,不引入 * 包含框架核心 + 类型契约 + Express + Mongoose + JWT 装配体。
* express / mongoose / jsonwebtoken。bcrypt 是 lazy import,
* 不走 Password 字段就不会触发。
* *
* 适用场景: * 安装 peer:express / mongoose / jsonwebtoken / bcrypt。
* - 只想用 Shrimp 的 RPC dispatch + 模块/字段声明 + 内存 CRUD
* - 自己接 HTTP / 自己写存储层
* - 跑测试 / 跑无 DB 的 demo
* *
* 需要完整后台(Express + Mongoose + JWT)请从 'shrimp-server/expmon' 导入。 * 前端只想要类型契约,**不要**从这里 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 { export {
ShrimpCode, ShrimpCode,
ShrimpError, ShrimpError,
@@ -64,9 +73,83 @@ export type { ShrimpCrud } from "../Shrimp/ShrimpCrud"
export { UserModule, RoleModule } from "../Shrimp/UserRoleModule" export { UserModule, RoleModule } from "../Shrimp/UserRoleModule"
export { OperationLogModule } from "../Shrimp/OperationLogModule" export { OperationLogModule } from "../Shrimp/OperationLogModule"
// ===== 密码哈希(可注入,默认 bcrypt lazy import) ===== // ===== 密码哈希 =====
export { bcryptHasher, plainHasher } from "../PasswordHasher" export { bcryptHasher, plainHasher } from "../PasswordHasher"
export type { IPasswordHasher } from "../PasswordHasher" export type { IPasswordHasher } from "../PasswordHasher"
// ===== 数据源(纯内存,无外部依赖) ===== // ===== 数据源 =====
export { MemoryShrimpCrud } from "../MemoryShrimpCrud" 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 || ""
}
}
-9
View File
@@ -1,9 +0,0 @@
/**
* Shrimp 纯类型入口
*
* 只导出 IShrimpType.ts 的全部协议(类型 + ShrimpCode enum + ShrimpError class),
* 前端 shrimp-admin / 任何只需要协议定义的消费方从这里 import,
* 不会触发任何运行时依赖。
*/
export * from "../IShrimpType"
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test"]
}