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

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

待办: ShrimpServer 强耦合 Mongo+JWT+Express, crudRegistry 用
.model 判断数据源, 这两个问题在 demo 中已暴露, 计划后续重构补到 90 分。
This commit is contained in:
2026-05-23 15:07:55 +08:00
commit 8548a1760a
19 changed files with 9033 additions and 0 deletions
+367
View File
@@ -0,0 +1,367 @@
/**
* Shrimp 前后端共用类型定义
* 定义错误码、协议、通用数据格式
*/
/** 业务错误码 */
export enum ShrimpCode {
OK = 0,
FAIL = 1,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
SERVER_ERROR = 500,
}
/** 业务错误 - tip 展示给用户 */
export class ShrimpError extends Error {
code: ShrimpCode
tip: ILabel
constructor(tip: ILabel, code: ShrimpCode = ShrimpCode.FAIL) {
super(extractILabelText(tip))
this.code = code
this.tip = tip
this.name = 'ShrimpError'
}
}
/** 抽取 ILabel 的字符串形态用于 Error.message / 日志(非展示) */
function extractILabelText(v: ILabel): string {
if (typeof v === 'string') return v
if (v && typeof v === 'object') {
const o = v as any
if ('t' in o) return o.t
if ('tc' in o) return o.tc
if ('d' in o) return String(o.d)
if ('n' in o) return String(o.n)
}
return '[ILabel]'
}
/** 统一响应格式 */
export interface IShrimpResponse<T = any> {
code: ShrimpCode
data?: T
tip?: ILabel // 给用户看的提示
log?: string // 给开发者看的日志
}
/** 模块信息(结构元数据,扁平表示:子模块与主模块同列,通过 parent 关联) */
export interface IModuleInfo {
moduleKey: string
events: string[]
label: ILabel
fields: IFieldConfig[]
icon?: string // 子模块跳转按钮图标(element-plus icon 名称)
parent?: string // 父模块 moduleKey;存在即为子模块(不进菜单、路径嵌套)
}
/** 登录结果(仅 token) */
export interface ILoginResult {
token: string
}
/** 当前用户信息 */
export interface IMeResult {
nickname?: string
moduleInfo: IModuleInfo[]
menuTree: IMenuItem[]
options?: Record<string, any>
}
// ============== 通用类型 ==============
/**
* 通用国际化标签 - 所有前端可见文本字段统一类型
*
* 形态:
* - string 字面量,前端原样显示
* - { t: 'i18n.key', params?: ... } 翻译(vue-i18n t)
* - { tc: 'i18n.key', count, params?: ... } 复数(vue-i18n tc)
* - { d: Date|number, format? } 日期格式化(vue-i18n d)
* - { n: number, format? } 数字/货币格式化(vue-i18n n)
* - { zh: '提交', en: 'Submit' } 内联多语言
*
* params 值本身可以是 ILabel,前端递归解析
*/
export type ILabel =
| string
| { t: string; params?: Record<string, ILabel | any> }
| { tc: string; count: number; params?: Record<string, ILabel | any> }
| { d: number | Date; format?: string }
| { n: number; format?: string }
| Record<string, string>
/** 菜单项 */
export interface IMenuItem {
name: string
icon?: string
label: ILabel // 菜单显示名称
path?: string
moduleKey?: string
children?: IMenuItem[]
}
// ============== Proto 协议定义 ==============
/** 标准 Table CRUD 协议(前端可见) */
export interface ITableProto<T> {
list(query?: IPageQuery & any): Promise<IPageResult<T>>
get(id: string): Promise<T | null>
add(item: Omit<T, '_id'>, ownerId?: string): Promise<T>
edit(id: string, item: Partial<T>): Promise<T | null>
delete(id: string): Promise<boolean>
}
/** 完整 Table 协议(后端可用,含管理操作) */
export interface ITableCrudProto<T> extends ITableProto<T> {
clear(query?: IPageQuery & any): Promise<boolean>
export(query?: IPageQuery & any): Promise<T[]>
import(data?: T[], ownerId?: string): Promise<void>
}
// ============== 预制数据模型 ==============
/** 用户 */
export interface IUser {
username: string
password: string
nickname: string
roleId: string[]
active: boolean
createdAt: number
updatedAt: number
}
/** 角色 */
export interface IRole {
name: string
description: string
isSuperAdmin: boolean
powers: string[]
createdAt: number
updatedAt: number
}
/** 操作日志 */
export interface IOperationLog {
operatorId: string | null // 操作者 userId,登录失败等场景为 null
ip: string // 来源 IP
method: string // RPC 路径,如 "user.edit"、"login"
args: string // 参数(已脱敏 + JSON.stringify + 截断)
success: boolean
errorMsg: string // success=false 时填错误信息
createdAt: number
}
/** 为数据模型注入 _id 的泛型工具类型 */
export type WithId<T> = T & { _id: string }
/** 操作者契约 - 框架层通用操作者上下文,不依赖具体用户模型 */
export interface IShrimpOperator {
userId: string
roleId: string[]
isSuperAdmin: boolean
}
/** 权限 */
export interface IShrimpPowerData {
_id: string
powerKey: string
}
// ============== 前端客户端接口 ==============
/** 底层请求函数类型 */
export type ShrimpRequestFn = (path: string[], ...args: any[]) => Promise<IShrimpResponse>
/** Shrimp 客户端接口(前端实现) */
export interface IShrimpClient {
shrimpRequest: ShrimpRequestFn
hasEvent(moduleKey: string, eventName: string): boolean
}
// ============== 字段配置 ==============
//
// 【功能说明 - 给前端】
//
// IFieldConfig 是 Shrimp 框架的动态字段配置系统。
// 后端模块定义 fields 后,前端通过 GET /me 获取 moduleInfo[].fields,
// 即可自动生成表格列、搜索栏、新增/编辑表单,无需硬编码页面结构。
//
// 注意: _id 由框架自动注入(tableHide=true), 不需要在 fields 中配置, 数据返回但表格不显示。
//
// 使用流程:
// 1. 调用 GET /me → 拿到 moduleInfo 数组
// 2. 每个 moduleInfo 包含: moduleKey(模块名), events(可调用接口), fields(字段配置)
// 3. 根据 fields 渲染:
// - 表格列: 非 hidden 且非 tableHide 的字段 → 列标题=label, 数据=key
// - 搜索栏: searchable=true 的字段 → 渲染对应类型的搜索输入
// - 表单: 非 hidden 且 editable≠"readonly" 的字段, 根据 editable 决定:
// editable="always" 或缺省 → 新增/编辑都可编辑
// editable="readonly" → 新增/编辑都不可编辑(只读,如createdAt)
// editable="addOnly" → 新增可编辑, 编辑时不可编辑(如username)
// required=true 的字段标记必填, defaultValue 填入默认值
// - 排序: sortable=true 的字段 → 表头可点击排序
//
// type 与前端控件映射建议:
// string → Input 文本框
// number → InputNumber 数字框
// boolean → Switch 开关
// date → DatePicker 日期选择器
// select → Select 下拉框, 选项由 options 提供
// textarea → Input.TextArea 多行文本
// password → Input.Password 密码框
// relation → Select 下拉框, 选项从 moduleKey 指定的模块 list 接口获取,
// 显示字段为 labelKey, 值为 _id
//
/** 字段类型(string 基础类型,前端可自由扩展自定义类型) */
export type ShrimpFieldType = string
/** 框架内置字段类型常量(前端可直接使用或在此基础上扩展) */
export const ShrimpFieldTypes = {
String: "string" as ShrimpFieldType,
Number: "number" as ShrimpFieldType,
Boolean: "boolean" as ShrimpFieldType,
Date: "date" as ShrimpFieldType,
Select: "select" as ShrimpFieldType,
Textarea: "textarea" as ShrimpFieldType,
Password: "password" as ShrimpFieldType,
Relation: "relation" as ShrimpFieldType,
Json: "json" as ShrimpFieldType,
Tab: "tab" as ShrimpFieldType,
}
/** 字段可编辑状态 */
export type FieldEditable = "always" | "readonly" | "addOnly"
/** 字段类型处理器:定义每种 type 在请求/响应时的转换、验证、默认值 */
export interface IFieldTypeHandler {
/** 请求过滤:前端提交 → 保存前转换(如密码哈希、trim) */
reqFilter?: (value: any, field: IFieldConfig, item: Record<string, any>) => any | Promise<any>
/** 响应过滤:数据库取出 → 返回前端前转换(如密码脱敏为 ***、日期格式化) */
resFilter?: (value: any, field: IFieldConfig, item: Record<string, any>) => any
/** 验证:保存前校验,返回错误 ILabel 或 null(可直接返回字面字符串、{t}、{tc} 等) */
validate?: (value: any, field: IFieldConfig, item: Record<string, any>) => ILabel | null | Promise<ILabel | null>
/** 新增时的默认值(静态值或工厂函数) */
defaultValue?: any | (() => any)
}
/** 字段配置 */
export interface IFieldConfig {
key: string // 字段名(对应数据对象的属性名)
label: ILabel // 显示名称(表格列标题、表单标签)
type: ShrimpFieldType // 字段类型(决定前端渲染哪种控件)
required?: boolean // 是否必填(表单校验)
hidden?: boolean // 数据不返回给前端
tableHide?: boolean // 表格中不显示此列,但数据仍返回(如 _id)
editable?: FieldEditable // 可编辑状态: always(默认,始终可编辑) | readonly(始终只读,如createdAt) | addOnly(仅添加可编辑,编辑时只读,如username)
searchable?: boolean // 是否可搜索(出现在搜索栏)
sortable?: boolean // 是否可排序(表头可点击排序)
filterable?: boolean // 是否可筛选(出现在筛选栏,用于 filter 精确匹配)
options?: { label: ILabel; value: any }[] | string // select 类型的可选项,或全局 options key
relation?: { // relation 类型的关联配置
moduleKey: string // 关联模块名(从该模块的 list 接口获取选项)
labelKey: string // 关联模块中用作显示的字段名
}
defaultValue?: any // 新增时的默认值(优先级高于 typeHandler.defaultValue)
multiple?: boolean // 是否支持多选(relation、select 等)
rules?: IFieldRule[] // 通用验证规则(前后端共用)
/** tab 类型专用:每个 type 对应的子字段配置 */
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
}
/** 通用验证规则(前后端共用) */
export interface IFieldRule {
required?: boolean
min?: number
max?: number
pattern?: string
message?: ILabel
}
// ============== 预制协议 ==============
/** 分页查询参数 */
export interface IPageQuery {
page?: number // 页码,从 1 开始
pageSize?: number // 每页数量,默认 ShrimpConfig.defaultPageSize
keyword?: string // 关键词搜索,按 searchable 字段模糊匹配
sortBy?: string // 排序字段(对应 field.key)
sortOrder?: 'asc' | 'desc' // 排序方向
filter?: Record<string, any> // 字段精确匹配条件(AND 关系)
ownerId?: string // 子表场景: 父记录 _id。后端按模块 ownerKey 配置翻译为 filter 注入(用户无法绕过)
}
/** Shrimp 全局配置 */
export class ShrimpConfig {
static defaultPageSize: number = 100000
}
/** 分页结果 */
export interface IPageResult<T> {
list: T[] // 当前页数据
total: number // 总记录数
page: number // 当前页码
pageSize: number // 每页数量
totalPages: number // 总页数
}
// ============== 数据源查询协议 ==============
//
// IShrimpQuery 是数据源无关的查询协议。
// ShrimpTableModule 负责将前端参数(IPageQuery)翻译为 IShrimpQuery,
// 各 ShrimpCrud 实现(MemoryCrud/MongoShrimpCrud)负责执行。
//
// 查询语义:
// WHERE (where 全部满足) AND (orWhere 至少一组满足)
// ORDER BY order
// LIMIT limit OFFSET offset
//
/** 查询条件运算符 */
export interface IShrimpCondition {
eq?: any // 精确匹配 (=)
in?: any[] // IN 查询
like?: string // 模糊匹配 (不区分大小写)
gte?: any // 大于等于 (>=)
lte?: any // 小于等于 (<=)
}
/** 判断值是否为 IShrimpCondition 对象 */
export function isShrimpCondition(val: any): val is IShrimpCondition {
return val != null && typeof val === 'object' && !Array.isArray(val)
&& ('eq' in val || 'in' in val || 'like' in val || 'gte' in val || 'lte' in val)
}
/** 关联填充指令 */
export interface IShrimpPopulate {
key: string // 当前模块的字段名 (如 roleId)
moduleKey: string // 关联模块名 (如 role)
labelKey: string // 关联模块中用作显示的字段 (如 name)
}
/** 通用查询协议 (数据源无关) */
export interface IShrimpQuery {
where?: Record<string, IShrimpCondition | any> // AND 条件 (原始值=eq简写)
orWhere?: Record<string, IShrimpCondition>[] // OR 条件组 (用于 keyword)
order?: [string, 'asc' | 'desc'][] // 排序
offset?: number // 偏移量
limit?: number // 限制数量
populate?: IShrimpPopulate[] // 关联填充 (输出 {key}_label)
}
/** 权限项 */
export interface IPowerItem {
key: string
label: ILabel
}
/** 用户模块协议 */
export interface IUserProto extends ITableCrudProto<WithId<IUser>> { }
/** 角色模块协议 */
export interface IRoleProto extends ITableCrudProto<WithId<IRole>> {
allPower(): Promise<IPowerItem[]>
}
+127
View File
@@ -0,0 +1,127 @@
import { ShrimpCrud } from './Shrimp'
import { IShrimpQuery, IShrimpCondition, IShrimpPopulate, IPageResult, isShrimpCondition } from './IShrimpType'
export class MemoryShrimpCrud<T extends { _id: string }> implements ShrimpCrud<T> {
private data: Map<string, T> = new Map()
private autoId: number = 1
/** 获取关联模块的数据源(用于 populate) */
getRelatedCrud?: (moduleKey: string) => ShrimpCrud<any> | undefined
private isCondition = isShrimpCondition
private matchCondition(item: any, key: string, cond: IShrimpCondition | any): boolean {
const v = item[key]
if (this.isCondition(cond)) {
if (cond.eq !== undefined && v !== cond.eq) return false
if (cond.in !== undefined && !cond.in.includes(v)) return false
if (cond.like !== undefined && !String(v ?? '').toLowerCase().includes(String(cond.like).toLowerCase())) return false
if (cond.gte !== undefined && v < cond.gte) return false
if (cond.lte !== undefined && v > cond.lte) return false
return true
}
return v === cond
}
async findOne(query?: any): Promise<T | null> {
if (!query) return null
for (const item of this.data.values()) {
if (Object.keys(query).every(key => (item as any)[key] === query[key])) {
return item
}
}
return null
}
async list(query?: IShrimpQuery): Promise<IPageResult<T>> {
let items = Array.from(this.data.values())
// where 条件 (AND)
if (query?.where) {
for (const [key, cond] of Object.entries(query.where)) {
items = items.filter(item => this.matchCondition(item, key, cond))
}
}
// orWhere 条件 (OR 组之间)
if (query?.orWhere && query.orWhere.length > 0) {
items = items.filter(item =>
query.orWhere!.some(group =>
Object.entries(group).every(([key, cond]) => this.matchCondition(item, key, cond))
)
)
}
const total = items.length
// 排序
if (query?.order) {
for (const [key, dir] of query.order) {
const d = dir === 'desc' ? -1 : 1
items.sort((a, b) => {
const va = (a as any)[key], vb = (b as any)[key]
if (va == null && vb == null) return 0
if (va == null) return 1
if (vb == null) return -1
if (va < vb) return -d
if (va > vb) return d
return 0
})
}
}
// 分页
const offset = query?.offset || 0
const limit = query?.limit ?? items.length
const list = items.slice(offset, offset + limit)
const page = Math.floor(offset / limit) + 1
const pageSize = limit
const totalPages = Math.ceil(total / pageSize)
return { list, total, page, pageSize, totalPages }
}
async populateItems(items: any[], populates: IShrimpPopulate[]): Promise<void> {
for (const pop of populates) {
const relatedCrud = this.getRelatedCrud?.(pop.moduleKey)
if (!relatedCrud) continue
const allRelated = (await relatedCrud.list({})).list
const labelMap = new Map(allRelated.map(item => [String(item._id), (item as any)[pop.labelKey]]))
for (const item of items) {
const val = (item as any)[pop.key]
if (Array.isArray(val)) {
(item as any)[`${pop.key}_label`] = val.map((id: any) => labelMap.get(String(id)) ?? null)
} else if (val != null) {
(item as any)[`${pop.key}_label`] = labelMap.get(String(val)) ?? null
}
}
}
}
async get(id: string): Promise<T | null> {
return this.data.get(id) || null
}
async add(item: Omit<T, '_id'>): Promise<T> {
const id = (this.autoId++).toString()
const newItem = { _id: id, ...item } as T
this.data.set(id, newItem)
return newItem
}
async edit(id: string, item: Partial<T>): Promise<T | null> {
const old = this.data.get(id)
if (!old) return null
const updated = { ...old, ...item }
this.data.set(id, updated)
return updated
}
async delete(id: string): Promise<boolean> {
return this.data.delete(id)
}
async clear(): Promise<boolean> {
this.data.clear()
return true
}
}
+130
View File
@@ -0,0 +1,130 @@
import { Types, Model, FilterQuery } from 'mongoose';
import { ShrimpCrud } from './Shrimp';
import { IShrimpQuery, IShrimpCondition, IShrimpPopulate, IPageResult, ShrimpConfig, isShrimpCondition } from './IShrimpType';
export class MongoShrimpCrud<T> implements ShrimpCrud<T> {
constructor(private model: Model<any>) { }
/** 获取关联模块的 Mongoose Model(用于 populate / $lookup) */
getRelatedModel?: (moduleKey: string) => Model<any> | undefined
/** 判断值是否为 IShrimpCondition 对象 */
private isCondition = isShrimpCondition
/** 将 IShrimpCondition 翻译为 MongoDB 查询片段 */
private translateCondition(cond: IShrimpCondition | any): any {
if (!this.isCondition(cond)) return cond // 简写: 原始值 = eq
const q: any = {}
if (cond.eq !== undefined) q.$eq = cond.eq
if (cond.in !== undefined) q.$in = cond.in
if (cond.like !== undefined) q.$regex = cond.like, q.$options = 'i'
if (cond.gte !== undefined) q.$gte = cond.gte
if (cond.lte !== undefined) q.$lte = cond.lte
return q
}
/** 将 IShrimpQuery 翻译为 Mongoose 查询 */
private buildMongooseQuery(query?: IShrimpQuery): { filter: FilterQuery<T>, sort: any, skip: number, limit: number } {
const filter: FilterQuery<T> = {}
// where → AND 条件
if (query?.where) {
for (const [key, cond] of Object.entries(query.where)) {
(filter as any)[key] = this.translateCondition(cond)
}
}
// orWhere → $or
if (query?.orWhere && query.orWhere.length > 0) {
filter.$or = query.orWhere.map(group => {
const obj: any = {}
for (const [key, cond] of Object.entries(group)) {
obj[key] = this.translateCondition(cond)
}
return obj
})
}
// 排序
const sort: any = {}
if (query?.order) {
for (const [key, dir] of query.order) {
sort[key] = dir === 'desc' ? -1 : 1
}
}
return {
filter,
sort,
skip: query?.offset || 0,
limit: query?.limit ?? ShrimpConfig.defaultPageSize,
}
}
async list(query?: IShrimpQuery): Promise<IPageResult<T>> {
const { filter, sort, skip, limit } = this.buildMongooseQuery(query)
const [docs, total] = await Promise.all([
this.model.find(filter).sort(sort).skip(skip).limit(limit).lean(),
this.model.countDocuments(filter),
])
const page = Math.floor(skip / limit) + 1
const totalPages = Math.ceil(total / limit)
return { list: docs, total, page, pageSize: limit, totalPages }
}
async populateItems(items: any[], populates: IShrimpPopulate[], crudRegistry?: Map<string, any>): Promise<void> {
for (const pop of populates) {
// 优先用 getRelatedModel,其次用 crudRegistry(自动解析 relation)
let relatedModel = this.getRelatedModel?.(pop.moduleKey)
if (!relatedModel && crudRegistry) {
const relatedCrud = crudRegistry.get(pop.moduleKey) as any
relatedModel = relatedCrud?.model
}
if (!relatedModel) continue
const allRefIds = new Set<string>()
for (const item of items) {
const val = (item as any)[pop.key]
if (Array.isArray(val)) {
val.forEach((id: any) => { if (id != null) allRefIds.add(String(id)) })
} else if (val != null) {
allRefIds.add(String(val))
}
}
if (allRefIds.size === 0) continue
const docs = await relatedModel.find({ _id: { $in: Array.from(allRefIds) } }).select(`${pop.labelKey} _id`)
const labelMap = new Map(docs.map(doc => [String(doc._id), (doc as any)[pop.labelKey]]))
for (const item of items) {
const val = (item as any)[pop.key]
if (Array.isArray(val)) {
(item as any)[`${pop.key}_label`] = val.map((id: any) => labelMap.get(String(id)) ?? null)
} else if (val != null) {
(item as any)[`${pop.key}_label`] = labelMap.get(String(val)) ?? null
}
}
}
}
async findOne(query?: any): Promise<T | null> {
return await this.model.findOne(query || {}).lean() as T | null
}
async get(id: string): Promise<T | null> {
return await this.model.findById(id).lean() as T | null;
}
async add(item: Omit<T, '_id'>): Promise<T> {
return await this.model.create(item);
}
async edit(id: string, item: Partial<T>): Promise<T | null> {
return await this.model.findByIdAndUpdate(id, item, { new: true });
}
async delete(id: string): Promise<boolean> {
const result = await this.model.findByIdAndDelete(id);
return !!result;
}
async clear(): Promise<boolean> {
await this.model.deleteMany({});
return true;
}
}
+89
View File
@@ -0,0 +1,89 @@
/**
* OperationLogModule
* 操作日志子表 - 挂在 userModule 下,记录"某用户做了什么"
* - 默认只记 mutation(add/edit/delete/clear/import) + login
* - args 自动脱敏(password/pwd/token/secret → "***") + JSON.stringify + 截断到 2000 字符
* - 日志失败不影响主调用
* - 只暴露 list/get,不开 add/edit/delete 防止误改
*/
import { ShrimpModule, ShrimpTableModule, ShrimpCrud } from "./Shrimp"
import { Shrimp } from "./Shrimp"
import { IFieldConfig, IOperationLog, WithId, ILabel } from "./IShrimpType"
const SENSITIVE_KEY_RE = /(password|pwd|token|secret)/i
const ARGS_MAX_LEN = 2000
// operatorId 是子表→父记录(user)的外键,纯数据库字段,不进 fields(框架按 ownerKey 自动注入 filter)
const operationLogFields: IFieldConfig[] = [
{ key: "ip", label: { t: "operationLog.ip" }, type: "string", searchable: true, editable: "readonly" },
{ key: "method", label: { t: "operationLog.method" }, type: "string", searchable: true, filterable: true, editable: "readonly" },
{ key: "args", label: { t: "operationLog.args" }, type: "textarea", editable: "readonly" },
{ key: "success", label: { t: "operationLog.success" }, type: "boolean", filterable: true, editable: "readonly" },
{ key: "errorMsg", label: { t: "operationLog.errorMsg" }, type: "string", editable: "readonly" },
{ key: "createdAt", label: { t: "operationLog.createdAt" }, type: "date", editable: "readonly", sortable: true, filterable: true },
]
export class OperationLogModule extends ShrimpTableModule<WithId<IOperationLog>> {
/** 触发记录的事件名集合,可被外部 add/delete 扩展 */
logEvents: Set<string> = new Set(['add', 'edit', 'delete', 'clear', 'import', 'login'])
constructor(parent: Shrimp | ShrimpModule, dataSource: ShrimpCrud<WithId<IOperationLog>>, fields?: IFieldConfig[], label?: ILabel) {
super(parent, "operationLog", dataSource, fields || operationLogFields, label || { t: "user.operationLog" }, undefined, {
icon: "Tickets",
// 声明 operatorId 是父记录(user)的归属字段,框架据此自动做子表过滤
ownerKey: "operatorId",
})
// 只挂只读事件 — 不暴露 add/edit/delete,防止外部改日志
this.addEvent("list", this.power)
this.addEvent("get", this.power)
}
/** 路径最后一段在 logEvents 内,且不是 operationLog 自身的调用(防递归) */
shouldLog(path: string[]): boolean {
if (path.length === 0) return false
if (path.includes('operationLog')) return false
const last = path[path.length - 1]
return this.logEvents.has(last)
}
/** 深度遍历替换敏感字段值,再 JSON.stringify 并截断 */
sanitizeArgs(args: any[]): string {
const walk = (val: any): any => {
if (val == null) return val
if (Array.isArray(val)) return val.map(walk)
if (typeof val === 'object') {
const out: Record<string, any> = {}
for (const [k, v] of Object.entries(val)) {
out[k] = SENSITIVE_KEY_RE.test(k) ? '***' : walk(v)
}
return out
}
return val
}
let str: string
try {
str = JSON.stringify(walk(args))
} catch {
str = '[unserializable]'
}
return str.length > ARGS_MAX_LEN ? str.substring(0, ARGS_MAX_LEN) + '...' : str
}
/** 写一条日志,内部吞错(日志失败不能搞挂主流程)。operatorId 强制 String 化,避免 ObjectId 与字符串查询不匹配 */
async record(operatorId: any, ip: string, path: string[], args: any[], success: boolean, errorMsg: string = ''): Promise<void> {
try {
await this.dataSource.add({
operatorId: operatorId == null ? null : String(operatorId),
ip,
method: path.join('.'),
args: this.sanitizeArgs(args),
success,
errorMsg,
createdAt: Date.now(),
} as Omit<WithId<IOperationLog>, '_id'>)
} catch (e: any) {
console.warn('[OperationLog] record failed', e?.message || e)
}
}
}
+870
View File
@@ -0,0 +1,870 @@
/**
* Shrimp
* 后台管理系统快速开发框架
*/
import { ShrimpCode, IShrimpResponse, ITableCrudProto, IModuleInfo, IUser, IRole, WithId, IRoleProto, IPageQuery, IPageResult, IFieldConfig, IFieldRule, IFieldTypeHandler, IShrimpQuery, IShrimpCondition, IShrimpPopulate, ShrimpConfig, IShrimpOperator, IMenuItem, ShrimpError, ShrimpFieldTypes, ILabel } from "./IShrimpType"
import * as bcrypt from "bcrypt"
import { AsyncLocalStorage } from 'async_hooks'
export class Shrimp {
root: Shrimp = this
modules: Map<string, ShrimpModule> = new Map()
/** 全局 CRUD 注册表,用于 MongoShrimpCrud 自动解析 relation */
crudRegistry: Map<string, ShrimpCrud<any>> = new Map()
/** 请求级操作者上下文,通过 AsyncLocalStorage 避免并发覆盖 */
static asyncLocalStorage = new AsyncLocalStorage<IShrimpOperator | null>()
get operator(): IShrimpOperator | null {
return Shrimp.asyncLocalStorage.getStore() ?? null
}
async call(path: string[], ...args: any[]): Promise<any> {
let module = this.modules.get(path[0])
if (module == null) {
throw new Error(`Module "${path[0]}" not found`)
}
return await module.call(path.slice(1), ...args)
}
checkEvent(powers: Set<string>, path: string[]): boolean {
let module = this.modules.get(path[0])
if (module == null) return false
return module.checkEvent(powers, path.slice(1))
}
getModuleInfo(powers: Set<string>): IModuleInfo[] {
const list: IModuleInfo[] = []
this.collectModuleInfo(this.modules, powers, undefined, list)
return list
}
private collectModuleInfo(modules: Map<string, ShrimpModule>, powers: Set<string>, parent: string | undefined, out: IModuleInfo[]) {
modules.forEach(module => {
if (!powers.has(module.power.key)) return
const info: IModuleInfo = {
moduleKey: module.moduleKey,
events: module.getEventInfo(powers),
label: module.label,
fields: module instanceof ShrimpTableModule ? module.getFields() : [],
}
if (module.icon) info.icon = module.icon
if (parent) info.parent = parent
out.push(info)
if (module.modules.size > 0) {
this.collectModuleInfo(module.modules, powers, module.moduleKey, out)
}
})
}
/** 成功响应 */
success<T>(data: T, tip?: ILabel, log?: string): IShrimpResponse<T> {
const r: IShrimpResponse<T> = { code: ShrimpCode.OK, data }
if (tip) r.tip = tip
if (log) r.log = log
return r
}
/** 失败响应 */
fail<T = any>(code: ShrimpCode, tip?: ILabel, log?: string): IShrimpResponse<T> {
const r: IShrimpResponse<T> = { code }
if (tip) r.tip = tip
if (log) r.log = log
return r
}
async allPower(): Promise<{ key: string; label: ILabel }[]> {
const powers: { key: string; label: ILabel }[] = []
const collect = (module: any) => {
// 模块权限
powers.push({ key: module.power.key, label: module.power.label })
// 事件权限(children 已有 key 和 label)
powers.push(...module.power.children)
// 递归子模块
module.modules.forEach(collect)
}
this.root.modules.forEach(collect)
// 去重
const map = new Map<string, ILabel>()
powers.forEach(p => map.set(p.key, p.label))
return Array.from(map.entries()).map(([key, label]) => ({ key, label }))
}
/** 菜单树,默认平铺所有模块,子类可覆盖为分组结构 */
getMenuTree(): IMenuItem[] {
const items: IMenuItem[] = []
this.modules.forEach(module => {
items.push({
name: module.moduleKey,
label: { t: module.moduleKey + '.menuManage' },
moduleKey: module.moduleKey
})
})
return items
}
/** 根据权限过滤菜单树(递归处理 children;children 全部被过滤后,分组节点也一并剔除) */
filterMenuTree(fullMenuTree: IMenuItem[], rolePower: string[]): IMenuItem[] {
const allowedModules = new Set(rolePower.map(p => p.split('.')[0]))
const filter = (nodes: IMenuItem[]): IMenuItem[] => {
const result: IMenuItem[] = []
for (const node of nodes) {
if (node.moduleKey) {
if (allowedModules.has(node.moduleKey)) {
result.push(node)
}
continue
}
if (!node.children || node.children.length === 0) {
continue
}
const filteredChildren = filter(node.children)
if (filteredChildren.length === 0) continue
result.push({ ...node, children: filteredChildren })
}
return result
}
return filter(fullMenuTree)
}
}
type ShrimpEventHandler = (...args: any[]) => Promise<any>
export class ShrimpEvent {
constructor(public name: string, public handler: ShrimpEventHandler, public power: RootShrimpPower) {
}
}
export interface IShrimpModuleOptions {
icon?: string // 前端子模块跳转按钮图标(element-plus icon 名)
ownerKey?: string // 子表→父记录归属字段名(子模块专用,语义: 主人/上级/归属)。前端据此自动过滤和回填默认值
}
export class ShrimpModule<P extends Record<string, any> = Record<string, any>> {
power: RootShrimpPower
root: Shrimp
modules: Map<string, ShrimpModule> = new Map()
events: Map<string, ShrimpEvent> = new Map()
icon?: string
ownerKey?: string
constructor(public parent: Shrimp | ShrimpModule, public moduleKey: string, public label: ILabel, power?: RootShrimpPower, options?: IShrimpModuleOptions) {
if (power == null) {
if (parent instanceof Shrimp) {
power = new RootShrimpPower(moduleKey, label)
}
else {
power = new ShrimpPower(parent.power, moduleKey, label)
}
}
this.power = power
this.icon = options?.icon
this.ownerKey = options?.ownerKey
parent.modules.set(this.moduleKey, this)
this.root = parent.root
}
addEvent<K extends keyof P & string>(name: K, label: ILabel): this
addEvent<K extends keyof P & string>(name: K, power: RootShrimpPower): this
addEvent<K extends keyof P & string>(name: K, powerOrLabel: RootShrimpPower | ILabel) {
const handler = (this as any)[name]
if (typeof handler !== 'function') {
throw new Error(`Method "${name}" not found on ${this.moduleKey}`)
}
let power: RootShrimpPower
if (powerOrLabel instanceof RootShrimpPower) {
power = powerOrLabel
} else {
power = new ShrimpPower(this.power, name, powerOrLabel)
}
this.events.set(name, new ShrimpEvent(name, handler.bind(this), power))
return this
}
async call(path: string[], ...args: any[]): Promise<any> {
if (path.length > 1) {
let module = this.modules.get(path[0])
if (module == null) {
throw new Error(`Module "${path[0]}" not found`)
}
return await module.call(path.slice(1), ...args)
} else {
const event = this.events.get(path[0])
if (event == null) {
throw new Error(`Event "${path[0]}" not found`)
}
return await event.handler(...args)
}
}
getEventInfo(powers: Set<string>): string[] {
let events: string[] = []
this.events.forEach(event => {
if (powers.has(event.power.key)) {
events.push(event.name)
}
})
return events
}
checkEvent(powers: Set<string>, path: string[]): boolean {
if (path.length > 1) {
let module = this.modules.get(path[0])
if (module == null) return false
return module.checkEvent(powers, path.slice(1))
} else {
const event = this.events.get(path[0])
if (event == null) return false
return powers.has(event.power.key)
}
}
}
export class RootShrimpPower {
children: ShrimpPower[] = []
constructor(public powerKey: string, public label: ILabel) {
}
get key(): string {
return this.powerKey
}
}
export class ShrimpPower extends RootShrimpPower {
constructor(public parent: RootShrimpPower, public powerKey: string, public label: ILabel) {
super(powerKey, label)
parent.children.push(this)
}
get key(): string {
return this.parent.key + "." + this.powerKey
}
}
// CRUD 接口
export interface ShrimpCrud<T> {
findOne(query?: any): Promise<T | null>
list(query?: IShrimpQuery): Promise<IPageResult<T>>
get(id: string): Promise<T | null>
add(item: Omit<T, '_id'>): Promise<T>
edit(id: string, item: Partial<T>): Promise<T | null>
delete(id: string): Promise<boolean>
clear(): Promise<boolean>
/** 为记录填充关联 _label 字段 */
populateItems(items: any[], populates: IShrimpPopulate[], crudRegistry?: Map<string, ShrimpCrud<any>>): Promise<void>
}
/** 内置字段类型处理器 */
export const defaultTypeHandlers: Record<string, IFieldTypeHandler> = {
[ShrimpFieldTypes.Password]: {
reqFilter: async (value) => {
if (typeof value === 'string' && value.length > 0) {
return bcrypt.hash(value, 10)
}
return value
},
resFilter: () => "***",
},
[ShrimpFieldTypes.Date]: {
defaultValue: () => Date.now(),
},
[ShrimpFieldTypes.Number]: {
defaultValue: 0,
},
[ShrimpFieldTypes.Boolean]: {
defaultValue: false,
},
[ShrimpFieldTypes.Json]: {
reqFilter: (value) => {
if (value == null || value === "") return undefined
if (typeof value === "string") {
try {
return JSON.parse(value)
} catch {
throw new ShrimpError({ t: 'shrimp.invalidJson' })
}
}
return value
},
resFilter: (value) => {
if (value == null) return value
if (typeof value === "object") {
return JSON.stringify(value)
}
return value
},
},
[ShrimpFieldTypes.Tab]: {
reqFilter: (value) => {
if (value == null || value === "") return undefined
if (typeof value === "string") {
try {
return JSON.parse(value)
} catch {
throw new ShrimpError({ t: 'shrimp.invalidJson' })
}
}
return value
},
resFilter: (value) => {
if (value == null) return value
if (typeof value === "object") {
return JSON.stringify(value)
}
return value
},
},
}
export class ShrimpTableModule<T, P extends ITableCrudProto<T> = ITableCrudProto<T>> extends ShrimpModule<P> implements ITableCrudProto<T> {
fields: IFieldConfig[] = []
constructor(public parent: Shrimp | ShrimpModule, moduleKey: string, public dataSource: ShrimpCrud<T>, fields?: IFieldConfig[], label?: ILabel, power?: RootShrimpPower, options?: IShrimpModuleOptions) {
super(parent, moduleKey, label || { t: moduleKey }, power, options)
if (fields) {
this.fields = fields
}
// 自动注册 CRUD 到 root.crudRegistry,供 MongoShrimpCrud.populateItems 自动解析 relation
if ((dataSource as any).model) {
this.root.crudRegistry.set(moduleKey, dataSource)
}
}
getFields(): IFieldConfig[] {
return this.fields
}
static typeHandlers: Map<string, IFieldTypeHandler> = new Map(Object.entries(defaultTypeHandlers))
static registerTypeHandler(type: string, handler: IFieldTypeHandler) {
this.typeHandlers.set(type, handler)
}
private getTypeHandler(field: IFieldConfig): IFieldTypeHandler | undefined {
return ShrimpTableModule.typeHandlers.get(field.type)
}
/** 前置验证:基于 IFieldConfig 的通用校验 */
private async validateField(field: IFieldConfig, value: any, item: Record<string, any>): Promise<ILabel | null> {
const isEmpty = value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)
// 1. required
if (field.required && isEmpty) {
return field.rules?.find(r => r.required)?.message || { t: 'shrimp.fieldRequired', params: { field: field.label } }
}
if (isEmpty) return null
// 2. options 校验
if (Array.isArray(field.options)) {
const validValues = new Set(field.options.map(o => o.value))
const values = field.multiple && Array.isArray(value) ? value : [value]
for (const v of values) {
if (!validValues.has(v)) {
return field.rules?.find(r => r.message)?.message || { t: 'shrimp.fieldInvalid', params: { field: field.label } }
}
}
}
// 3. type 基础校验
switch (field.type) {
case ShrimpFieldTypes.String:
if (typeof value !== 'string') return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
case ShrimpFieldTypes.Number:
if (typeof value !== 'number' || Number.isNaN(value)) return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
case ShrimpFieldTypes.Boolean:
if (typeof value !== 'boolean') return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
break
case ShrimpFieldTypes.Date:
if (typeof value !== 'number' && !(value instanceof Date) && isNaN(Date.parse(value))) {
return { t: 'shrimp.fieldTypeError', params: { field: field.label } }
}
break
}
// 4. rules 校验
if (field.rules) {
for (const rule of field.rules) {
const msg = rule.message || { t: 'shrimp.fieldInvalid', params: { field: field.label } }
if (rule.min !== undefined) {
if (typeof value === 'number' && value < rule.min) return { t: 'shrimp.fieldMin', params: { field: field.label, min: rule.min } }
if (typeof value === 'string' && value.length < rule.min) return { t: 'shrimp.fieldMinLength', params: { field: field.label, min: rule.min } }
if (Array.isArray(value) && value.length < rule.min) return { t: 'shrimp.fieldMinLength', params: { field: field.label, min: rule.min } }
}
if (rule.max !== undefined) {
if (typeof value === 'number' && value > rule.max) return { t: 'shrimp.fieldMax', params: { field: field.label, max: rule.max } }
if (typeof value === 'string' && value.length > rule.max) return { t: 'shrimp.fieldMaxLength', params: { field: field.label, max: rule.max } }
if (Array.isArray(value) && value.length > rule.max) return { t: 'shrimp.fieldMaxLength', params: { field: field.label, max: rule.max } }
}
if (rule.pattern) {
const regex = new RegExp(rule.pattern)
if (!regex.test(String(value))) return msg
}
}
}
return null
}
/** 准备新增数据:过滤 readonly → 默认值 → reqFilter → validate */
private async prepareAddItem(item: Record<string, any>): Promise<Record<string, any>> {
const result = { ...item }
for (const field of this.fields) {
if (field.editable === "readonly") {
delete result[field.key]
continue
}
const handler = this.getTypeHandler(field)
if (result[field.key] === undefined) {
const dv = field.defaultValue !== undefined ? field.defaultValue : handler?.defaultValue
if (dv !== undefined) {
result[field.key] = typeof dv === 'function' ? (dv as () => any)() : dv
}
}
if (handler?.reqFilter && result[field.key] !== undefined) {
result[field.key] = await handler.reqFilter(result[field.key], field, result)
}
const fieldErr = await this.validateField(field, result[field.key], result)
if (fieldErr) throw new ShrimpError(fieldErr)
if (handler?.validate && result[field.key] !== undefined) {
const err = await handler.validate(result[field.key], field, result)
if (err) throw new ShrimpError(err)
}
}
return result
}
/** 准备编辑数据:过滤 readonly/addOnly → reqFilter → validate */
private async prepareEditItem(item: Record<string, any>): Promise<Record<string, any>> {
const result = { ...item }
for (const field of this.fields) {
if (field.editable === "readonly" || field.editable === "addOnly") {
delete result[field.key]
continue
}
// 编辑时 undefined 表示未修改,跳过校验并从结果中移除
if (result[field.key] === undefined) {
delete result[field.key]
continue
}
const handler = this.getTypeHandler(field)
if (handler?.reqFilter) {
result[field.key] = await handler.reqFilter(result[field.key], field, result)
}
const fieldErr = await this.validateField(field, result[field.key], result)
if (fieldErr) throw new ShrimpError(fieldErr)
if (handler?.validate) {
const err = await handler.validate(result[field.key], field, result)
if (err) throw new ShrimpError(err)
}
}
return result
}
/** 处理响应数据:resFilter */
private async processResItem(item: Record<string, any>): Promise<Record<string, any>> {
const result = { ...item }
for (const field of this.fields) {
const handler = this.getTypeHandler(field)
if (handler?.resFilter && result[field.key] !== undefined) {
result[field.key] = await handler.resFilter(result[field.key], field, result)
}
}
return result
}
/** 填充关联 _label 并应用 resFilter(多条) */
private async prepareResponseItems(items: any[]): Promise<any[]> {
if (items.length === 0) return items
const populates = this.getRelationPopulates()
if (populates.length > 0 && this.dataSource.populateItems) {
await this.dataSource.populateItems(items, populates, this.root.crudRegistry)
}
return Promise.all(items.map(item => this.processResItem(item)))
}
/** 填充关联 _label 并应用 resFilter(单条) */
private async prepareResponseItem(item: any): Promise<any> {
if (!item) return item
const populates = this.getRelationPopulates()
if (populates.length > 0 && this.dataSource.populateItems) {
await this.dataSource.populateItems([item], populates, this.root.crudRegistry)
}
return this.processResItem(item)
}
private excludeKeys(item: any, keys: string[]): any {
if (keys.length === 0) return item
const result = { ...item }
for (const key of keys) {
delete result[key]
}
return result
}
private filterHidden(item: any): any {
return this.excludeKeys(item, this.fields.filter(f => f.hidden).map(f => f.key))
}
private getRelationFields(): IFieldConfig[] {
return this.fields.filter(f => f.type === "relation" && f.relation)
}
private getRelationPopulates(): IShrimpPopulate[] {
return this.getRelationFields().map(f => ({
key: f.key,
moduleKey: f.relation!.moduleKey,
labelKey: f.relation!.labelKey,
}))
}
/** 将前端 IPageQuery 翻译为数据源 IShrimpQuery */
private buildQuery(query?: IPageQuery & any): IShrimpQuery {
const { keyword, page, pageSize, sortBy, sortOrder, filter, ownerId } = query || {}
const p = page || 1
const ps = pageSize || ShrimpConfig.defaultPageSize
const shrimpQuery: IShrimpQuery = {
offset: (p - 1) * ps,
limit: ps,
}
// filter → where
if (filter && typeof filter === 'object') {
const filterableFields = new Map(this.fields.filter(f => f.filterable).map(f => [f.key, f]))
const stringLikeTypes = new Set(['string', 'textarea'])
const where: Record<string, IShrimpCondition> = {}
for (const [key, value] of Object.entries(filter)) {
const field = filterableFields.get(key)
if (!field) continue
if (value == null) continue
if (Array.isArray(value) && value.length === 0) continue
if (typeof value === 'string' && value === '') continue
const obj = value as any
if (typeof obj === 'object' && !Array.isArray(obj) && obj.min === undefined && obj.max === undefined) continue
if (Array.isArray(value)) {
where[key] = { in: value }
} else if (typeof value === 'object') {
const cond: IShrimpCondition = {}
if (obj.min !== undefined) cond.gte = obj.min
if (obj.max !== undefined) cond.lte = obj.max
where[key] = cond
} else if (typeof value === 'boolean') {
where[key] = { eq: value }
} else if (typeof value === 'string' && stringLikeTypes.has(field.type)) {
where[key] = { like: value }
} else {
where[key] = { eq: value }
}
}
if (Object.keys(where).length > 0) shrimpQuery.where = where
}
// 子表场景: ownerId + 模块 ownerKey 配置 → 强制注入过滤(用户无法绕过)
if (ownerId != null && ownerId !== '' && this.ownerKey) {
shrimpQuery.where = shrimpQuery.where || {}
shrimpQuery.where[this.ownerKey] = { eq: ownerId }
}
// keyword → orWhere(仅对字符串类型字段做模糊匹配)
if (keyword) {
const stringLikeTypes = new Set(['string', 'textarea'])
const searchFields = this.fields
.filter(f => f.searchable && stringLikeTypes.has(f.type))
.map(f => f.key)
if (searchFields.length > 0) {
shrimpQuery.orWhere = searchFields.map(key => ({ [key]: { like: keyword } }))
}
}
// 排序
if (sortBy) {
shrimpQuery.order = [[sortBy, sortOrder === 'desc' ? 'desc' : 'asc']]
}
return shrimpQuery
}
async list(query?: IPageQuery & any): Promise<IPageResult<T>> {
const shrimpQuery = this.buildQuery(query)
const result = await this.dataSource.list(shrimpQuery)
result.list = await this.prepareResponseItems(result.list)
result.list = result.list.map(item => this.filterHidden(item))
return result
}
async get(id: string): Promise<T | null> {
const item = await this.dataSource.get(id)
if (item) {
const processed = await this.prepareResponseItem(item)
return this.filterHidden(processed) as T
}
return item
}
async add(item: Omit<T, '_id'>, ownerId?: string): Promise<T> {
if (ownerId && this.ownerKey) {
(item as any)[this.ownerKey] = ownerId
}
const prepared = await this.prepareAddItem(item as any)
const result = await this.dataSource.add(prepared as Omit<T, '_id'>)
const processed = await this.prepareResponseItem(result)
return this.filterHidden(processed) as T
}
async edit(id: string, item: Partial<T>): Promise<T | null> {
const prepared = await this.prepareEditItem(item as any)
const result = await this.dataSource.edit(id, prepared as Partial<T>)
if (result) {
const processed = await this.prepareResponseItem(result)
return this.filterHidden(processed) as T
}
return result
}
async delete(id: string): Promise<boolean> {
return await this.dataSource.delete(id)
}
async clear(query?: IPageQuery & any): Promise<boolean> {
const hasFilter = query && (
(query.keyword) ||
(query.filter && typeof query.filter === 'object' && Object.keys(query.filter).length > 0)
)
if (hasFilter) {
const shrimpQuery = this.buildQuery(query)
delete shrimpQuery.offset
delete shrimpQuery.limit
const result = await this.dataSource.list(shrimpQuery)
for (const item of result.list as any[]) {
await this.dataSource.delete(item._id)
}
return true
}
return await this.dataSource.clear()
}
async export(query?: IPageQuery & any): Promise<T[]> {
const shrimpQuery = this.buildQuery(query)
delete shrimpQuery.offset
delete shrimpQuery.limit
const result = await this.dataSource.list(shrimpQuery)
result.list = await this.prepareResponseItems(result.list)
return result.list.map(item => this.filterHidden(item))
}
async import(data?: T[], ownerId?: string): Promise<void> {
if (!data || data.length === 0) return
for (const raw of data) {
const item = { ...raw } as Record<string, any>
if (ownerId && this.ownerKey) item[this.ownerKey] = ownerId
const id = item._id ? String(item._id) : undefined
if (id) {
// 有 _id 且数据库里已存在 → 编辑覆盖
const existing = await this.dataSource.get(id)
if (existing) {
const prepared = await this.prepareEditItem(item)
await this.dataSource.edit(id, prepared as Partial<T>)
continue
}
}
// 无 _id,或 _id 在库里找不到 → 当作新增
const prepared = await this.prepareAddItem(item)
await this.dataSource.add(prepared as Omit<T, '_id'>)
}
}
initCrud() {
return this
.addEvent("list", this.power)
.addEvent("get", this.power)
.addEvent("add", { t: "power.add" })
.addEvent("edit", { t: "power.edit" })
.addEvent("delete", { t: "power.delete" })
}
}
/** 用户模块扩展 - 添加登录和获取用户信息功能 */
const userFields: IFieldConfig[] = [
{ key: "username", label: { t: "user.username" }, type: "string", required: true, searchable: true, editable: "addOnly" },
{ key: "password", label: { t: "user.password" }, type: "password", tableHide: true },
{ key: "nickname", label: { t: "user.nickname" }, type: "string", searchable: true },
{ key: "roleId", label: { t: "user.roleId" }, type: "relation", relation: { moduleKey: "role", labelKey: "name" }, filterable: true, multiple: true, defaultValue: [] },
// { key: "status", label: { t: "user.status" }, type: "select", options: [{ label: { t: "base.disabled" }, value: 0 }, { label: { t: "base.enabled" }, value: 1 }], filterable: true, defaultValue: 1 },
{ key: "active", label: { t: "user.active" }, type: "boolean", filterable: true, defaultValue: true },
{ key: "createdAt", label: { t: "user.createdAt" }, type: "date", editable: "readonly", sortable: true, filterable: true },
{ key: "updatedAt", label: { t: "user.updatedAt" }, type: "date", editable: "readonly", sortable: true },
]
export class UserModule extends ShrimpTableModule<WithId<IUser>> {
constructor(public parent: Shrimp | ShrimpModule, dataSource: ShrimpCrud<WithId<IUser>>, fields?: IFieldConfig[]) {
super(parent, "user", dataSource, fields || userFields)
this.initCrud()
}
/** 校验密码,子类可覆盖 */
protected async verifyPassword(storedPassword: string, plainPassword: string): Promise<boolean> {
return bcrypt.compare(plainPassword, storedPassword)
}
/** 从用户对象提取角色 ID 列表,子类可覆盖 */
protected getUserRoleIds(user: WithId<IUser>): string[] {
return Array.isArray(user.roleId) ? user.roleId.map(String) : user.roleId ? [String(user.roleId)] : []
}
/** 用户登录 */
async getUser(username: string, password: string): Promise<WithId<IUser>> {
const user = await this.dataSource.findOne({ username, active: true })
if (!user || !(await this.verifyPassword(user.password, password))) {
throw new ShrimpError({ t: 'shrimp.loginFailed' })
}
return user
}
/** 获取当前用户信息 */
async getModule(userId: string, roleModule: RoleModule): Promise<IModuleInfo[]> {
const user = await this.dataSource.get(userId)
if (!user) {
throw new ShrimpError({ t: 'shrimp.userNotFound' })
}
const roleIds = this.getUserRoleIds(user)
const roles = await Promise.all(roleIds.map(id => roleModule.dataSource.get(id)))
const isSuperAdmin = roles.some(r => r?.isSuperAdmin)
const powerKeys = isSuperAdmin
? (await this.root.allPower()).map(p => p.key)
: roles.flatMap(r => r?.powers || [])
return this.root.getModuleInfo(new Set(powerKeys))
}
/** 覆盖编辑 - 禁止禁用自己、禁止修改自己的角色 */
async edit(id: string, item: Partial<IUser>): Promise<WithId<IUser> | null> {
const op = this.root.operator
if (op && String(op.userId) === String(id)) {
if (item.active === false) {
throw new ShrimpError({ t: 'shrimp.cannotDisableSelf' })
}
if (item.roleId != null) {
const newRoleIds = Array.isArray(item.roleId) ? item.roleId.map(String) : [String(item.roleId)]
const oldUser = await this.dataSource.get(id)
const oldRoleIds = oldUser ? this.getUserRoleIds(oldUser) : []
if (JSON.stringify([...newRoleIds].sort()) !== JSON.stringify([...oldRoleIds].sort())) {
throw new ShrimpError({ t: 'shrimp.cannotChangeOwnRole' })
}
}
}
return super.edit(id, item)
}
/** 覆盖删除 - 禁止删除自己 */
async delete(id: string): Promise<boolean> {
const op = this.root.operator
if (op && String(op.userId) === String(id)) {
throw new ShrimpError({ t: 'shrimp.cannotDeleteSelf' })
}
return super.delete(id)
}
/** 覆盖清空 - 禁止清空所有用户 */
async clear(): Promise<boolean> {
if (this.root.operator) {
throw new ShrimpError({ t: 'shrimp.cannotClearAllUsers' })
}
return super.clear()
}
}
/** 角色模块 */
const roleFields: IFieldConfig[] = [
{ key: "name", label: { t: "role.name" }, type: "string", required: true, searchable: true },
{ key: "description", label: { t: "role.description" }, type: "textarea" },
{ key: "isSuperAdmin", label: { t: "role.isSuperAdmin" }, type: "boolean" },
{ key: "powers", label: { t: "role.powers" }, type: "string" },
{ key: "createdAt", label: { t: "role.createdAt" }, type: "date", editable: "readonly", sortable: true },
{ key: "updatedAt", label: { t: "role.updatedAt" }, type: "date", editable: "readonly", sortable: true },
]
export class RoleModule extends ShrimpTableModule<WithId<IRole>, IRoleProto> {
constructor(public parent: Shrimp | ShrimpModule, dataSource: ShrimpCrud<WithId<IRole>>, fields?: IFieldConfig[]) {
super(parent, "role", dataSource, fields || roleFields)
this.initCrud()
this.addEvent("clear", { t: "power.clear" })
this.addEvent("export", { t: "power.export" })
this.addEvent("import", { t: "power.import" })
this.addEvent("allPower", this.power)
}
async allPower(): Promise<{ key: string; label: ILabel }[]> {
return this.root.allPower()
}
/** 从操作者上下文提取角色 ID 列表,子类可覆盖 */
protected getOperatorRoleIds(op: IShrimpOperator): string[] {
return Array.isArray(op.roleId) ? op.roleId.map(String) : op.roleId ? [String(op.roleId)] : []
}
/** 覆盖编辑 - 禁止编辑自己的任一角色(防止锁死自己) */
async edit(id: string, item: Partial<IRole>): Promise<WithId<IRole> | null> {
const op = this.root.operator
if (op) {
const opRoleIds = this.getOperatorRoleIds(op)
if (opRoleIds.includes(String(id))) {
throw new ShrimpError({ t: 'shrimp.cannotEditOwnRole' })
}
}
return super.edit(id, item)
}
/** 填充超级管理员权限(展示用) */
private async fillSuperAdminPowers(role: WithId<IRole> | null): Promise<WithId<IRole> | null> {
if (role && role.isSuperAdmin) {
const allPowers = await this.allPower()
role.powers = allPowers.map(p => p.key)
}
return role
}
async list(query?: IPageQuery & any): Promise<IPageResult<WithId<IRole>>> {
const result = await super.list(query)
for (const item of result.list) {
if (item.isSuperAdmin) {
const allPowers = await this.allPower()
item.powers = allPowers.map(p => p.key)
}
}
return result
}
async get(id: string): Promise<WithId<IRole> | null> {
const result = await super.get(id)
return this.fillSuperAdminPowers(result)
}
/** 覆盖删除 - 禁止删除自己的任一角色 */
async delete(id: string): Promise<boolean> {
const op = this.root.operator
if (op) {
const opRoleIds = this.getOperatorRoleIds(op)
if (opRoleIds.includes(String(id))) {
throw new ShrimpError({ t: 'shrimp.cannotDeleteOwnRole' })
}
}
return super.delete(id)
}
/** 覆盖清空 - 禁止清空所有角色 */
async clear(): Promise<boolean> {
if (this.root.operator) {
throw new ShrimpError({ t: 'shrimp.cannotClearAllRoles' })
}
return super.clear()
}
}
+362
View File
@@ -0,0 +1,362 @@
/**
* ShrimpServer
* Shrimp 的服务端实现,接入 express + mongoose + JWT
* 提供通用的后台管理 API(登录、鉴权、菜单、事件调度)
*/
import { Router, Request, Response } from "express"
import jsonwebtoken from "jsonwebtoken"
import mongoose, { Schema, Model } from "mongoose"
import { Shrimp, ShrimpCrud, UserModule, RoleModule, RootShrimpPower } from "./Shrimp"
import { MongoShrimpCrud } from "./MongoShrimpCrud"
import { OperationLogModule } from "./OperationLogModule"
import { ShrimpCode, IMeResult, IUser, IRole, IOperationLog, WithId, IMenuItem, IShrimpOperator, ShrimpError } from "./IShrimpType"
declare global {
namespace Express {
interface Request {
user: { _id: string; name: string; power: Set<string>; roleId: string[]; isSuperAdmin: boolean }
}
}
}
// ============== 默认 Mongoose Schema(可导出,也可被子类覆盖) ==============
export const UserSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
nickname: { type: String, default: '' },
roleId: { type: [Schema.Types.ObjectId], ref: 'Role', default: [] },
active: { type: Boolean, default: true }
}, { timestamps: true })
export const RoleSchema = new Schema({
name: { type: String, required: true },
description: { type: String, default: '' },
isSuperAdmin: { type: Boolean, default: false },
powers: { type: [String], default: [] },
}, { timestamps: true })
export const OperationLogSchema = new Schema({
operatorId: { type: String, default: null },
ip: { type: String, default: '' },
method: { type: String, required: true },
args: { type: String, default: '' },
success: { type: Boolean, default: true },
errorMsg: { type: String, default: '' },
createdAt: { type: Number, default: () => Date.now() },
}, { timestamps: false })
// ============== ShrimpServer ==============
export class ShrimpServer extends Shrimp {
userModule: UserModule
roleModule: RoleModule
operationLogModule: OperationLogModule
router: Router = Router()
jwtSecret: string
config: Record<string, any>
globalOptions: Record<string, any> = {}
forcedOptionAccess = new Map<string, RootShrimpPower>()
registerOptions(key: string, options: any, access?: RootShrimpPower) {
this.globalOptions[key] = options
if (access) {
this.forcedOptionAccess.set(key, access)
}
}
/** 缓存的 Mongoose Model,避免重复注册 */
protected _userModel?: Model<IUser>
protected _roleModel?: Model<IRole>
protected _operationLogModel?: Model<IOperationLog>
constructor(jwtSecret: string, config: Record<string, any> = {}, mongodbUri: string = 'mongodb://localhost:27017/shrimp') {
super()
this.jwtSecret = jwtSecret
this.config = config
// 初始化数据源
const userCrud = this.createUserCrud()
const roleCrud = this.createRoleCrud()
const operationLogCrud = this.createOperationLogCrud()
// 初始化模块
this.userModule = this.createUserModule(userCrud)
this.roleModule = this.createRoleModule(roleCrud)
this.operationLogModule = this.createOperationLogModule(operationLogCrud)
// 连接数据库
mongoose.connect(mongodbUri).then(() => {
console.log(mongodbUri + ' MongoDB connected')
this.onDbConnected()
})
// ---- 路由 ----
// 后台配置接口(不需要鉴权)
this.router.get('/config', (_req: Request, res: Response) => {
res.json(this.success(this.config))
})
// 登录接口(不需要鉴权)
this.router.post('/login', async (req: Request, res: Response) => {
const ip = req.ip || ''
const { username, password } = req.body
const args = [{ username, password }]
try {
const user = await this.userModule.getUser(username, password)
const token = jsonwebtoken.sign(this.getJwtPayload(user), this.jwtSecret, { expiresIn: '7d' })
this.operationLogModule.record(user._id, ip, ['login'], args, true)
res.json(this.success({ token }))
} catch (error: any) {
const msg = error instanceof ShrimpError ? error.tip : { t: 'shrimp.loginFailed' }
const errMsg = error instanceof ShrimpError ? JSON.stringify(error.tip) : (error?.message || '')
this.operationLogModule.record(null, ip, ['login'], args, false, errMsg)
res.json(this.fail(ShrimpCode.FAIL, msg))
}
})
// 鉴权中间件
this.router.use(async (req: Request, res: Response, next) => {
try {
const auth = req.headers.authorization
if (!auth || !auth.startsWith('Bearer ')) {
return res.json(this.fail(ShrimpCode.UNAUTHORIZED, { t: 'shrimp.relogin' }, 'No token'))
}
const token = auth.split(' ')[1]
const decoded = jsonwebtoken.verify(token, this.jwtSecret) as any
const user = await this.userModule.dataSource.get(decoded._id)
if (!user || !this.isUserActive(user)) {
return res.json(this.fail(ShrimpCode.UNAUTHORIZED, { t: 'shrimp.userDisabled' }, 'User disabled'))
}
const roleIds = this.getUserRoleIds(user)
const roles = await Promise.all(roleIds.map(id => this.roleModule.dataSource.get(id)))
const isSuperAdmin = roles.some(r => this.isRoleSuperAdmin(r))
const powers = isSuperAdmin
? new Set((await this.allPower()).map(p => p.key))
: new Set(roles.flatMap(r => this.getRolePowers(r)))
req.user = { _id: user._id, name: this.getUserDisplayName(user), power: powers, roleId: roleIds, isSuperAdmin }
next()
} catch (error: any) {
const msg = error instanceof ShrimpError ? error.tip : { t: 'shrimp.relogin' }
return res.json(this.fail(ShrimpCode.UNAUTHORIZED, msg))
}
})
// 获取当前用户信息
this.router.get('/me', async (req: Request, res: Response) => {
try {
const moduleInfo = await this.userModule.getModule(req.user._id, this.roleModule)
const user = await this.userModule.dataSource.get(req.user._id)
if (!user) {
return res.json(this.fail(ShrimpCode.NOT_FOUND, { t: 'shrimp.userNotFound' }))
}
const roleIds = this.getUserRoleIds(user)
const roles = await Promise.all(roleIds.map(id => this.roleModule.dataSource.get(id)))
const isSuperAdmin = roles.some(r => this.isRoleSuperAdmin(r))
const powers = isSuperAdmin
? (await this.allPower()).map(p => p.key)
: roles.flatMap(r => this.getRolePowers(r))
const filteredMenuTree = this.filterMenuTree(this.getMenuTree(), powers)
// 按需收集该用户有权限的模块中引用的全局 options key(自动去重)
const neededKeys = new Set<string>()
for (const mod of moduleInfo) {
for (const field of mod.fields || []) {
if (typeof field.options === 'string') {
neededKeys.add(field.options)
}
}
}
const filteredOptions: Record<string, any> = {}
for (const key of neededKeys) {
if (this.globalOptions[key] != null) {
filteredOptions[key] = this.globalOptions[key]
}
}
for (const [key, access] of this.forcedOptionAccess) {
if (this.globalOptions[key] != null) {
if (isSuperAdmin || powers.includes(access.powerKey)) {
filteredOptions[key] = this.globalOptions[key]
}
}
}
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
res.json(this.success<IMeResult>({
nickname: this.getUserDisplayName(user),
moduleInfo,
menuTree: filteredMenuTree,
options: filteredOptions
}))
} catch (error: any) {
if (error instanceof ShrimpError) {
res.json(this.fail(error.code, error.tip))
} else {
res.json(this.fail(ShrimpCode.FAIL, { t: 'shrimp.serverError' }, error.message))
}
}
})
// 通用事件调用接口
this.router.post('/*path', async (req: Request, res: Response) => {
const raw = req.params.path
const path = (Array.isArray(raw) ? raw.join('/') : raw).split('/').filter(Boolean)
const args = Array.isArray(req.body) ? req.body : [req.body]
const ip = req.ip || ''
const shouldLog = this.operationLogModule.shouldLog(path)
try {
if (path.length === 0) {
return res.json(this.fail(ShrimpCode.FAIL, { t: 'shrimp.emptyPath' }))
}
const powers = req.user.power
if (!this.checkEvent(powers, path)) {
return res.json(this.fail(ShrimpCode.FORBIDDEN, { t: 'shrimp.forbidden' }))
}
const operator: IShrimpOperator = {
userId: req.user._id,
roleId: req.user.roleId,
isSuperAdmin: req.user.isSuperAdmin
}
const result = await Shrimp.asyncLocalStorage.run(operator, () => this.call(path, ...args))
if (shouldLog) this.operationLogModule.record(req.user._id, ip, path, args, true)
res.json(this.success(result))
} catch (error: any) {
if (shouldLog) {
const errMsg = error instanceof ShrimpError ? JSON.stringify(error.tip) : (error?.message || '')
this.operationLogModule.record(req.user?._id ?? null, ip, path, args, false, errMsg)
}
if (error instanceof ShrimpError) {
res.json(this.fail(error.code, error.tip))
} else {
res.json(this.fail(ShrimpCode.SERVER_ERROR, { t: 'shrimp.serverError' }, error.message))
}
}
})
}
// ============== 可覆盖的 Schema 工厂方法 ==============
protected createUserSchema(): mongoose.Schema {
return UserSchema
}
protected createRoleSchema(): mongoose.Schema {
return RoleSchema
}
protected createOperationLogSchema(): mongoose.Schema {
return OperationLogSchema
}
protected getUserModel(): Model<IUser> {
if (!this._userModel) {
this._userModel = mongoose.model<IUser>('shrimp_users', this.createUserSchema())
}
return this._userModel
}
protected getRoleModel(): Model<IRole> {
if (!this._roleModel) {
this._roleModel = mongoose.model<IRole>('shrimp_roles', this.createRoleSchema())
}
return this._roleModel
}
protected getOperationLogModel(): Model<IOperationLog> {
if (!this._operationLogModel) {
this._operationLogModel = mongoose.model<IOperationLog>('shrimp_operation_logs', this.createOperationLogSchema())
}
return this._operationLogModel
}
// ============== 可覆盖的 Crud 工厂方法 ==============
protected createUserCrud(): MongoShrimpCrud<WithId<IUser>> {
return new MongoShrimpCrud<WithId<IUser>>(this.getUserModel())
}
protected createRoleCrud(): MongoShrimpCrud<WithId<IRole>> {
return new MongoShrimpCrud<WithId<IRole>>(this.getRoleModel())
}
protected createOperationLogCrud(): MongoShrimpCrud<WithId<IOperationLog>> {
return new MongoShrimpCrud<WithId<IOperationLog>>(this.getOperationLogModel())
}
// ============== 可覆盖的 Module 工厂方法 ==============
protected createUserModule(dataSource: ShrimpCrud<WithId<IUser>>): UserModule {
return new UserModule(this, dataSource)
}
protected createRoleModule(dataSource: ShrimpCrud<WithId<IRole>>): RoleModule {
return new RoleModule(this, dataSource)
}
protected createOperationLogModule(dataSource: ShrimpCrud<WithId<IOperationLog>>): OperationLogModule {
return new OperationLogModule(this.userModule, dataSource)
}
// ============== 可覆盖的用户/角色字段访问钩子 ==============
/** 从用户对象生成 JWT payload,子类可覆盖 */
protected getJwtPayload(user: WithId<IUser>): Record<string, any> {
return { _id: user._id, roleId: user.roleId }
}
/** 判断用户是否可用,子类可覆盖 */
protected isUserActive(user: WithId<IUser>): boolean {
return user.active === true
}
/** 从用户对象提取角色 ID 列表,子类可覆盖 */
protected getUserRoleIds(user: WithId<IUser>): string[] {
return Array.isArray(user.roleId) ? user.roleId.map(String) : user.roleId ? [String(user.roleId)] : []
}
/** 判断角色是否为超级管理员,子类可覆盖 */
protected isRoleSuperAdmin(role: WithId<IRole> | null): boolean {
return !!role?.isSuperAdmin
}
/** 从角色对象提取权限列表,子类可覆盖 */
protected getRolePowers(role: WithId<IRole> | null): string[] {
return role?.powers || []
}
/** 从用户对象提取显示名称,子类可覆盖 */
protected getUserDisplayName(user: WithId<IUser>): string {
return user.nickname || ''
}
/** 数据库连接后的回调,子类可覆盖以执行连接后的逻辑 */
protected async onDbConnected(): Promise<void> {
}
/** 初始化默认数据(如默认角色、用户),子类可覆盖 */
protected async initDefaultData(name: string = "Administrator", description: "System administrator with all permissions"): Promise<void> {
const result = await this.userModule.dataSource.list({ limit: 1 })
if (result.total > 0) return
console.log("初始化默认数据")
const adminRole = await this.roleModule.dataSource.add({
name: name,
description: description,
isSuperAdmin: true,
powers: [],
createdAt: Date.now(),
updatedAt: Date.now()
})
await this.userModule.add({
username: "admin",
password: "admin",
nickname: "Administrator",
roleId: [adminRole._id],
active: true,
createdAt: Date.now(),
updatedAt: Date.now()
})
}
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Shrimp Server — 公共 API
*
* 内部实现细节(如 ShrimpEvent)未在此处导出,业务请只依赖本文件再导出的符号。
*/
// ===== 类型 / 接口 / 枚举 =====
export {
ShrimpCode,
ShrimpError,
ShrimpFieldTypes,
ShrimpConfig,
isShrimpCondition,
} from "./IShrimpType"
export type {
ILabel,
IShrimpResponse,
IModuleInfo,
ILoginResult,
IMeResult,
IMenuItem,
ITableProto,
ITableCrudProto,
IUser,
IRole,
IOperationLog,
WithId,
IShrimpOperator,
IShrimpPowerData,
ShrimpRequestFn,
IShrimpClient,
ShrimpFieldType,
FieldEditable,
IFieldTypeHandler,
IFieldConfig,
IFieldRule,
IPageQuery,
IPageResult,
IShrimpCondition,
IShrimpPopulate,
IShrimpQuery,
IPowerItem,
IUserProto,
IRoleProto,
} from "./IShrimpType"
// ===== 框架核心 =====
export {
Shrimp,
ShrimpModule,
ShrimpTableModule,
ShrimpPower,
RootShrimpPower,
UserModule,
RoleModule,
defaultTypeHandlers,
} from "./Shrimp"
export type {
IShrimpModuleOptions,
ShrimpCrud,
} from "./Shrimp"
// ===== 服务端实现(Express + Mongoose + JWT) =====
export {
ShrimpServer,
UserSchema,
RoleSchema,
OperationLogSchema,
} from "./ShrimpServer"
// ===== 数据源 =====
export { MongoShrimpCrud } from "./MongoShrimpCrud"
export { MemoryShrimpCrud } from "./MemoryShrimpCrud"
// ===== 可选模块 =====
export { OperationLogModule } from "./OperationLogModule"