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,191 @@
1
+ # 路由斜杠兼容性修复
2
+
3
+ ## 🔍 问题描述
4
+
5
+ 用户发现健康检查接口的访问行为不一致:
6
+ - ✅ `http://localhost:3000/health/` - 可以访问
7
+ - ❌ `http://localhost:3000/health` - 无法访问
8
+
9
+ ## 🔧 问题分析
10
+
11
+ ### 根本原因
12
+
13
+ 问题出现在框架的路由注册逻辑中:
14
+
15
+ ```typescript
16
+ // 路由绑定
17
+ bindRouter("/health", HealthController);
18
+
19
+ // 控制器方法
20
+ @Get("/")
21
+ async healthCheck() { ... }
22
+ ```
23
+
24
+ ### 路由构建过程
25
+
26
+ 1. `bindRouter("/health", HealthController)` 将控制器绑定到 `/health` 路径
27
+ 2. `@Get("/")` 表示在控制器路径下的根路径
28
+ 3. `path.join("/health", "/")` 生成 `/health/`
29
+ 4. 最终注册的路由是 `/health/`,而不是 `/health`
30
+
31
+ ### Koa Router 行为
32
+
33
+ Koa Router 对路径匹配是严格的:
34
+ - `/health/` 只匹配 `http://localhost:3000/health/`
35
+ - `/health` 只匹配 `http://localhost:3000/health`
36
+
37
+ ## ✅ 解决方案
38
+
39
+ ### 修复策略
40
+
41
+ 在路由注册时,如果 URL 以斜杠结尾且不是根路径,同时注册无斜杠版本:
42
+
43
+ ```typescript
44
+ // 原始逻辑
45
+ _router.get(_url, cb)
46
+
47
+ // 新增逻辑:同时注册无斜杠版本
48
+ if (_url.endsWith('/') && _url !== '/') {
49
+ const urlWithoutSlash = _url.slice(0, -1);
50
+ _router.get(urlWithoutSlash, cb)
51
+ }
52
+ ```
53
+
54
+ ### 修复范围
55
+
56
+ 为所有 HTTP 方法添加了斜杠兼容性支持:
57
+ - ✅ GET 方法
58
+ - ✅ POST 方法
59
+ - ✅ PUT 方法
60
+ - ✅ DELETE 方法
61
+ - ✅ ALL 方法
62
+
63
+ ### 中间件兼容性
64
+
65
+ 修复同时考虑了中间件的兼容性:
66
+
67
+ ```typescript
68
+ // 原始URL的中间件
69
+ if (middlewares.length > 0) {
70
+ for (const middleware of middlewares) {
71
+ _router.use(_url, middleware);
72
+ }
73
+ }
74
+
75
+ // 无斜杠版本的中间件
76
+ if (_url.endsWith('/') && _url !== '/') {
77
+ const urlWithoutSlash = _url.slice(0, -1);
78
+ if (middlewares.length > 0) {
79
+ for (const middleware of middlewares) {
80
+ _router.use(urlWithoutSlash, middleware);
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ ## 🎯 修复效果
87
+
88
+ ### 健康检查接口
89
+
90
+ 现在两个地址都可以正常访问:
91
+ - ✅ `http://localhost:3000/health` - 现在可以访问
92
+ - ✅ `http://localhost:3000/health/` - 仍然可以访问
93
+
94
+ ### 其他接口
95
+
96
+ 所有使用 `@Get("/")` 的接口都获得了相同的兼容性:
97
+ - ✅ `http://localhost:3000/api/users` - 可以访问
98
+ - ✅ `http://localhost:3000/api/users/` - 也可以访问
99
+
100
+ ## 📊 技术细节
101
+
102
+ ### 路径处理逻辑
103
+
104
+ ```typescript
105
+ // 原始路径构建
106
+ const _url = path.join(_path, url).replace(/\\/g, "/");
107
+
108
+ // 兼容性检查
109
+ if (_url.endsWith('/') && _url !== '/') {
110
+ const urlWithoutSlash = _url.slice(0, -1);
111
+ // 注册无斜杠版本
112
+ }
113
+ ```
114
+
115
+ ### 特殊情况处理
116
+
117
+ - **根路径保护**: `_url !== '/'` 确保不会处理根路径
118
+ - **中间件同步**: 确保两个版本使用相同的中间件
119
+ - **方法一致性**: 所有 HTTP 方法都应用相同的逻辑
120
+
121
+ ## 🧪 测试验证
122
+
123
+ ### 基础测试
124
+
125
+ ```bash
126
+ # 健康检查 - 无斜杠
127
+ curl http://localhost:3000/health
128
+
129
+ # 健康检查 - 有斜杠
130
+ curl http://localhost:3000/health/
131
+
132
+ # 数据库健康检查
133
+ curl http://localhost:3000/health/db
134
+
135
+ # 缓存健康检查
136
+ curl http://localhost:3000/health/cache
137
+ ```
138
+
139
+ ### 预期结果
140
+
141
+ 所有测试都应该返回相同的响应,证明路由兼容性正常工作。
142
+
143
+ ## 🔄 向后兼容性
144
+
145
+ ### 现有代码
146
+
147
+ - ✅ 现有使用 `@Get("/")` 的代码无需修改
148
+ - ✅ 现有使用 `@Post("/")` 的代码无需修改
149
+ - ✅ 现有中间件配置无需修改
150
+
151
+ ### 文档更新
152
+
153
+ - ✅ 文档中的地址 `http://localhost:3000/health` 现在可以正常工作
154
+ - ✅ 无需更新任何文档内容
155
+
156
+ ## 🎉 总结
157
+
158
+ 这个修复解决了框架路由系统的斜杠兼容性问题:
159
+
160
+ ### 优势
161
+
162
+ 1. **用户体验提升**: 用户可以使用标准的无斜杠 URL
163
+ 2. **RESTful 兼容**: 符合 RESTful API 最佳实践
164
+ 3. **向后兼容**: 保持现有代码和文档的兼容性
165
+ 4. **全面支持**: 覆盖所有 HTTP 方法和中间件
166
+
167
+ ### 技术特点
168
+
169
+ 1. **自动检测**: 自动识别需要兼容的路径
170
+ 2. **中间件同步**: 确保两个版本使用相同的中间件
171
+ 3. **性能优化**: 只在必要时注册额外路由
172
+ 4. **安全保护**: 避免处理根路径等特殊情况
173
+
174
+ ### 影响范围
175
+
176
+ - ✅ 所有使用 `@Get("/")` 的控制器方法
177
+ - ✅ 所有使用 `@Post("/")` 的控制器方法
178
+ - ✅ 所有使用 `@Put("/")` 的控制器方法
179
+ - ✅ 所有使用 `@Delete("/")` 的控制器方法
180
+ - ✅ 所有使用 `@All("/")` 的控制器方法
181
+
182
+ 现在框架支持同时访问有斜杠和无斜杠的 URL,提供了更好的用户体验和 API 兼容性!
183
+
184
+ ---
185
+
186
+ **修复版本**: v1.0.1
187
+ **修复时间**: 2024-01-01
188
+ **影响范围**: 所有路由注册逻辑
189
+
190
+
191
+
@@ -0,0 +1,243 @@
1
+ # Service调用拦截器插件
2
+
3
+ 基于dp-ioc的Interceptor注解规则,提供完整的Service调用周期监控和管理功能。
4
+
5
+ ## 🚀 功能特性
6
+
7
+ ### 基础拦截器 (ServiceCallInterceptor)
8
+ - ✅ **完整调用周期监控** - 记录方法调用的开始、执行、结束、异常等各个阶段
9
+ - ✅ **性能统计** - 自动统计调用次数、成功率、平均耗时等指标
10
+ - ✅ **敏感信息脱敏** - 自动过滤密码、token等敏感字段
11
+ - ✅ **调用历史记录** - 保存最近的调用历史,便于调试和分析
12
+ - ✅ **详细日志记录** - 提供结构化的调用日志
13
+
14
+ ### 高级拦截器 (AdvancedServiceCallInterceptor)
15
+ - 🔄 **自动重试机制** - 支持指数退避重试策略
16
+ - 💾 **智能缓存** - 可配置的方法结果缓存
17
+ - ⚡ **熔断器模式** - 防止级联故障的熔断保护
18
+ - 📊 **性能监控** - 慢调用检测和性能指标收集
19
+ - 🎛️ **灵活配置** - 支持多种配置选项
20
+
21
+ ## 📦 安装和导入
22
+
23
+ ```typescript
24
+ import { Injectable, Interceptor } from "dp-ioc";
25
+ import { createServiceCallInterceptor } from '@src/framework/interceptors/ServiceCallInterceptor';
26
+ import { createAdvancedServiceCallInterceptor, InterceptorOptions } from '@src/framework/interceptors/AdvancedServiceCallInterceptor';
27
+ ```
28
+
29
+ ## 🔧 基础使用
30
+
31
+ ### 1. 基础拦截器使用
32
+
33
+ ```typescript
34
+ @Injectable()
35
+ export class UserService {
36
+
37
+ @Interceptor(createServiceCallInterceptor())
38
+ async getUserById(id: number): Promise<User> {
39
+ // 你的业务逻辑
40
+ return await this.userRepository.findById(id);
41
+ }
42
+
43
+ @Interceptor(createServiceCallInterceptor())
44
+ async createUser(userData: CreateUserDto): Promise<User> {
45
+ // 你的业务逻辑
46
+ return await this.userRepository.create(userData);
47
+ }
48
+ }
49
+ ```
50
+
51
+ ### 2. 高级拦截器使用
52
+
53
+ ```typescript
54
+ @Injectable()
55
+ export class OrderService {
56
+
57
+ @Interceptor(createAdvancedServiceCallInterceptor({
58
+ enablePerformanceMonitoring: true,
59
+ enableCaching: true,
60
+ enableRetry: true,
61
+ enableCircuitBreaker: true,
62
+ cacheTTL: 300000, // 5分钟
63
+ maxRetries: 3,
64
+ retryDelay: 1000,
65
+ circuitBreakerThreshold: 5,
66
+ slowCallThreshold: 1000
67
+ }))
68
+ async getOrderById(orderId: number): Promise<Order> {
69
+ // 可能失败的外部API调用
70
+ return await this.externalOrderService.getOrder(orderId);
71
+ }
72
+ }
73
+ ```
74
+
75
+ ## ⚙️ 配置选项
76
+
77
+ ### InterceptorOptions
78
+
79
+ ```typescript
80
+ interface InterceptorOptions {
81
+ enablePerformanceMonitoring?: boolean; // 启用性能监控
82
+ enableCaching?: boolean; // 启用缓存
83
+ enableRetry?: boolean; // 启用重试
84
+ enableCircuitBreaker?: boolean; // 启用熔断器
85
+ cacheTTL?: number; // 缓存TTL (毫秒)
86
+ maxRetries?: number; // 最大重试次数
87
+ retryDelay?: number; // 重试延迟 (毫秒)
88
+ circuitBreakerThreshold?: number; // 熔断器阈值
89
+ slowCallThreshold?: number; // 慢调用阈值 (毫秒)
90
+ }
91
+ ```
92
+
93
+ ## 📊 监控和统计
94
+
95
+ ### 获取调用统计
96
+
97
+ ```typescript
98
+ import { serviceCallInterceptor } from '@src/framework/interceptors/ServiceCallInterceptor';
99
+
100
+ // 获取统计报告
101
+ const report = serviceCallInterceptor.generateReport();
102
+ console.log(report);
103
+
104
+ // 获取调用历史
105
+ const history = serviceCallInterceptor.getCallHistory();
106
+ console.log(history);
107
+
108
+ // 获取方法统计
109
+ const methodStats = serviceCallInterceptor.getMethodStats('UserService.getUserById');
110
+ console.log(methodStats);
111
+ ```
112
+
113
+ ### 高级拦截器状态
114
+
115
+ ```typescript
116
+ import { advancedServiceCallInterceptor } from '@src/framework/interceptors/AdvancedServiceCallInterceptor';
117
+
118
+ // 获取拦截器状态
119
+ const status = advancedServiceCallInterceptor.getStatus();
120
+ console.log(status);
121
+
122
+ // 清理缓存
123
+ advancedServiceCallInterceptor.clearCache();
124
+
125
+ // 重置熔断器
126
+ advancedServiceCallInterceptor.resetCircuitBreakers();
127
+ ```
128
+
129
+ ## 📝 日志输出示例
130
+
131
+ ### 基础拦截器日志
132
+
133
+ ```
134
+ 🚀 Service调用开始: UserService.getUserById 参数: [123], 时间: 2025-10-27T00:30:00.000Z
135
+ ✅ Service调用成功: UserService.getUserById 耗时: 150ms, 结果: {"id":123,"name":"张三"}, 时间: 2025-10-27T00:30:00.150Z
136
+ ```
137
+
138
+ ### 高级拦截器日志
139
+
140
+ ```
141
+ 执行方法: OrderService.getOrderById (尝试 1) 参数: [456]
142
+ 方法调用失败,1000ms后重试 (1/3): OrderService.getOrderById 错误: 外部API调用失败, 尝试次数: 1/3
143
+ 执行方法: OrderService.getOrderById (尝试 2) 参数: [456]
144
+ 方法执行成功: OrderService.getOrderById 耗时: 300ms, 尝试次数: 2
145
+ ```
146
+
147
+ ## 🎯 使用场景
148
+
149
+ ### 1. 基础监控场景
150
+ - 开发环境调试
151
+ - 生产环境监控
152
+ - 性能分析
153
+ - 错误追踪
154
+
155
+ ### 2. 高级功能场景
156
+ - 外部API调用(重试 + 熔断)
157
+ - 频繁查询优化(缓存)
158
+ - 性能敏感操作(监控)
159
+ - 高可用性要求(熔断器)
160
+
161
+ ## 🔍 示例代码
162
+
163
+ 查看完整示例:
164
+ - `src/examples/ServiceInterceptorExample.ts` - 基础拦截器示例
165
+ - `src/examples/InterceptorExampleRunner.ts` - 完整使用示例
166
+
167
+ ## 🛠️ 自定义扩展
168
+
169
+ ### 创建自定义拦截器
170
+
171
+ ```typescript
172
+ const customInterceptor = (params: Array<any>, instance: any, fn: Function, done: (err: any, param: any) => void) => {
173
+ // 你的自定义逻辑
174
+ const startTime = Date.now();
175
+
176
+ try {
177
+ const result = fn.apply(instance, params);
178
+
179
+ if (result && typeof result.then === 'function') {
180
+ result.then((res: any) => {
181
+ const duration = Date.now() - startTime;
182
+ console.log(`方法执行完成,耗时: ${duration}ms`);
183
+ done(null, res);
184
+ }).catch((error: Error) => {
185
+ done(error, null);
186
+ });
187
+ } else {
188
+ done(null, result);
189
+ }
190
+ } catch (error) {
191
+ done(error as Error, null);
192
+ }
193
+ };
194
+
195
+ @Interceptor(customInterceptor)
196
+ async myMethod() {
197
+ // 你的方法
198
+ }
199
+ ```
200
+
201
+ ## 📈 性能考虑
202
+
203
+ - 拦截器对性能影响很小(< 1ms)
204
+ - 缓存可以显著提升重复调用的性能
205
+ - 重试机制会增加失败调用的延迟
206
+ - 熔断器可以防止系统过载
207
+
208
+ ## 🔒 安全特性
209
+
210
+ - 自动脱敏敏感字段(password, token, secret等)
211
+ - 支持自定义脱敏规则
212
+ - 不记录敏感参数和返回值
213
+
214
+ ## 📋 最佳实践
215
+
216
+ 1. **开发环境**:使用基础拦截器进行调试
217
+ 2. **生产环境**:根据需要启用高级功能
218
+ 3. **外部调用**:建议启用重试和熔断器
219
+ 4. **频繁查询**:考虑启用缓存
220
+ 5. **性能敏感**:启用性能监控
221
+ 6. **定期清理**:定期清理缓存和历史记录
222
+
223
+ ## 🐛 故障排除
224
+
225
+ ### 常见问题
226
+
227
+ 1. **拦截器不生效**:确保正确导入和使用了`@Interceptor`装饰器
228
+ 2. **缓存不工作**:检查`enableCaching`配置和`cacheTTL`设置
229
+ 3. **重试不生效**:确认`enableRetry`为true且方法抛出异常
230
+ 4. **熔断器误触发**:调整`circuitBreakerThreshold`阈值
231
+
232
+ ### 调试技巧
233
+
234
+ ```typescript
235
+ // 启用详细日志
236
+ logger.setLevel('debug');
237
+
238
+ // 查看拦截器状态
239
+ console.log(serviceCallInterceptor.getStats());
240
+ console.log(advancedServiceCallInterceptor.getStatus());
241
+ ```
242
+
243
+
@@ -0,0 +1,205 @@
1
+ # Service 层文档索引
2
+
3
+ ## 📚 核心文档
4
+
5
+ ### 1. [Service 返回值规范](./SERVICE_RETURN_VALUE_SPECIFICATION.md) ⭐ 推荐阅读
6
+
7
+ **必读**:所有 Service 方法必须返回 `CommonServiceResult<T>` 对象
8
+
9
+ 主要内容:
10
+ - ✅ CommonServiceResult 结构和使用方式
11
+ - ✅ 状态码枚举和含义
12
+ - ✅ 静态工厂方法使用
13
+ - ✅ 完整示例(创建、查询、更新、删除)
14
+ - ✅ Controller 层如何处理返回值
15
+ - ✅ 最佳实践和常见错误
16
+
17
+ **何时查看**:
18
+ - 编写新的 Service 方法时
19
+ - 不确定如何返回结果时
20
+ - 需要了解错误处理方式时
21
+
22
+ ---
23
+
24
+ ### 2. [Service 层开发指南](./SERVICE_PATTERN_GUIDE.md) ⭐ 推荐阅读
25
+
26
+ **必读**:如何编写 Service 层代码
27
+
28
+ 主要内容:
29
+ - ✅ 使用懒加载 Getter 初始化 Repository
30
+ - ✅ 继承 BaseService 的用法
31
+ - ✅ 多 Repository 的场景处理
32
+ - ✅ 完整示例代码
33
+
34
+ **何时查看**:
35
+ - 第一次编写 Service 时
36
+ - 需要初始化 Repository 时
37
+ - 不知道如何设计 Service 结构时
38
+
39
+ ---
40
+
41
+ ### 3. [TransactionManager 使用指南](./TRANSACTION_MANAGER_USAGE.md)
42
+
43
+ **推荐**:事务管理器的使用
44
+
45
+ 主要内容:
46
+ - ✅ 基本事务使用
47
+ - ✅ 隔离级别设置
48
+ - ✅ 只读事务优化
49
+ - ✅ 批量操作
50
+ - ✅ 嵌套事务
51
+ - ✅ 错误处理和回滚
52
+
53
+ **何时查看**:
54
+ - 需要执行事务操作时
55
+ - 需要保证数据一致性时
56
+ - 处理复杂业务逻辑时
57
+
58
+ ---
59
+
60
+ ## 🎯 快速开始
61
+
62
+ ### 创建新 Service 的步骤
63
+
64
+ 1. **创建 Service 文件**
65
+ ```typescript
66
+ import { Injectable } from "dp-ioc";
67
+ import { BaseService } from "@src/service/base.service";
68
+ import { CommonServiceResult } from "@src/framework/types/ServiceResult";
69
+
70
+ @Injectable()
71
+ export class MyService extends BaseService {
72
+ // 添加方法
73
+ }
74
+ ```
75
+
76
+ 2. **编写 Service 方法**
77
+ ```typescript
78
+ async myMethod(dto: MyDto): Promise<CommonServiceResult<MyEntity>> {
79
+ try {
80
+ // 业务逻辑
81
+ return CommonServiceResult.success(result);
82
+ } catch (error) {
83
+ return CommonServiceResult.error("操作失败");
84
+ }
85
+ }
86
+ ```
87
+
88
+ 3. **返回 CommonServiceResult**
89
+ ```typescript
90
+ // 成功
91
+ return CommonServiceResult.success(data);
92
+
93
+ // 验证错误
94
+ return CommonServiceResult.validationError("错误消息");
95
+
96
+ // 未找到
97
+ return CommonServiceResult.notFound("资源不存在");
98
+
99
+ // 冲突
100
+ return CommonServiceResult.conflict("资源冲突");
101
+
102
+ // 服务器错误
103
+ return CommonServiceResult.error("操作失败");
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 📋 文档结构
109
+
110
+ ```
111
+ docs/
112
+ ├── SERVICE_LAYER_INDEX.md # 本文件 - Service 层文档索引
113
+ ├── SERVICE_RETURN_VALUE_SPECIFICATION.md # Service 返回值规范 ⭐
114
+ ├── SERVICE_PATTERN_GUIDE.md # Service 层开发指南 ⭐
115
+ └── TRANSACTION_MANAGER_USAGE.md # 事务管理器使用指南
116
+ ```
117
+
118
+ ---
119
+
120
+ ## 🔍 常见问题
121
+
122
+ ### Q: Service 方法必须返回什么?
123
+
124
+ **A**: 所有 Service 方法必须返回 `CommonServiceResult<T>`
125
+
126
+ ```typescript
127
+ // ✅ 正确
128
+ async createUser(dto: CreateUserDto): Promise<CommonServiceResult<UserEntity>> {
129
+ return CommonServiceResult.success(user);
130
+ }
131
+
132
+ // ❌ 错误
133
+ async createUser(dto: CreateUserDto): Promise<UserEntity> {
134
+ return user; // 不要这样做
135
+ }
136
+ ```
137
+
138
+ ### Q: 如何处理 Service 中的异常?
139
+
140
+ **A**: 使用 try-catch 捕获异常,返回适当的错误结果
141
+
142
+ ```typescript
143
+ try {
144
+ // 业务逻辑
145
+ return CommonServiceResult.success(data);
146
+ } catch (error) {
147
+ logger.error("操作失败:", error);
148
+ return CommonServiceResult.error("操作失败");
149
+ }
150
+ ```
151
+
152
+ ### Q: 如何初始化 Repository?
153
+
154
+ **A**: 使用懒加载 Getter 或继承 BaseService
155
+
156
+ ```typescript
157
+ // 方案1: 懒加载 Getter
158
+ private get userRepository(): IUserRepository {
159
+ return this.createLazyRepository(YtUserEntity, UserRepository, this.repositoryCache);
160
+ }
161
+
162
+ // 方案2: 继承 BaseService
163
+ const repo = this.getDataRepository(YtUserEntity);
164
+ ```
165
+
166
+ ### Q: 何时使用事务?
167
+
168
+ **A**: 需要保证多个操作原子性时
169
+
170
+ ```typescript
171
+ await transactionManager.executeInTransaction(async (manager) => {
172
+ await this.userRepository.save(user1);
173
+ await this.userRepository.save(user2);
174
+ });
175
+ ```
176
+
177
+ 详细说明请查看 [TransactionManager 使用指南](./TRANSACTION_MANAGER_USAGE.md)
178
+
179
+ ---
180
+
181
+ ## 🛠️ 相关文档
182
+
183
+ ### 基础
184
+ - [企业级数据库架构](./ENTERPRISE_DATABASE_ARCHITECTURE.md) - 数据库设计
185
+ - [企业级错误处理](./ENTERPRISE_ERROR_HANDLING_GUIDE.md) - 错误处理
186
+ - [企业级日志系统](./ENTERPRISE_LOGGING_SYSTEM_GUIDE.md) - 日志管理
187
+
188
+ ### 高级
189
+ - [企业级部署指南](./ENTERPRISE_DEPLOYMENT_GUIDE.md) - 部署流程
190
+ - [环境配置示例](./ENVIRONMENT_CONFIG_EXAMPLE.md) - 环境配置
191
+
192
+ ---
193
+
194
+ ## 📞 获取帮助
195
+
196
+ 遇到问题?
197
+ 1. 首先查看对应的详细文档
198
+ 2. 查看代码示例(src/service/ 目录)
199
+ 3. 查看测试用例(test/service/ 目录)
200
+
201
+ 需要更多信息?
202
+ - 查看项目 README.md
203
+ - 查看完整的文档列表
204
+
205
+