create-dp-koa 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/README.md +50 -0
  2. package/index.mjs +97 -0
  3. package/package.json +33 -0
  4. package/template/.env.development +9 -0
  5. package/template/.env.production +12 -0
  6. package/template/.github/workflows/ci-cd.yml +182 -0
  7. package/template/.trae/documents/controller_development_plan.md +386 -0
  8. package/template/.trae/skills/00-backend-core.skill.md +50 -0
  9. package/template/.trae/skills/01-backend-skill-router.skill.md +55 -0
  10. package/template/.trae/skills/10-backend-api.skill.md +54 -0
  11. package/template/.trae/skills/11-backend-controller-recipes.skill.md +107 -0
  12. package/template/.trae/skills/20-backend-repository.skill.md +25 -0
  13. package/template/.trae/skills/21-backend-service.skill.md +135 -0
  14. package/template/.trae/skills/25-backend-comments-and-doc.skill.md +97 -0
  15. package/template/.trae/skills/30-backend-validation.skill.md +320 -0
  16. package/template/.trae/skills/40-backend-error-logging.skill.md +21 -0
  17. package/template/.trae/skills/50-backend-bootstrap-lifecycle.skill.md +90 -0
  18. package/template/.trae/skills/60-backend-router-registration.skill.md +71 -0
  19. package/template/.trae/skills/70-backend-middleware.skill.md +98 -0
  20. package/template/.trae/skills/80-backend-utils-and-libs.skill.md +90 -0
  21. package/template/.trae/skills/85-backend-plugins.rule.md +64 -0
  22. package/template/.trae/skills/90-backend-testing.skill.md +29 -0
  23. package/template/.trae/skills/README.md +49 -0
  24. package/template/.vscode/launch.json +38 -0
  25. package/template/.vscode/settings.json +1 -0
  26. package/template/Dockerfile +36 -0
  27. package/template/README.md +229 -0
  28. package/template/docker-compose.yml +135 -0
  29. package/template/docs/API_DOCUMENTATION.md +837 -0
  30. package/template/docs/ARCHITECTURE_REFACTOR.md +109 -0
  31. package/template/docs/CACHE_MIGRATION_GUIDE.md +142 -0
  32. package/template/docs/DEPLOYMENT_GUIDE.md +1062 -0
  33. package/template/docs/DEVELOPMENT_GUIDE.md +1097 -0
  34. package/template/docs/DOCUMENTATION_CLEANUP_REPORT.md +166 -0
  35. package/template/docs/DOCUMENTATION_COMPLETION_REPORT.md +223 -0
  36. package/template/docs/DOCUMENTATION_INDEX.md +294 -0
  37. package/template/docs/DOCUMENTATION_STRUCTURE.md +221 -0
  38. package/template/docs/ENTERPRISE_ANNOTATION_SYSTEM_GUIDE.md +2069 -0
  39. package/template/docs/ENTERPRISE_DATABASE_ARCHITECTURE.md +318 -0
  40. package/template/docs/ENTERPRISE_DEPLOYMENT_GUIDE.md +547 -0
  41. package/template/docs/ENTERPRISE_ERROR_HANDLING_GUIDE.md +357 -0
  42. package/template/docs/ENTERPRISE_LOGGING_SYSTEM_GUIDE.md +494 -0
  43. package/template/docs/ENVIRONMENT_CONFIG_EXAMPLE.md +69 -0
  44. package/template/docs/FINAL_IMPLEMENTATION_SUMMARY.md +206 -0
  45. package/template/docs/HEALTH_CHECK_ROUTE_FIX.md +134 -0
  46. package/template/docs/IMPLEMENTATION_CHECKLIST.md +204 -0
  47. package/template/docs/INSTALLATION_GUIDE.md +611 -0
  48. package/template/docs/INTERCEPTOR_TESTING_REPORT.md +226 -0
  49. package/template/docs/INTERCEPTOR_TESTING_SCRIPTS.md +143 -0
  50. package/template/docs/LOGGING_OPTIMIZATION_GUIDE.md +126 -0
  51. package/template/docs/MEMORY_DATABASE_GUIDE.md +212 -0
  52. package/template/docs/NEW_ROUTER_INTEGRATION_GUIDE.md +345 -0
  53. package/template/docs/NEW_ROUTER_INTEGRATION_SUMMARY.md +259 -0
  54. package/template/docs/NEW_ROUTER_USAGE_GUIDE.md +364 -0
  55. package/template/docs/QUICK_START.md +268 -0
  56. package/template/docs/ROUTE_SLASH_COMPATIBILITY_FIX.md +191 -0
  57. package/template/docs/SERVICE_INTERCEPTOR_GUIDE.md +243 -0
  58. package/template/docs/SERVICE_LAYER_INDEX.md +205 -0
  59. package/template/docs/SERVICE_PATTERN_GUIDE.md +270 -0
  60. package/template/docs/SERVICE_RETURN_VALUE_SPECIFICATION.md +466 -0
  61. package/template/docs/SWAGGER_DEBUG_MODE_GUIDE.md +80 -0
  62. package/template/docs/SWAGGER_INTEGRATION_GUIDE.md +416 -0
  63. package/template/docs/TRANSACTION_MANAGER_USAGE.md +360 -0
  64. package/template/docs/TROUBLESHOOTING.md +869 -0
  65. package/template/env.production.example +62 -0
  66. package/template/jest.config.js +34 -0
  67. package/template/package-lock.json +13240 -0
  68. package/template/package.json +119 -0
  69. package/template/patches/typeorm+0.3.25.patch +22 -0
  70. package/template/scripts/sync-template.mjs +84 -0
  71. package/template/scripts/test-annotation-system.sh +48 -0
  72. package/template/scripts/test-core-functionality.sh +28 -0
  73. package/template/src/annotations/decorators/ConfigManagement.ts +9 -0
  74. package/template/src/annotations/decorators/DistributedTracing.ts +9 -0
  75. package/template/src/annotations/decorators/EnterprisePerformance.ts +9 -0
  76. package/template/src/annotations/decorators/PerformanceMonitor.ts +32 -0
  77. package/template/src/annotations/decorators/SecurityAudit.ts +9 -0
  78. package/template/src/annotations/index.ts +50 -0
  79. package/template/src/annotations/processors/ConfigManagementProcessor.ts +369 -0
  80. package/template/src/annotations/processors/DistributedTracingProcessor.ts +288 -0
  81. package/template/src/annotations/processors/EnterprisePerformanceProcessor.ts +189 -0
  82. package/template/src/annotations/processors/PerformanceMonitorProcessor.ts +101 -0
  83. package/template/src/annotations/processors/SecurityAuditProcessor.ts +345 -0
  84. package/template/src/annotations/processors/SwaggerProcessor.ts +612 -0
  85. package/template/src/annotations/processors/index.ts +10 -0
  86. package/template/src/app.ts +123 -0
  87. package/template/src/controllers/base.controller.ts +41 -0
  88. package/template/src/controllers/cacheManagement.controller.ts +131 -0
  89. package/template/src/controllers/captcha.controller.ts +57 -0
  90. package/template/src/controllers/demo/AnnotationDemoController.ts +118 -0
  91. package/template/src/controllers/example/EnterpriseExampleController.ts +297 -0
  92. package/template/src/controllers/example/ExampleController.ts +110 -0
  93. package/template/src/controllers/example/NewAnnotationExampleController.ts +159 -0
  94. package/template/src/controllers/example/SwaggerExampleController.ts +205 -0
  95. package/template/src/controllers/example/TransactionExample.controller.ts +336 -0
  96. package/template/src/controllers/health.controller.ts +235 -0
  97. package/template/src/controllers/home/register.controller.ts +58 -0
  98. package/template/src/controllers/home/ytGoods.controller.ts +92 -0
  99. package/template/src/controllers/home/ytShop.controller.ts +135 -0
  100. package/template/src/controllers/home/ytUser.controller.ts +89 -0
  101. package/template/src/controllers/logManagement.controller.ts +396 -0
  102. package/template/src/controllers/public/emailSend.controller.ts +65 -0
  103. package/template/src/controllers/public/ytUserAuth.controller.ts +174 -0
  104. package/template/src/controllers/testData.controller.ts +253 -0
  105. package/template/src/dto/controller/example/NewAnnotationExampleController.dto.ts +73 -0
  106. package/template/src/dto/controller/home/emailSend.controller.dto.ts +40 -0
  107. package/template/src/dto/controller/home/register.controller.dto.ts +45 -0
  108. package/template/src/dto/controller/home/ytGoods.controller.dto.ts +55 -0
  109. package/template/src/dto/controller/home/ytShop.controller.dto.ts +69 -0
  110. package/template/src/dto/controller/home/ytUser.controller.dto.ts +44 -0
  111. package/template/src/dto/controller/public/ytUserAuth.controller.dto.ts +63 -0
  112. package/template/src/dto/goods.dto.ts +212 -0
  113. package/template/src/dto/service/ytService.dto.ts +13 -0
  114. package/template/src/dto/user.dto.ts +177 -0
  115. package/template/src/entity/base.entity.ts +13 -0
  116. package/template/src/entity/columnTypes.ts +13 -0
  117. package/template/src/entity/goodsImagesUnlockKey.entity.ts +33 -0
  118. package/template/src/entity/goodsUnlocker.entity.ts +34 -0
  119. package/template/src/entity/index.ts +15 -0
  120. package/template/src/entity/shop.entity.ts +52 -0
  121. package/template/src/entity/shopUser.entity.ts +41 -0
  122. package/template/src/entity/ytGoods.entity.ts +94 -0
  123. package/template/src/entity/ytUser.entity.ts +96 -0
  124. package/template/src/examples/InterceptorExampleRunner.ts +284 -0
  125. package/template/src/examples/ServiceInterceptorExample.ts +214 -0
  126. package/template/src/examples/SwaggerProcessorExample.ts +169 -0
  127. package/template/src/examples/TransactionManagerDemo.ts +377 -0
  128. package/template/src/examples/cacheExamples.ts +155 -0
  129. package/template/src/framework/decorator/controller.ts +311 -0
  130. package/template/src/framework/decorator/processor/AnnotationDecorators.ts +100 -0
  131. package/template/src/framework/decorator/processor/AnnotationProcessor.ts +156 -0
  132. package/template/src/framework/decorator/processor/AnnotationProcessorConfig.ts +45 -0
  133. package/template/src/framework/decorator/processor/AnnotationRegistry.ts +117 -0
  134. package/template/src/framework/decorator/processor/AnnotationSystemInitializer.ts +95 -0
  135. package/template/src/framework/decorator/processor/ProcessorManager.ts +76 -0
  136. package/template/src/framework/decorator/processor/processors/CustomProcessors.ts +126 -0
  137. package/template/src/framework/decorator/processor/processors/DefaultProcessors.ts +207 -0
  138. package/template/src/framework/decorator/refactored/DecoratorFactory.ts +99 -0
  139. package/template/src/framework/decorator/refactored/DecoratorMetadataManager.ts +125 -0
  140. package/template/src/framework/decorator/refactored/DecoratorValidator.ts +128 -0
  141. package/template/src/framework/decorator/refactored/TypeSafeDecorators.ts +139 -0
  142. package/template/src/framework/decorator/refactored/index.ts +98 -0
  143. package/template/src/framework/decorator/swagger.ts +150 -0
  144. package/template/src/framework/interceptors/AdvancedServiceCallInterceptor.ts +375 -0
  145. package/template/src/framework/interceptors/ServiceCallInterceptor.ts +348 -0
  146. package/template/src/framework/interceptors/index.ts +19 -0
  147. package/template/src/framework/plugins/registry.ts +63 -0
  148. package/template/src/framework/plugins/types.ts +15 -0
  149. package/template/src/framework/types/ServiceResult.ts +151 -0
  150. package/template/src/framework/types/index.ts +16 -0
  151. package/template/src/framework/utils/CacheManager.ts +430 -0
  152. package/template/src/framework/utils/CacheService.ts +248 -0
  153. package/template/src/framework/utils/DtoValidator.ts +164 -0
  154. package/template/src/framework/utils/MigrationHelper.ts +179 -0
  155. package/template/src/framework/utils/MigrationManager.ts +256 -0
  156. package/template/src/framework/utils/NewRouter.ts +207 -0
  157. package/template/src/framework/utils/TransactionManager.ts +172 -0
  158. package/template/src/framework/utils/bootstrap.ts +445 -0
  159. package/template/src/framework/utils/cache.ts +269 -0
  160. package/template/src/framework/utils/databaseConfig.ts +148 -0
  161. package/template/src/framework/utils/db.ts +39 -0
  162. package/template/src/framework/utils/dbMonitor.ts +106 -0
  163. package/template/src/framework/utils/dynamicSwagger.ts +410 -0
  164. package/template/src/framework/utils/function.ts +61 -0
  165. package/template/src/framework/utils/gracefulShutdown.ts +131 -0
  166. package/template/src/framework/utils/logger.ts +388 -0
  167. package/template/src/framework/utils/metrics.ts +182 -0
  168. package/template/src/framework/utils/router.ts +417 -0
  169. package/template/src/framework/utils/swagger.ts +184 -0
  170. package/template/src/framework/utils/testDb.ts +19 -0
  171. package/template/src/framework/utils/token.ts +23 -0
  172. package/template/src/framework/utils/transform.ts +17 -0
  173. package/template/src/libs/aokEmailSender.ts +42 -0
  174. package/template/src/libs/captcha.ts +37 -0
  175. package/template/src/libs/cos.ts +45 -0
  176. package/template/src/libs/mCache.ts +7 -0
  177. package/template/src/libs/serviceValidate.ts +3 -0
  178. package/template/src/libs/tecentSms.ts +51 -0
  179. package/template/src/middlewares/a.middleware.ts +6 -0
  180. package/template/src/middlewares/error.middleware.ts +14 -0
  181. package/template/src/middlewares/logging.middleware.ts +187 -0
  182. package/template/src/middlewares/static.middleware.ts +79 -0
  183. package/template/src/middlewares/swagger.middleware.ts +70 -0
  184. package/template/src/middlewares/token.middleware.ts +32 -0
  185. package/template/src/migrations/1700000000000-InitialDatabaseStructure.ts +172 -0
  186. package/template/src/migrations/index.ts +6 -0
  187. package/template/src/plugins/weboffice/core/context.ts +47 -0
  188. package/template/src/plugins/weboffice/core/errors.ts +51 -0
  189. package/template/src/plugins/weboffice/core/types.ts +63 -0
  190. package/template/src/plugins/weboffice/core/utils.ts +7 -0
  191. package/template/src/plugins/weboffice/entities/index.ts +3 -0
  192. package/template/src/plugins/weboffice/entities/webofficeFile.entity.ts +28 -0
  193. package/template/src/plugins/weboffice/entities/webofficeFileVersion.entity.ts +29 -0
  194. package/template/src/plugins/weboffice/http/routes.ts +179 -0
  195. package/template/src/plugins/weboffice/index.ts +23 -0
  196. package/template/src/plugins/weboffice/services/webofficeCallback.service.ts +274 -0
  197. package/template/src/repository/UserRepository.ts +122 -0
  198. package/template/src/repository/base/BaseRepository.ts +124 -0
  199. package/template/src/repository/interfaces/IBaseRepository.ts +67 -0
  200. package/template/src/routers/index.ts +49 -0
  201. package/template/src/service/base.service.ts +116 -0
  202. package/template/src/service/paramValidateTest.service.ts +139 -0
  203. package/template/src/service/ytGoods.service.ts +42 -0
  204. package/template/src/service/ytShop.service.ts +90 -0
  205. package/template/src/service/ytUser.service.ts +451 -0
  206. package/template/src/test/swaggerParameterTest.ts +90 -0
  207. package/template/src/utils/testDataInitializer.ts +296 -0
  208. package/template/static/output.json +15203 -0
  209. package/template/test/controllers/controllers.test.ts +173 -0
  210. package/template/test/controllers/example/ExampleController.test.ts +222 -0
  211. package/template/test/controllers/example/NewAnnotationExampleController.test.ts +200 -0
  212. package/template/test/framework/TransactionManagerDemo.test.ts +363 -0
  213. package/template/test/framework/annotation/AnnotationDecorators.test.ts +222 -0
  214. package/template/test/framework/annotation/AnnotationExecutor.test.ts +246 -0
  215. package/template/test/framework/annotation/AnnotationProcessor.test.ts +179 -0
  216. package/template/test/framework/annotation/CustomProcessors.test.ts +313 -0
  217. package/template/test/framework/annotation/DefaultProcessors.test.ts +371 -0
  218. package/template/test/framework/annotation/NewRouter.test.ts +272 -0
  219. package/template/test/framework/annotation/ProcessorManager.test.ts +248 -0
  220. package/template/test/framework/annotation/setup.ts +26 -0
  221. package/template/test/framework/cache.test.ts +101 -0
  222. package/template/test/framework/databaseConfig.test.ts +142 -0
  223. package/template/test/integration/integration.test.ts +153 -0
  224. package/template/test/plugins/weboffice/http.routes.int.test.ts +61 -0
  225. package/template/test/service/business.test.ts +87 -0
  226. package/template/test/service/paramValidateTest.service.test.ts +184 -0
  227. package/template/test/service/ytUser.service.test.ts +566 -0
  228. package/template/test/setup.ts +20 -0
  229. package/template/test/setupAfterEnv.ts +14 -0
  230. package/template/test/utils/testHelpers.ts +220 -0
  231. package/template/test_output.txt +0 -0
  232. package/template/tsconfig.build.json +17 -0
  233. package/template/tsconfig.json +31 -0
  234. package/template/webpack.config.js +71 -0
  235. package/template/yarn.lock +7354 -0
@@ -0,0 +1,360 @@
1
+ # TransactionManager 使用指南
2
+
3
+ ## 概述
4
+
5
+ TransactionManager 是一个企业级事务管理器,提供了简洁、安全的数据库事务处理能力。它确保数据库操作的原子性、一致性、隔离性和持久性(ACID 特性)。
6
+
7
+ ## 主要特性
8
+
9
+ ✅ **自动资源管理** - 自动释放连接,防止内存泄露
10
+ ✅ **多种隔离级别** - 支持 READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
11
+ ✅ **只读事务优化** - 专门针对只读操作优化
12
+ ✅ **批量操作支持** - 一次事务处理多个操作
13
+ ✅ **嵌套事务** - 支持在现有事务中执行额外操作
14
+ ✅ **完善的错误处理** - 自动回滚,确保数据一致性
15
+
16
+ ## 快速开始
17
+
18
+ ### 1. 基本使用
19
+
20
+ ```typescript
21
+ import { transactionManager } from '@src/framework/utils/TransactionManager';
22
+
23
+ // 在事务中执行操作
24
+ const result = await transactionManager.executeInTransaction(async (manager) => {
25
+ // 所有数据库操作都在事务中执行
26
+ const user = new YtUserEntity();
27
+ user.email = 'user@example.com';
28
+ user.password = await bcrypt.hash('password', 10);
29
+
30
+ return await manager.save(user);
31
+ });
32
+ ```
33
+
34
+ ### 2. 在 Service 中使用
35
+
36
+ ```typescript
37
+ import { Injectable } from "dp-ioc";
38
+ import { transactionManager } from "@src/framework/utils/TransactionManager";
39
+ import { YtUserEntity } from "@src/entity/ytUser.entity";
40
+
41
+ @Injectable()
42
+ export class MyService {
43
+ async createUser(userData: any): Promise<YtUserEntity> {
44
+ return await transactionManager.executeInTransaction(async (manager) => {
45
+ // 1. 创建用户
46
+ const user = new YtUserEntity();
47
+ user.email = userData.email;
48
+ user.password = userData.password;
49
+ const savedUser = await manager.save(user);
50
+
51
+ // 2. 创建相关记录(都在同一事务中)
52
+ // const profile = await manager.save(ProfileEntity, profileData);
53
+
54
+ return savedUser;
55
+ });
56
+ }
57
+ }
58
+ ```
59
+
60
+ ## 使用场景详解
61
+
62
+ ### 场景 1: 用户注册(多表操作)
63
+
64
+ ```typescript
65
+ async createUserWithProfile(userData: any, profileData: any): Promise<any> {
66
+ return await transactionManager.executeInTransaction(async (manager) => {
67
+ // 步骤 1: 创建用户
68
+ const user = await manager.save(YtUserEntity, userData);
69
+
70
+ // 步骤 2: 创建用户配置
71
+ const profile = await manager.save(ProfileEntity, {
72
+ ...profileData,
73
+ userId: user.id
74
+ });
75
+
76
+ // 步骤 3: 创建默认权限
77
+ const permissions = await manager.save(PermissionEntity, {
78
+ userId: user.id,
79
+ permissions: ['read']
80
+ });
81
+
82
+ // 如果任何一步失败,整个事务都会回滚
83
+ return { user, profile, permissions };
84
+ });
85
+ }
86
+ ```
87
+
88
+ ### 场景 2: 转账操作(需要一致性保证)
89
+
90
+ ```typescript
91
+ async transferMoney(fromUserId: number, toUserId: number, amount: number) {
92
+ return await transactionManager.executeInTransaction(
93
+ async (manager) => {
94
+ // 使用 SERIALIZABLE 隔离级别确保最高一致性
95
+ const fromAccount = await manager.findOne(AccountEntity, {
96
+ where: { userId: fromUserId }
97
+ });
98
+
99
+ const toAccount = await manager.findOne(AccountEntity, {
100
+ where: { userId: toUserId }
101
+ });
102
+
103
+ // 检查余额
104
+ if (fromAccount.balance < amount) {
105
+ throw new Error('余额不足');
106
+ }
107
+
108
+ // 扣款
109
+ fromAccount.balance -= amount;
110
+ await manager.save(fromAccount);
111
+
112
+ // 入账
113
+ toAccount.balance += amount;
114
+ await manager.save(toAccount);
115
+
116
+ // 记录转账记录
117
+ await manager.save(TransferRecordEntity, {
118
+ fromUserId,
119
+ toUserId,
120
+ amount,
121
+ createdAt: new Date()
122
+ });
123
+
124
+ return { success: true };
125
+ },
126
+ 'SERIALIZABLE' // 最高隔离级别
127
+ );
128
+ }
129
+ ```
130
+
131
+ ### 场景 3: 批量导入数据
132
+
133
+ ```typescript
134
+ async importUsers(userList: any[]): Promise<any[]> {
135
+ const operations = userList.map(userData => {
136
+ return async (manager: EntityManager) => {
137
+ // 验证数据
138
+ if (!userData.email) {
139
+ throw new Error('邮箱不能为空');
140
+ }
141
+
142
+ // 创建用户
143
+ const user = new YtUserEntity();
144
+ user.email = userData.email;
145
+ user.password = await bcrypt.hash(userData.password, 10);
146
+
147
+ return await manager.save(user);
148
+ };
149
+ });
150
+
151
+ // 所有操作在一个事务中执行
152
+ return await transactionManager.executeBatchTransaction(operations);
153
+ }
154
+ ```
155
+
156
+ ### 场景 4: 只读查询优化
157
+
158
+ ```typescript
159
+ async getReportData(startDate: Date, endDate: Date): Promise<any> {
160
+ return await transactionManager.executeInReadOnlyTransaction(async (manager) => {
161
+ // 只读事务,不会产生任何写操作
162
+ // 数据库可以优化只读查询
163
+
164
+ const [users, orders, payments] = await Promise.all([
165
+ manager.count(YtUserEntity, {
166
+ where: { createDate: Between(startDate, endDate) }
167
+ }),
168
+ manager.count(OrderEntity, {
169
+ where: { createDate: Between(startDate, endDate) }
170
+ }),
171
+ manager.count(PaymentEntity, {
172
+ where: { createDate: Between(startDate, endDate) }
173
+ })
174
+ ]);
175
+
176
+ return {
177
+ users,
178
+ orders,
179
+ payments
180
+ };
181
+ });
182
+ }
183
+ ```
184
+
185
+ ### 场景 5: 需要嵌套事务的复杂操作
186
+
187
+ ```typescript
188
+ async processOrder(orderId: number): Promise<any> {
189
+ return await transactionManager.executeInTransaction(async (manager) => {
190
+ // 主事务:处理订单
191
+ const order = await manager.findOne(OrderEntity, orderId);
192
+ order.status = 'processing';
193
+ await manager.save(order);
194
+
195
+ // 嵌套事务:处理支付
196
+ await transactionManager.executeNestedTransaction(async (nestedManager) => {
197
+ const payment = await nestedManager.save(PaymentEntity, {
198
+ orderId: order.id,
199
+ amount: order.total
200
+ });
201
+
202
+ // 嵌套事务:发送通知
203
+ await transactionManager.executeNestedTransaction(async (innerManager) => {
204
+ await innerManager.save(NotificationEntity, {
205
+ userId: order.userId,
206
+ message: '订单已支付'
207
+ });
208
+ });
209
+
210
+ return payment;
211
+ });
212
+
213
+ return order;
214
+ });
215
+ }
216
+ ```
217
+
218
+ ### 场景 6: 错误处理和回滚
219
+
220
+ ```typescript
221
+ async createOrderWithInventoryCheck(orderData: any): Promise<any> {
222
+ try {
223
+ return await transactionManager.executeInTransaction(async (manager) => {
224
+ // 检查库存
225
+ const product = await manager.findOne(ProductEntity, orderData.productId);
226
+ if (product.stock < orderData.quantity) {
227
+ throw new Error('库存不足'); // 抛出错误会自动回滚
228
+ }
229
+
230
+ // 创建订单
231
+ const order = await manager.save(OrderEntity, orderData);
232
+
233
+ // 更新库存
234
+ product.stock -= orderData.quantity;
235
+ await manager.save(product);
236
+
237
+ return order;
238
+ });
239
+ } catch (error) {
240
+ // 所有操作已自动回滚
241
+ logger.error('创建订单失败,已回滚所有更改');
242
+ throw error;
243
+ }
244
+ }
245
+ ```
246
+
247
+ ## 隔离级别说明
248
+
249
+ | 隔离级别 | 说明 | 使用场景 |
250
+ |---------|------|---------|
251
+ | READ_UNCOMMITTED | 允许读取未提交数据 | 性能要求高,不太关心数据一致性 |
252
+ | READ_COMMITTED | 只能读取已提交数据(默认) | 大多数业务场景 |
253
+ | REPEATABLE_READ | 事务内多次读取一致 | 需要重复读取一致性 |
254
+ | SERIALIZABLE | 最高隔离级别 | 金融交易、高一致性要求 |
255
+
256
+ ```typescript
257
+ // 使用隔离级别
258
+ await transactionManager.executeInTransaction(
259
+ async (manager) => {
260
+ // 业务逻辑
261
+ },
262
+ 'SERIALIZABLE' // 指定隔离级别
263
+ );
264
+ ```
265
+
266
+ ## 最佳实践
267
+
268
+ ### ✅ 推荐做法
269
+
270
+ 1. **始终使用事务处理多表操作**
271
+ ```typescript
272
+ // 好的做法
273
+ await transactionManager.executeInTransaction(async (manager) => {
274
+ await manager.save(user);
275
+ await manager.save(profile);
276
+ });
277
+ ```
278
+
279
+ 2. **为事务操作添加适当的错误处理**
280
+ ```typescript
281
+ try {
282
+ await transactionManager.executeInTransaction(async (manager) => {
283
+ // 操作
284
+ });
285
+ } catch (error) {
286
+ logger.error('操作失败:', error);
287
+ // 事务已自动回滚
288
+ }
289
+ ```
290
+
291
+ 3. **使用只读事务优化查询性能**
292
+ ```typescript
293
+ // 只读操作使用只读事务
294
+ await transactionManager.executeInReadOnlyTransaction(async (manager) => {
295
+ return await manager.find(UserEntity);
296
+ });
297
+ ```
298
+
299
+ ### ❌ 避免的做法
300
+
301
+ 1. **不要在事务中执行长时间运行的操作**
302
+ ```typescript
303
+ // 不好的做法
304
+ await transactionManager.executeInTransaction(async (manager) => {
305
+ await sleep(5000); // 长时间持有连接
306
+ });
307
+ ```
308
+
309
+ 2. **不要忘记处理错误**
310
+ ```typescript
311
+ // 不好的做法
312
+ await transactionManager.executeInTransaction(async (manager) => {
313
+ // 没有错误处理
314
+ });
315
+ ```
316
+
317
+ 3. **不要在事务中调用外部服务**
318
+ ```typescript
319
+ // 不好的做法
320
+ await transactionManager.executeInTransaction(async (manager) => {
321
+ await manager.save(data);
322
+ await externalApi.call(); // 可能会导致事务锁定
323
+ });
324
+ ```
325
+
326
+ ## 性能优化建议
327
+
328
+ 1. **事务应尽可能短** - 减少数据库锁定时间
329
+ 2. **合理使用隔离级别** - 高隔离级别会影响性能
330
+ 3. **批量操作使用 executeBatchTransaction** - 减少事务开启次数
331
+ 4. **只读操作使用 executeInReadOnlyTransaction** - 数据库可以优化
332
+
333
+ ## 常见问题
334
+
335
+ ### Q: 事务会自动提交吗?
336
+ A: 是的,如果事务中的所有操作成功执行,会自动提交。如果出现任何错误,会自动回滚。
337
+
338
+ ### Q: 如何处理并发冲突?
339
+ A: 使用适当的隔离级别(如 SERIALIZABLE)和重试机制。
340
+
341
+ ### Q: 事务会影响性能吗?
342
+ A: 合理使用事务不会影响性能。避免长事务和在事务中执行耗时操作。
343
+
344
+ ### Q: 可以手动控制提交和回滚吗?
345
+ A: 不需要,TransactionManager 会自动处理。业务逻辑通过返回值或抛出错误来控制事务。
346
+
347
+ ## 更多示例
348
+
349
+ 查看 `src/examples/TransactionManagerDemo.ts` 获取更多完整示例代码。
350
+
351
+ ## 内存泄露修复
352
+
353
+ 本次修复确保了以下资源的正确释放:
354
+ - ✅ 所有数据库连接都会被正确释放
355
+ - ✅ 事务中的 queryRunner 会被正确清理
356
+ - ✅ 应用关闭时所有资源都会被释放
357
+
358
+ 请参考 `MEMORY_LEAK_FIX_REPORT.md` 了解详细的内存泄露修复说明。
359
+
360
+