Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c264ec6673 | ||
|
|
f437e2e5e0 | ||
|
|
ad5f7f18f5 | ||
|
|
e04d01a80c | ||
|
|
eb339ccc49 | ||
|
|
8f9dfd40e0 | ||
|
|
ee35b47f69 | ||
|
|
bc54b475cf | ||
|
|
4b51d31e9f | ||
|
|
c5c06bee13 | ||
|
|
f94a01e0a1 | ||
|
|
5ecbf2cc01 | ||
|
|
9fff8c472d | ||
|
|
187c6f6030 | ||
|
|
c99ea0e18c | ||
|
|
652b31052e |
@@ -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`。**用哪种形态取决于你写在哪一层**。
|
||||||
|
|||||||
@@ -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
@@ -1,30 +1,24 @@
|
|||||||
{
|
{
|
||||||
"name": "shrimp-server",
|
"name": "shrimp-server",
|
||||||
"version": "0.5.0",
|
"version": "0.7.0",
|
||||||
"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
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============== 数据源查询协议 ==============
|
// ============== 数据源查询协议 ==============
|
||||||
|
|||||||
@@ -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 }
|
||||||
@@ -261,18 +271,6 @@ export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto
|
|||||||
return this.excludeKeys(item, this.fields.filter(f => f.hidden).map(f => f.key))
|
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,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildQuery(query?: IPageQuery & any): IShrimpQuery {
|
private buildQuery(query?: IPageQuery & any): IShrimpQuery {
|
||||||
const { keyword, page, pageSize, sortBy, sortOrder, filter, ownerId } = query || {}
|
const { keyword, page, pageSize, sortBy, sortOrder, filter, ownerId } = query || {}
|
||||||
const p = page || 1
|
const p = page || 1
|
||||||
@@ -287,6 +285,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 +344,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 +401,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> {
|
||||||
|
|||||||
@@ -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 },
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -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
@@ -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 || ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
/**
|
|
||||||
* Shrimp 纯类型入口
|
|
||||||
*
|
|
||||||
* 只导出 IShrimpType.ts 的全部协议(类型 + ShrimpCode enum + ShrimpError class),
|
|
||||||
* 前端 shrimp-admin / 任何只需要协议定义的消费方从这里 import,
|
|
||||||
* 不会触发任何运行时依赖。
|
|
||||||
*/
|
|
||||||
|
|
||||||
export * from "../IShrimpType"
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"rootDir": "./src"
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "test"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user