码巢引擎2026年开发文档
00-开发规范
后端规范
README
后端开发手册
前端规范
README
TypeScript最佳实践
前端布局规范
前端页面模板
前端颜色与组件规范
核心规范
组件配置手册
问题排查指南
页面模板
最佳实践
README
bp-20260223-m7ps
图片上传优化总结
BUG自动记录系统使用指南
README
TYPE_SAFETY_GUIDE
常见BUG知识库
常见BUG知识库
开发前检查清单
开发安全规范
开发规范-完整版-含FutureBirdAadminAi部署
数据模型字典
文档分类规范
文档标准化规范
文档模板-基础版
文档模板-技术版
类型安全快速参考卡
类型安全规范体系
规范更新指南
过期文档清理机制
错误处理规范
错误预防指南
常见BUG知识库
常见BUG知识库
01-快速开始
Gitee快速开始
README
协作快速开始
快速开始
质量保证快速开始
02-部署指南
Docker更新指南
Docker部署
FutureBirdAadminAi部署指南
FutureBirdAadminAi部署问题分析
README
发布指南
宝塔Docker部署教程
宝塔PM2部署教程
宝塔图形化部署教程
快速发布指南
数据库和依赖变更处理指南
构建和发布
构建标准
构建检查清单
生产部署快速开始
生产部署方案
生产部署标准
生产部署检查清单
程序备份性能
自动修复和发布指南
自动化发布命令使用指南
部署快速开始
部署指南
项目更新部署指南
03-开发指南
Git凭据配置
Git推送规则
Git自动配置
README
全局样式
协作设置
定时任务
开发指南
开发流程
开发环境标准
技术改进
贡献指南
项目目录树
项目目录结构
04-API文档
API接口文档
README
hr-api
企业API
05-数据库
DATABASE_SCHEMA
README
分区指南
数据库字典
数据持久化
数据模型统一
数据迁移
06-架构设计
RBAC-PERMISSIONS
README
SaaS客户引导流程设计
companyId统一规范
employee-permission-system-design
enterprise-data-linkage
仓库实现总结
仓库模式
企业管理端员工权限系统分析
前端架构
前端重构总结
员工权限系统评估报告
员工管理菜单重构方案
权限系统混乱问题分析
架构优化计划
架构使用指南
架构结构
架构结构
状态管理
用户身份管理体系
系统架构
面试管理模块重构规划
项目技术栈
07-测试质量
README
测试修复标准
测试报告
质量保证系统
08-版本管理
CHANGELOG
README
VERSION_RULES
09-配置指南
README
SMTP配置指南
主题切换指南
渠道配置指南
环境变量指南
环境隔离
12-项目记忆
README
知识库导入指南
记忆系统指南
13-迁移指南
README
备份迁移指南
管理员迁移指南
迁移快速开始
17-其他
README
压缩摘要
18-开放平台
01-架构设计
02-API接口设计
03-安全机制
04-前端设计
05-数据库设计
开放平台API指南
开放平台API说明
19-智能进化
AI执行规则
AI进化机制
README
自动化实现总览
黄金规则
40-操作教程
README
微信公众号域名配置指南
微信本地开发调试指南
44-技能文件
alipay-payment-integration
references
checklist
SKILL
audio
python
README
typescript
README
SKILL
database
python
README
typescript
README
SKILL
design-style-thinking
SKILL
doctor
references
sql-patterns
SKILL
document-generation
python
README
SKILL
email
SKILL
embedding
python
README
typescript
README
SKILL
expo-advanced
references
audio-record-play
file-upload
masonry-layout
save-to-gallery
top-tab-navigation
SKILL
feishu-base
SKILL
feishu-message
SKILL
fetch-url
python
README
typescript
README
SKILL
frontend-design
LICENSE
SKILL
FutureBird-coding-web-performance-best-practice
SKILL
general-dev-preview
references
web-preview
SKILL
image-generation
python
README
typescript
README
SKILL
knowledge
references
python
README
typescript
README
cli
SKILL
llm
python
README
typescript
README
SKILL
miniapp-upload-asr
SKILL
pptx-generation
python
README
SKILL
project-memory-loader
scripts
project_memory_loader
SKILL
repair
scripts
merge-commit-map
SKILL
shadcn-web-base-theme
assets
colors
amber
artistic-green
bento-blue
blue
cyan
emerald
fuchsia
gray
green
indigo
lime
low-pink
neutral
orange
purple
red
retro-brown
rose
sky
supbase-green
teal
tech-purple
vintage-grey
violet
yellow
fonts
business
classic
playful
radius
2xl
2xs
lg
md
none
sm
xl
xs
shadow
artistic
bento
cool
retro
superbase
tech
tool
vintage
default
references
colors
fonts
quick
radius
shadows
scripts
theme
SKILL
package
skill-creator-coze
scripts
init_skill
quick_validate
SKILL
storage
python
README
typescript
README
SKILL
supabase
assets
supabase-client
supabase-client
references
_future
asset-supabase-browser
asset-supabase-config-inject
asset-supabase-config-route
python-auth
python-realtime
python-storage
typescript-auth
typescript-realtime
typescript-storage
typescript-supabase-browser
typescript-supabase-config-inject
typescript-supabase-config-route
python
README
database
edge-functions
orm-model-guide
supabase_client
typescript
README
database
drizzle-schema-guide
edge-functions
supabase-client
cli
rls
SKILL
supabase-auth
references
typescript
supabase-browser
supabase-config-inject
supabase-config-route
auth-config
verify-session
SKILL
ui-design-ref
reference
3D黏土风
克莱因蓝高定风
暗黑科技风
杂志风
极光柔和
柔和卡片
玻璃拟态
纯白极简风
自然有机
SKILL
ui-ux-pro-max
scripts
core
design_system
search
SKILL
vercel-composition-patterns
rules
architecture-avoid-boolean-props
architecture-compound-components
patterns-children-over-render-props
patterns-explicit-variants
react19-no-forwardref
state-context-interface
state-decouple-implementation
state-lift-state
AGENTS
SKILL
vercel-react-best-practices
rules
advanced-event-handler-refs
advanced-init-once
advanced-use-latest
async-api-routes
async-defer-await
async-dependencies
async-parallel
async-suspense-boundaries
bundle-barrel-imports
bundle-conditional
bundle-defer-third-party
bundle-dynamic-imports
bundle-preload
client-event-listeners
client-localstorage-schema
client-passive-event-listeners
client-swr-dedup
js-batch-dom-css
js-cache-function-results
js-cache-property-access
js-cache-storage
js-combine-iterations
js-early-exit
js-hoist-regexp
js-index-maps
js-length-check-first
js-min-max-loop
js-set-map-lookups
js-tosorted-immutable
rendering-activity
rendering-animate-svg-wrapper
rendering-conditional-render
rendering-content-visibility
rendering-hoist-jsx
rendering-hydration-no-flicker
rendering-hydration-suppress-warning
rendering-svg-precision
rendering-usetransition-loading
rerender-defer-reads
rerender-dependencies
rerender-derived-state-no-effect
rerender-derived-state
rerender-functional-setstate
rerender-lazy-state-init
rerender-memo-with-default-value
rerender-memo
rerender-move-effect-to-event
rerender-simple-expression-in-memo
rerender-transitions
rerender-use-ref-transient-values
server-auth-actions
server-cache-lru
server-cache-react
server-dedup-props
server-parallel-fetching
server-serialization
AGENTS
SKILL
video-edit
python
README
typescript
README
SKILL
video-generation
python
README
typescript
README
SKILL
volcano-ark
SKILL
web-design-guidelines
SKILL
web-search
python
README
typescript
README
SKILL
webrtc-best-practice
SKILL
websocket-guide
references
nextjs
nodejs
SKILL
wechat-bot
SKILL
wechat-official-account
SKILL
README
README
未来鸟:企业数字化转型奔腾的力量!
-
+
首页
管理员迁移指南
> **文档版本**: v1.0.0 > **创建日期**: 2026-02-12 > **最后更新**: 2026-02-12 > **维护人**: 未来鸟FutureBird码巢企业服务引擎开发组 > **状态**: [最新] > **搜索标签**: 迁移, 管理员, 用户迁移, 数据迁移 --- # Manager迁移到仓储模式指南 本指南展示如何将现有的Manager类迁移到使用仓储模式,以`TenantManager`为例。 ## 迁移前后对比 ### 1. 导入变化 **迁移前**: ```typescript import { eq, desc, and, like, or, count, sql } from "drizzle-orm"; import { getDb } from "FutureBirdAadminAi-coding-dev-sdk"; import { saasTenants, saasCompanies } from "./shared/schema"; ``` **迁移后**: ```typescript import { getTenantRepository } from '@/infrastructure/database/repositories'; import type { ITenantRepository } from '@/domains/tenant/repositories/ITenantRepository'; import type { SaasTenant, InsertSaasTenant } from '@/storage/database/shared/schema'; ``` ### 2. 类构造函数 **迁移前**: ```typescript export class TenantManager { // 没有构造函数,直接在方法中使用getDb() } ``` **迁移后**: ```typescript export class TenantManagerV2 { private tenantRepository: ITenantRepository; constructor() { this.tenantRepository = getTenantRepository(); } } ``` ### 3. 数据库访问方式 #### 查询单个对象 **迁移前**: ```typescript async getTenantById(id: string): Promise<Tenant | null> { const db = await getDb(); const [tenant] = await db .select() .from(saasTenants) .where(eq(saasTenants.id, id)) .limit(1); return tenant || null; } ``` **迁移后**: ```typescript async getTenantById(id: string): Promise<SaasTenant | null> { return await this.tenantRepository.findById(id); } ``` #### 查询列表 **迁移前**: ```typescript async getTenants(options: { skip?: number; limit?: number; filters?: any; }) { const db = await getDb(); const conditions = []; if (filters.tenantNo) { conditions.push(eq(saasTenants.tenantNo, filters.tenantNo)); } if (filters.status) { conditions.push(eq(saasTenants.status, filters.status)); } const tenants = await db .select() .from(saasTenants) .where(conditions.length > 0 ? and(...conditions) : undefined) .orderBy(desc(saasTenants.createdAt)) .limit(validatedPagination.limit) .offset(validatedPagination.skip); return tenants; } ``` **迁移后**: ```typescript async getTenants(options: { skip?: number; limit?: number; filters?: any; }) { const repoFilters: any = {}; if (filters.tenantNo) { repoFilters.tenantNo = filters.tenantNo; } if (filters.status) { repoFilters.status = filters.status; } const tenants = await this.tenantRepository.findAll({ filters: repoFilters, pagination: { skip: options.skip || 0, limit: options.limit || 20 }, sort: { field: 'createdAt' as any, direction: 'desc' } }); return tenants; } ``` #### 创建数据 **迁移前**: ```typescript async createTenant(data: InsertTenant): Promise<Tenant> { const validated = createTenantSchema.parse(data); const db = await getDb(); const [tenant] = await db.insert(saasTenants).values(validated).returning(); return tenant; } ``` **迁移后**: ```typescript async createTenant(data: InsertSaasTenant): Promise<SaasTenant> { const validated = createTenantSchema.parse(data); return await this.tenantRepository.create(validated); } ``` #### 更新数据 **迁移前**: ```typescript async updateTenant(id: string, data: Partial<InsertTenant>): Promise<Tenant | null> { const validated = updateTenantSchema.parse(data); const db = await getDb(); const [tenant] = await db .update(saasTenants) .set({ ...validated, updatedAt: new Date() }) .where(eq(saasTenants.id, id)) .returning(); return tenant || null; } ``` **迁移后**: ```typescript async updateTenant(id: string, data: Partial<InsertSaasTenant>): Promise<SaasTenant | null> { const validated = updateTenantSchema.parse(data); const tenant = await this.tenantRepository.update(id, validated as any); invalidateCache('tenant'); // 清除缓存 return tenant; } ``` #### 删除数据 **迁移前**: ```typescript async deleteTenant(id: string): Promise<boolean> { const db = await getDb(); const result = await db.delete(saasTenants).where(eq(saasTenants.id, id)); return (result.rowCount ?? 0) > 0; } ``` **迁移后**: ```typescript async deleteTenant(id: string): Promise<boolean> { const deleted = await this.tenantRepository.delete(id); invalidateCache('tenant'); // 清除缓存 return deleted; } ``` #### 统计数量 **迁移前**: ```typescript async countTenants(filters?: any): Promise<number> { const db = await getDb(); const conditions = []; if (filters?.status) { conditions.push(eq(saasTenants.status, filters.status)); } const [result] = await db .select({ count: count() }) .from(saasTenants) .where(conditions.length > 0 ? and(...conditions) : undefined); return result?.count || 0; } ``` **迁移后**: ```typescript async countTenants(filters?: any): Promise<number> { const repoFilters: any = {}; if (filters?.status) { repoFilters.status = filters.status; } return await this.tenantRepository.count(repoFilters); } ``` ### 4. 业务逻辑保留 迁移过程中,以下业务逻辑保持不变: - **数据验证**:继续使用Zod schema进行数据验证 - **缓存管理**:继续使用缓存机制 - **自定义业务逻辑**:如余额更新、激活/停用等 **示例**: ```typescript // 保留的业务逻辑 async updateTenantBalance( tenantId: string, amount: number, type: 'add' | 'subtract' ): Promise<SaasTenant | null> { const tenant = await this.getTenantById(tenantId); if (!tenant) return null; const currentBalance = Number(tenant.balance || 0); const newBalance = type === 'add' ? currentBalance + amount : currentBalance - amount; return this.updateTenant(tenantId, { balance: newBalance.toString(), }); } ``` ## 迁移步骤 ### 步骤1:分析现有Manager 1. 列出所有数据库操作(查询、插入、更新、删除) 2. 识别业务逻辑(验证、缓存、计算等) 3. 记录依赖的表和字段 ### 步骤2:检查仓储接口 确保对应的仓储接口已经定义了所需的方法: ```typescript // 检查仓储接口 import type { ITenantRepository } from '@/domains/tenant/repositories/ITenantRepository'; // 查看是否有所需的方法 interface ITenantRepository extends IRepository<SaasTenant, InsertSaasTenant, Partial<InsertSaasTenant>> { findByTenantNo(tenantNo: string): Promise<SaasTenant | null>; // ... 其他方法 } ``` ### 步骤3:创建新的Manager类 ```typescript export class TenantManagerV2 { private tenantRepository: ITenantRepository; constructor() { this.tenantRepository = getTenantRepository(); } // ... 迁移后的方法 } ``` ### 步骤4:迁移方法 按照"数据访问方式"部分的示例,逐个迁移方法。 **迁移原则**: 1. 先迁移简单方法( findById, create, update, delete ) 2. 再迁移查询方法( findAll, count ) 3. 最后处理复杂方法(跨表查询、聚合计算等) ### 步骤5:处理特殊情况 #### 模糊查询 如果仓储不支持模糊查询,可以在Manager层过滤: ```typescript // 仓储只支持精确匹配 const tenants = await this.tenantRepository.findAll({ filters: { status: 'ACTIVE' } }); // 在应用层进行模糊匹配 const filtered = tenants.filter(t => t.tenantName.includes(searchTerm) ); ``` #### 跨表查询 如果需要跨表查询,有几种处理方式: **方式1:在仓储中添加专门的跨表查询方法** ```typescript // 在ITenantRepository中定义 getCompanyCountByTenantIds(tenantIds: string[]): Promise<{ tenantId: string; count: number }[]>; // 在TenantRepository中实现 async getCompanyCountByTenantIds(tenantIds: string[]): Promise<{ tenantId: string; count: number }[]> { // 使用join或子查询实现 } ``` **方式2:使用事务** ```typescript async getTenantWithCompanyCount(tenantId: string) { return await this.tenantRepository.transaction(async (tx) => { const tenant = await tx.select().from(saasTenants).where(eq(saasTenants.id, tenantId)); const count = await tx.select({ count: count() }).from(saasCompanies).where(eq(saasCompanies.tenantId, tenantId)); return { ...tenant, companyCount: count }; }); } ``` ### 步骤6:测试 1. **单元测试**:确保每个方法的功能与原方法一致 2. **集成测试**:确保与其他模块的交互正常 3. **性能测试**:确保迁移后的性能不降低 ### 步骤7:替换使用 ```typescript // 旧代码 import { tenantManager } from '@/storage/database/tenantManager'; const tenant = await tenantManager.getTenantById(id); // 新代码 import { tenantManagerV2 } from '@/application/services/tenantManagerV2'; const tenant = await tenantManagerV2.getTenantById(id); ``` ## 优势对比 ### 迁移前的问题 1. **代码重复**:每个Manager都要实现类似的查询逻辑 2. **难以测试**:直接依赖数据库,难以mock 3. **业务逻辑混杂**:数据访问和业务逻辑混在一起 4. **维护困难**:修改查询逻辑需要改多个地方 ### 迁移后的优势 1. **代码复用**:通用逻辑在BaseRepository中统一实现 2. **易于测试**:可以mock仓储接口进行单元测试 3. **关注点分离**:数据访问逻辑封装在仓储中 4. **易于维护**:修改查询逻辑只需改仓储层 ## 最佳实践 1. **保留验证层**:数据验证应该在Manager层,不在仓储层 2. **保留缓存层**:缓存逻辑应该在Manager层 3. **简化仓储**:仓储只负责数据访问,不包含业务逻辑 4. **使用类型**:充分利用TypeScript的类型系统 5. **渐进迁移**:先迁移简单的Manager,积累经验后再迁移复杂的 ## 常见问题 ### Q1:仓储中没有我需要的方法怎么办? **A**:有两种方式: 1. 在仓储接口中添加新方法,然后在仓储实现中实现它 2. 在Manager中使用事务直接操作数据库 ### Q2:如何处理复杂的聚合查询? **A**: 1. 如果查询频繁使用,建议在仓储中添加专门的方法 2. 如果偶尔使用,可以在Manager中使用事务处理 ### Q3:迁移后性能会下降吗? **A**:通常不会。因为: 1. 仓储层做了优化(如索引使用、查询缓存) 2. 减少了代码重复,有利于维护和性能优化 ### Q4:是否需要一次性迁移所有Manager? **A**:不需要。可以逐步迁移: 1. 先迁移新功能使用仓储模式 2. 然后逐步迁移现有功能 3. 旧代码和新代码可以共存 ## 参考资源 - [仓储模式架构说明](../06-架构设计/仓库模式.md) - [仓储实施总结](../06-架构设计/仓库实现总结.md) - [TenantManagerV2示例](../../src/application/services/tenantManagerV2.ts)
未来鸟
2026年7月27日 10:43
转发
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
分享
链接
类型
密码
更新密码
有效期
Markdown文件
Word文件
PDF文档(打印)
AI