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.
- package/README.md +50 -0
- package/index.mjs +97 -0
- package/package.json +33 -0
- package/template/.env.development +9 -0
- package/template/.env.production +12 -0
- package/template/.github/workflows/ci-cd.yml +182 -0
- package/template/.trae/documents/controller_development_plan.md +386 -0
- package/template/.trae/skills/00-backend-core.skill.md +50 -0
- package/template/.trae/skills/01-backend-skill-router.skill.md +55 -0
- package/template/.trae/skills/10-backend-api.skill.md +54 -0
- package/template/.trae/skills/11-backend-controller-recipes.skill.md +107 -0
- package/template/.trae/skills/20-backend-repository.skill.md +25 -0
- package/template/.trae/skills/21-backend-service.skill.md +135 -0
- package/template/.trae/skills/25-backend-comments-and-doc.skill.md +97 -0
- package/template/.trae/skills/30-backend-validation.skill.md +320 -0
- package/template/.trae/skills/40-backend-error-logging.skill.md +21 -0
- package/template/.trae/skills/50-backend-bootstrap-lifecycle.skill.md +90 -0
- package/template/.trae/skills/60-backend-router-registration.skill.md +71 -0
- package/template/.trae/skills/70-backend-middleware.skill.md +98 -0
- package/template/.trae/skills/80-backend-utils-and-libs.skill.md +90 -0
- package/template/.trae/skills/85-backend-plugins.rule.md +64 -0
- package/template/.trae/skills/90-backend-testing.skill.md +29 -0
- package/template/.trae/skills/README.md +49 -0
- package/template/.vscode/launch.json +38 -0
- package/template/.vscode/settings.json +1 -0
- package/template/Dockerfile +36 -0
- package/template/README.md +229 -0
- package/template/docker-compose.yml +135 -0
- package/template/docs/API_DOCUMENTATION.md +837 -0
- package/template/docs/ARCHITECTURE_REFACTOR.md +109 -0
- package/template/docs/CACHE_MIGRATION_GUIDE.md +142 -0
- package/template/docs/DEPLOYMENT_GUIDE.md +1062 -0
- package/template/docs/DEVELOPMENT_GUIDE.md +1097 -0
- package/template/docs/DOCUMENTATION_CLEANUP_REPORT.md +166 -0
- package/template/docs/DOCUMENTATION_COMPLETION_REPORT.md +223 -0
- package/template/docs/DOCUMENTATION_INDEX.md +294 -0
- package/template/docs/DOCUMENTATION_STRUCTURE.md +221 -0
- package/template/docs/ENTERPRISE_ANNOTATION_SYSTEM_GUIDE.md +2069 -0
- package/template/docs/ENTERPRISE_DATABASE_ARCHITECTURE.md +318 -0
- package/template/docs/ENTERPRISE_DEPLOYMENT_GUIDE.md +547 -0
- package/template/docs/ENTERPRISE_ERROR_HANDLING_GUIDE.md +357 -0
- package/template/docs/ENTERPRISE_LOGGING_SYSTEM_GUIDE.md +494 -0
- package/template/docs/ENVIRONMENT_CONFIG_EXAMPLE.md +69 -0
- package/template/docs/FINAL_IMPLEMENTATION_SUMMARY.md +206 -0
- package/template/docs/HEALTH_CHECK_ROUTE_FIX.md +134 -0
- package/template/docs/IMPLEMENTATION_CHECKLIST.md +204 -0
- package/template/docs/INSTALLATION_GUIDE.md +611 -0
- package/template/docs/INTERCEPTOR_TESTING_REPORT.md +226 -0
- package/template/docs/INTERCEPTOR_TESTING_SCRIPTS.md +143 -0
- package/template/docs/LOGGING_OPTIMIZATION_GUIDE.md +126 -0
- package/template/docs/MEMORY_DATABASE_GUIDE.md +212 -0
- package/template/docs/NEW_ROUTER_INTEGRATION_GUIDE.md +345 -0
- package/template/docs/NEW_ROUTER_INTEGRATION_SUMMARY.md +259 -0
- package/template/docs/NEW_ROUTER_USAGE_GUIDE.md +364 -0
- package/template/docs/QUICK_START.md +268 -0
- package/template/docs/ROUTE_SLASH_COMPATIBILITY_FIX.md +191 -0
- package/template/docs/SERVICE_INTERCEPTOR_GUIDE.md +243 -0
- package/template/docs/SERVICE_LAYER_INDEX.md +205 -0
- package/template/docs/SERVICE_PATTERN_GUIDE.md +270 -0
- package/template/docs/SERVICE_RETURN_VALUE_SPECIFICATION.md +466 -0
- package/template/docs/SWAGGER_DEBUG_MODE_GUIDE.md +80 -0
- package/template/docs/SWAGGER_INTEGRATION_GUIDE.md +416 -0
- package/template/docs/TRANSACTION_MANAGER_USAGE.md +360 -0
- package/template/docs/TROUBLESHOOTING.md +869 -0
- package/template/env.production.example +62 -0
- package/template/jest.config.js +34 -0
- package/template/package-lock.json +13240 -0
- package/template/package.json +119 -0
- package/template/patches/typeorm+0.3.25.patch +22 -0
- package/template/scripts/sync-template.mjs +84 -0
- package/template/scripts/test-annotation-system.sh +48 -0
- package/template/scripts/test-core-functionality.sh +28 -0
- package/template/src/annotations/decorators/ConfigManagement.ts +9 -0
- package/template/src/annotations/decorators/DistributedTracing.ts +9 -0
- package/template/src/annotations/decorators/EnterprisePerformance.ts +9 -0
- package/template/src/annotations/decorators/PerformanceMonitor.ts +32 -0
- package/template/src/annotations/decorators/SecurityAudit.ts +9 -0
- package/template/src/annotations/index.ts +50 -0
- package/template/src/annotations/processors/ConfigManagementProcessor.ts +369 -0
- package/template/src/annotations/processors/DistributedTracingProcessor.ts +288 -0
- package/template/src/annotations/processors/EnterprisePerformanceProcessor.ts +189 -0
- package/template/src/annotations/processors/PerformanceMonitorProcessor.ts +101 -0
- package/template/src/annotations/processors/SecurityAuditProcessor.ts +345 -0
- package/template/src/annotations/processors/SwaggerProcessor.ts +612 -0
- package/template/src/annotations/processors/index.ts +10 -0
- package/template/src/app.ts +123 -0
- package/template/src/controllers/base.controller.ts +41 -0
- package/template/src/controllers/cacheManagement.controller.ts +131 -0
- package/template/src/controllers/captcha.controller.ts +57 -0
- package/template/src/controllers/demo/AnnotationDemoController.ts +118 -0
- package/template/src/controllers/example/EnterpriseExampleController.ts +297 -0
- package/template/src/controllers/example/ExampleController.ts +110 -0
- package/template/src/controllers/example/NewAnnotationExampleController.ts +159 -0
- package/template/src/controllers/example/SwaggerExampleController.ts +205 -0
- package/template/src/controllers/example/TransactionExample.controller.ts +336 -0
- package/template/src/controllers/health.controller.ts +235 -0
- package/template/src/controllers/home/register.controller.ts +58 -0
- package/template/src/controllers/home/ytGoods.controller.ts +92 -0
- package/template/src/controllers/home/ytShop.controller.ts +135 -0
- package/template/src/controllers/home/ytUser.controller.ts +89 -0
- package/template/src/controllers/logManagement.controller.ts +396 -0
- package/template/src/controllers/public/emailSend.controller.ts +65 -0
- package/template/src/controllers/public/ytUserAuth.controller.ts +174 -0
- package/template/src/controllers/testData.controller.ts +253 -0
- package/template/src/dto/controller/example/NewAnnotationExampleController.dto.ts +73 -0
- package/template/src/dto/controller/home/emailSend.controller.dto.ts +40 -0
- package/template/src/dto/controller/home/register.controller.dto.ts +45 -0
- package/template/src/dto/controller/home/ytGoods.controller.dto.ts +55 -0
- package/template/src/dto/controller/home/ytShop.controller.dto.ts +69 -0
- package/template/src/dto/controller/home/ytUser.controller.dto.ts +44 -0
- package/template/src/dto/controller/public/ytUserAuth.controller.dto.ts +63 -0
- package/template/src/dto/goods.dto.ts +212 -0
- package/template/src/dto/service/ytService.dto.ts +13 -0
- package/template/src/dto/user.dto.ts +177 -0
- package/template/src/entity/base.entity.ts +13 -0
- package/template/src/entity/columnTypes.ts +13 -0
- package/template/src/entity/goodsImagesUnlockKey.entity.ts +33 -0
- package/template/src/entity/goodsUnlocker.entity.ts +34 -0
- package/template/src/entity/index.ts +15 -0
- package/template/src/entity/shop.entity.ts +52 -0
- package/template/src/entity/shopUser.entity.ts +41 -0
- package/template/src/entity/ytGoods.entity.ts +94 -0
- package/template/src/entity/ytUser.entity.ts +96 -0
- package/template/src/examples/InterceptorExampleRunner.ts +284 -0
- package/template/src/examples/ServiceInterceptorExample.ts +214 -0
- package/template/src/examples/SwaggerProcessorExample.ts +169 -0
- package/template/src/examples/TransactionManagerDemo.ts +377 -0
- package/template/src/examples/cacheExamples.ts +155 -0
- package/template/src/framework/decorator/controller.ts +311 -0
- package/template/src/framework/decorator/processor/AnnotationDecorators.ts +100 -0
- package/template/src/framework/decorator/processor/AnnotationProcessor.ts +156 -0
- package/template/src/framework/decorator/processor/AnnotationProcessorConfig.ts +45 -0
- package/template/src/framework/decorator/processor/AnnotationRegistry.ts +117 -0
- package/template/src/framework/decorator/processor/AnnotationSystemInitializer.ts +95 -0
- package/template/src/framework/decorator/processor/ProcessorManager.ts +76 -0
- package/template/src/framework/decorator/processor/processors/CustomProcessors.ts +126 -0
- package/template/src/framework/decorator/processor/processors/DefaultProcessors.ts +207 -0
- package/template/src/framework/decorator/refactored/DecoratorFactory.ts +99 -0
- package/template/src/framework/decorator/refactored/DecoratorMetadataManager.ts +125 -0
- package/template/src/framework/decorator/refactored/DecoratorValidator.ts +128 -0
- package/template/src/framework/decorator/refactored/TypeSafeDecorators.ts +139 -0
- package/template/src/framework/decorator/refactored/index.ts +98 -0
- package/template/src/framework/decorator/swagger.ts +150 -0
- package/template/src/framework/interceptors/AdvancedServiceCallInterceptor.ts +375 -0
- package/template/src/framework/interceptors/ServiceCallInterceptor.ts +348 -0
- package/template/src/framework/interceptors/index.ts +19 -0
- package/template/src/framework/plugins/registry.ts +63 -0
- package/template/src/framework/plugins/types.ts +15 -0
- package/template/src/framework/types/ServiceResult.ts +151 -0
- package/template/src/framework/types/index.ts +16 -0
- package/template/src/framework/utils/CacheManager.ts +430 -0
- package/template/src/framework/utils/CacheService.ts +248 -0
- package/template/src/framework/utils/DtoValidator.ts +164 -0
- package/template/src/framework/utils/MigrationHelper.ts +179 -0
- package/template/src/framework/utils/MigrationManager.ts +256 -0
- package/template/src/framework/utils/NewRouter.ts +207 -0
- package/template/src/framework/utils/TransactionManager.ts +172 -0
- package/template/src/framework/utils/bootstrap.ts +445 -0
- package/template/src/framework/utils/cache.ts +269 -0
- package/template/src/framework/utils/databaseConfig.ts +148 -0
- package/template/src/framework/utils/db.ts +39 -0
- package/template/src/framework/utils/dbMonitor.ts +106 -0
- package/template/src/framework/utils/dynamicSwagger.ts +410 -0
- package/template/src/framework/utils/function.ts +61 -0
- package/template/src/framework/utils/gracefulShutdown.ts +131 -0
- package/template/src/framework/utils/logger.ts +388 -0
- package/template/src/framework/utils/metrics.ts +182 -0
- package/template/src/framework/utils/router.ts +417 -0
- package/template/src/framework/utils/swagger.ts +184 -0
- package/template/src/framework/utils/testDb.ts +19 -0
- package/template/src/framework/utils/token.ts +23 -0
- package/template/src/framework/utils/transform.ts +17 -0
- package/template/src/libs/aokEmailSender.ts +42 -0
- package/template/src/libs/captcha.ts +37 -0
- package/template/src/libs/cos.ts +45 -0
- package/template/src/libs/mCache.ts +7 -0
- package/template/src/libs/serviceValidate.ts +3 -0
- package/template/src/libs/tecentSms.ts +51 -0
- package/template/src/middlewares/a.middleware.ts +6 -0
- package/template/src/middlewares/error.middleware.ts +14 -0
- package/template/src/middlewares/logging.middleware.ts +187 -0
- package/template/src/middlewares/static.middleware.ts +79 -0
- package/template/src/middlewares/swagger.middleware.ts +70 -0
- package/template/src/middlewares/token.middleware.ts +32 -0
- package/template/src/migrations/1700000000000-InitialDatabaseStructure.ts +172 -0
- package/template/src/migrations/index.ts +6 -0
- package/template/src/plugins/weboffice/core/context.ts +47 -0
- package/template/src/plugins/weboffice/core/errors.ts +51 -0
- package/template/src/plugins/weboffice/core/types.ts +63 -0
- package/template/src/plugins/weboffice/core/utils.ts +7 -0
- package/template/src/plugins/weboffice/entities/index.ts +3 -0
- package/template/src/plugins/weboffice/entities/webofficeFile.entity.ts +28 -0
- package/template/src/plugins/weboffice/entities/webofficeFileVersion.entity.ts +29 -0
- package/template/src/plugins/weboffice/http/routes.ts +179 -0
- package/template/src/plugins/weboffice/index.ts +23 -0
- package/template/src/plugins/weboffice/services/webofficeCallback.service.ts +274 -0
- package/template/src/repository/UserRepository.ts +122 -0
- package/template/src/repository/base/BaseRepository.ts +124 -0
- package/template/src/repository/interfaces/IBaseRepository.ts +67 -0
- package/template/src/routers/index.ts +49 -0
- package/template/src/service/base.service.ts +116 -0
- package/template/src/service/paramValidateTest.service.ts +139 -0
- package/template/src/service/ytGoods.service.ts +42 -0
- package/template/src/service/ytShop.service.ts +90 -0
- package/template/src/service/ytUser.service.ts +451 -0
- package/template/src/test/swaggerParameterTest.ts +90 -0
- package/template/src/utils/testDataInitializer.ts +296 -0
- package/template/static/output.json +15203 -0
- package/template/test/controllers/controllers.test.ts +173 -0
- package/template/test/controllers/example/ExampleController.test.ts +222 -0
- package/template/test/controllers/example/NewAnnotationExampleController.test.ts +200 -0
- package/template/test/framework/TransactionManagerDemo.test.ts +363 -0
- package/template/test/framework/annotation/AnnotationDecorators.test.ts +222 -0
- package/template/test/framework/annotation/AnnotationExecutor.test.ts +246 -0
- package/template/test/framework/annotation/AnnotationProcessor.test.ts +179 -0
- package/template/test/framework/annotation/CustomProcessors.test.ts +313 -0
- package/template/test/framework/annotation/DefaultProcessors.test.ts +371 -0
- package/template/test/framework/annotation/NewRouter.test.ts +272 -0
- package/template/test/framework/annotation/ProcessorManager.test.ts +248 -0
- package/template/test/framework/annotation/setup.ts +26 -0
- package/template/test/framework/cache.test.ts +101 -0
- package/template/test/framework/databaseConfig.test.ts +142 -0
- package/template/test/integration/integration.test.ts +153 -0
- package/template/test/plugins/weboffice/http.routes.int.test.ts +61 -0
- package/template/test/service/business.test.ts +87 -0
- package/template/test/service/paramValidateTest.service.test.ts +184 -0
- package/template/test/service/ytUser.service.test.ts +566 -0
- package/template/test/setup.ts +20 -0
- package/template/test/setupAfterEnv.ts +14 -0
- package/template/test/utils/testHelpers.ts +220 -0
- package/template/test_output.txt +0 -0
- package/template/tsconfig.build.json +17 -0
- package/template/tsconfig.json +31 -0
- package/template/webpack.config.js +71 -0
- package/template/yarn.lock +7354 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Swagger装饰器 - 用于在Controller层生成API文档
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* API文档基本配置装饰器
|
|
7
|
+
*/
|
|
8
|
+
export function Api(
|
|
9
|
+
config: {
|
|
10
|
+
tags?: string[];
|
|
11
|
+
summary?: string;
|
|
12
|
+
description?: string;
|
|
13
|
+
operationId?: string;
|
|
14
|
+
} = {}
|
|
15
|
+
): MethodDecorator {
|
|
16
|
+
return (target: any, methodName: string | symbol) => {
|
|
17
|
+
if (!target.$_SwaggerMethods) {
|
|
18
|
+
target.$_SwaggerMethods = new Map();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const methodMetadata = {
|
|
22
|
+
tags: config.tags || [],
|
|
23
|
+
summary: config.summary || '',
|
|
24
|
+
description: config.description || '',
|
|
25
|
+
operationId: config.operationId || methodName.toString(),
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
target.$_SwaggerMethods.set(methodName.toString(), methodMetadata);
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* API参数装饰器
|
|
34
|
+
*/
|
|
35
|
+
export function ApiParam(
|
|
36
|
+
config: {
|
|
37
|
+
name: string;
|
|
38
|
+
in: 'path' | 'query' | 'header' | 'cookie';
|
|
39
|
+
description?: string;
|
|
40
|
+
required?: boolean;
|
|
41
|
+
schema?: any;
|
|
42
|
+
example?: any;
|
|
43
|
+
}
|
|
44
|
+
): ParameterDecorator {
|
|
45
|
+
return (target: any, propertyKey: string | symbol | undefined, parameterIndex: number) => {
|
|
46
|
+
if (!target.$_SwaggerParams) {
|
|
47
|
+
target.$_SwaggerParams = new Map();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const methodName = propertyKey?.toString() || '';
|
|
51
|
+
if (!target.$_SwaggerParams.has(methodName)) {
|
|
52
|
+
target.$_SwaggerParams.set(methodName, []);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const params = target.$_SwaggerParams.get(methodName);
|
|
56
|
+
params.push({
|
|
57
|
+
...config,
|
|
58
|
+
parameterIndex,
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* API请求体装饰器
|
|
65
|
+
*/
|
|
66
|
+
export function ApiBody(
|
|
67
|
+
config: {
|
|
68
|
+
description?: string;
|
|
69
|
+
required?: boolean;
|
|
70
|
+
schema: any;
|
|
71
|
+
examples?: Record<string, any>;
|
|
72
|
+
}
|
|
73
|
+
): MethodDecorator {
|
|
74
|
+
return (target: any, methodName: string | symbol) => {
|
|
75
|
+
if (!target.$_SwaggerBodies) {
|
|
76
|
+
target.$_SwaggerBodies = new Map();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
target.$_SwaggerBodies.set(methodName.toString(), config);
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* API响应装饰器
|
|
85
|
+
*/
|
|
86
|
+
export function ApiResponse(
|
|
87
|
+
config: {
|
|
88
|
+
status: number;
|
|
89
|
+
description: string;
|
|
90
|
+
schema?: any;
|
|
91
|
+
examples?: Record<string, any>;
|
|
92
|
+
}
|
|
93
|
+
): MethodDecorator {
|
|
94
|
+
return (target: any, methodName: string | symbol) => {
|
|
95
|
+
if (!target.$_SwaggerResponses) {
|
|
96
|
+
target.$_SwaggerResponses = new Map();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const methodNameStr = methodName.toString();
|
|
100
|
+
if (!target.$_SwaggerResponses.has(methodNameStr)) {
|
|
101
|
+
target.$_SwaggerResponses.set(methodNameStr, []);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const responses = target.$_SwaggerResponses.get(methodNameStr);
|
|
105
|
+
responses.push(config);
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* API标签装饰器(用于Controller类)
|
|
111
|
+
*/
|
|
112
|
+
export function ApiTags(...tags: string[]): ClassDecorator {
|
|
113
|
+
return (target: any) => {
|
|
114
|
+
target.$_SwaggerTags = tags;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* API操作装饰器(用于Controller类)
|
|
120
|
+
*/
|
|
121
|
+
export function ApiOperation(
|
|
122
|
+
config: {
|
|
123
|
+
summary?: string;
|
|
124
|
+
description?: string;
|
|
125
|
+
operationId?: string;
|
|
126
|
+
} = {}
|
|
127
|
+
): MethodDecorator {
|
|
128
|
+
return (target: any, methodName: string | symbol) => {
|
|
129
|
+
if (!target.$_SwaggerOperations) {
|
|
130
|
+
target.$_SwaggerOperations = new Map();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
target.$_SwaggerOperations.set(methodName.toString(), config);
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 获取Swagger元数据
|
|
139
|
+
*/
|
|
140
|
+
export function getSwaggerMetadata(target: any) {
|
|
141
|
+
return {
|
|
142
|
+
tags: target.$_SwaggerTags || [],
|
|
143
|
+
methods: target.$_SwaggerMethods || new Map(),
|
|
144
|
+
params: target.$_SwaggerParams || new Map(),
|
|
145
|
+
bodies: target.$_SwaggerBodies || new Map(),
|
|
146
|
+
responses: target.$_SwaggerResponses || new Map(),
|
|
147
|
+
operations: target.$_SwaggerOperations || new Map(),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 高级Service调用拦截器
|
|
3
|
+
* 支持性能监控、缓存、重试等功能
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { logger } from '@src/framework/utils/logger';
|
|
7
|
+
import { ServiceCallInterceptor, ServiceCallInfo, ServiceCallPhase } from './ServiceCallInterceptor';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 拦截器配置选项
|
|
11
|
+
*/
|
|
12
|
+
export interface InterceptorOptions {
|
|
13
|
+
enablePerformanceMonitoring?: boolean;
|
|
14
|
+
enableCaching?: boolean;
|
|
15
|
+
enableRetry?: boolean;
|
|
16
|
+
enableCircuitBreaker?: boolean;
|
|
17
|
+
cacheTTL?: number;
|
|
18
|
+
maxRetries?: number;
|
|
19
|
+
retryDelay?: number;
|
|
20
|
+
circuitBreakerThreshold?: number;
|
|
21
|
+
slowCallThreshold?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 缓存项
|
|
26
|
+
*/
|
|
27
|
+
interface CacheItem {
|
|
28
|
+
key: string;
|
|
29
|
+
value: any;
|
|
30
|
+
timestamp: number;
|
|
31
|
+
ttl: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 熔断器状态
|
|
36
|
+
*/
|
|
37
|
+
enum CircuitBreakerState {
|
|
38
|
+
CLOSED = 'CLOSED',
|
|
39
|
+
OPEN = 'OPEN',
|
|
40
|
+
HALF_OPEN = 'HALF_OPEN'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 高级Service调用拦截器
|
|
45
|
+
*/
|
|
46
|
+
export class AdvancedServiceCallInterceptor {
|
|
47
|
+
private static instance: AdvancedServiceCallInterceptor;
|
|
48
|
+
private cache = new Map<string, CacheItem>();
|
|
49
|
+
private circuitBreakerState = new Map<string, CircuitBreakerState>();
|
|
50
|
+
private circuitBreakerFailures = new Map<string, number>();
|
|
51
|
+
private circuitBreakerLastFailure = new Map<string, number>();
|
|
52
|
+
private slowCalls = new Map<string, number>();
|
|
53
|
+
private options: InterceptorOptions;
|
|
54
|
+
|
|
55
|
+
constructor(options: InterceptorOptions = {}) {
|
|
56
|
+
this.options = {
|
|
57
|
+
enablePerformanceMonitoring: true,
|
|
58
|
+
enableCaching: false,
|
|
59
|
+
enableRetry: false,
|
|
60
|
+
enableCircuitBreaker: false,
|
|
61
|
+
cacheTTL: 300000, // 5分钟
|
|
62
|
+
maxRetries: 3,
|
|
63
|
+
retryDelay: 1000,
|
|
64
|
+
circuitBreakerThreshold: 5,
|
|
65
|
+
slowCallThreshold: 1000,
|
|
66
|
+
...options
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 获取单例实例
|
|
72
|
+
*/
|
|
73
|
+
public static getInstance(options?: InterceptorOptions): AdvancedServiceCallInterceptor {
|
|
74
|
+
if (!AdvancedServiceCallInterceptor.instance) {
|
|
75
|
+
AdvancedServiceCallInterceptor.instance = new AdvancedServiceCallInterceptor(options);
|
|
76
|
+
}
|
|
77
|
+
return AdvancedServiceCallInterceptor.instance;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 创建高级拦截器函数
|
|
82
|
+
*/
|
|
83
|
+
public createAdvancedInterceptor() {
|
|
84
|
+
return (params: Array<any>, instance: any, fn: Function, done: (err: any, param: any) => void) => {
|
|
85
|
+
const serviceName = instance.constructor.name;
|
|
86
|
+
const methodName = fn.name;
|
|
87
|
+
const methodKey = `${serviceName}.${methodName}`;
|
|
88
|
+
|
|
89
|
+
// 检查熔断器状态
|
|
90
|
+
if (this.options.enableCircuitBreaker && this.isCircuitBreakerOpen(methodKey)) {
|
|
91
|
+
const error = new Error(`Circuit breaker is open for ${methodKey}`);
|
|
92
|
+
logger.warn(`熔断器开启,跳过方法调用: ${methodKey}`);
|
|
93
|
+
done(error, null);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 检查缓存
|
|
98
|
+
if (this.options.enableCaching) {
|
|
99
|
+
const cacheKey = this.generateCacheKey(methodKey, params);
|
|
100
|
+
const cachedResult = this.getFromCache(cacheKey);
|
|
101
|
+
if (cachedResult) {
|
|
102
|
+
logger.info(`缓存命中: ${methodKey}`);
|
|
103
|
+
done(null, cachedResult);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 执行方法(带重试)
|
|
109
|
+
this.executeWithRetry(params, instance, fn, done, methodKey);
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 带重试的执行方法
|
|
115
|
+
*/
|
|
116
|
+
private async executeWithRetry(
|
|
117
|
+
params: Array<any>,
|
|
118
|
+
instance: any,
|
|
119
|
+
fn: Function,
|
|
120
|
+
done: (err: any, param: any) => void,
|
|
121
|
+
methodKey: string
|
|
122
|
+
) {
|
|
123
|
+
let lastError: Error | null = null;
|
|
124
|
+
const maxRetries = this.options.maxRetries || 3;
|
|
125
|
+
|
|
126
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
127
|
+
try {
|
|
128
|
+
const result = await this.executeMethod(params, instance, fn, methodKey, attempt);
|
|
129
|
+
|
|
130
|
+
// 成功时重置熔断器
|
|
131
|
+
if (this.options.enableCircuitBreaker) {
|
|
132
|
+
this.resetCircuitBreaker(methodKey);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 缓存结果
|
|
136
|
+
if (this.options.enableCaching && result) {
|
|
137
|
+
const cacheKey = this.generateCacheKey(methodKey, params);
|
|
138
|
+
this.setCache(cacheKey, result);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
done(null, result);
|
|
142
|
+
return;
|
|
143
|
+
|
|
144
|
+
} catch (error) {
|
|
145
|
+
lastError = error as Error;
|
|
146
|
+
|
|
147
|
+
// 更新熔断器状态
|
|
148
|
+
if (this.options.enableCircuitBreaker) {
|
|
149
|
+
this.recordCircuitBreakerFailure(methodKey);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// 如果不是最后一次尝试,等待后重试
|
|
153
|
+
if (attempt < maxRetries) {
|
|
154
|
+
const delay = this.options.retryDelay! * Math.pow(2, attempt); // 指数退避
|
|
155
|
+
logger.warn(`方法调用失败,${delay}ms后重试 (${attempt + 1}/${maxRetries}): ${methodKey}`,
|
|
156
|
+
`错误: ${lastError.message}, 尝试次数: ${attempt + 1}/${maxRetries}`);
|
|
157
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 所有重试都失败了
|
|
163
|
+
logger.error(`方法调用最终失败: ${methodKey}`,
|
|
164
|
+
lastError || new Error('未知错误'), `尝试次数: ${maxRetries + 1}`);
|
|
165
|
+
done(lastError, null);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 执行方法
|
|
170
|
+
*/
|
|
171
|
+
private async executeMethod(
|
|
172
|
+
params: Array<any>,
|
|
173
|
+
instance: any,
|
|
174
|
+
fn: Function,
|
|
175
|
+
methodKey: string,
|
|
176
|
+
attempt: number
|
|
177
|
+
): Promise<any> {
|
|
178
|
+
const startTime = Date.now();
|
|
179
|
+
|
|
180
|
+
logger.info(`执行方法: ${methodKey} (尝试 ${attempt + 1})`, {
|
|
181
|
+
method: methodKey,
|
|
182
|
+
attempt: attempt + 1,
|
|
183
|
+
parameters: this.sanitizeParameters(params)
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
const result = fn.apply(instance, params);
|
|
187
|
+
|
|
188
|
+
// 处理异步方法
|
|
189
|
+
if (result && typeof result.then === 'function') {
|
|
190
|
+
const asyncResult = await result;
|
|
191
|
+
const duration = Date.now() - startTime;
|
|
192
|
+
|
|
193
|
+
// 性能监控
|
|
194
|
+
if (this.options.enablePerformanceMonitoring) {
|
|
195
|
+
this.recordPerformanceMetrics(methodKey, duration);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
logger.info(`方法执行成功: ${methodKey}`, {
|
|
199
|
+
method: methodKey,
|
|
200
|
+
duration: `${duration}ms`,
|
|
201
|
+
attempt: attempt + 1
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
return asyncResult;
|
|
205
|
+
} else {
|
|
206
|
+
// 同步方法
|
|
207
|
+
const duration = Date.now() - startTime;
|
|
208
|
+
|
|
209
|
+
if (this.options.enablePerformanceMonitoring) {
|
|
210
|
+
this.recordPerformanceMetrics(methodKey, duration);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
logger.info(`方法执行成功: ${methodKey}`, {
|
|
214
|
+
method: methodKey,
|
|
215
|
+
duration: `${duration}ms`,
|
|
216
|
+
attempt: attempt + 1
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* 生成缓存键
|
|
225
|
+
*/
|
|
226
|
+
private generateCacheKey(methodKey: string, params: any[]): string {
|
|
227
|
+
const paramsHash = JSON.stringify(params);
|
|
228
|
+
return `${methodKey}:${Buffer.from(paramsHash).toString('base64')}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* 从缓存获取
|
|
233
|
+
*/
|
|
234
|
+
private getFromCache(key: string): any {
|
|
235
|
+
const item = this.cache.get(key);
|
|
236
|
+
if (item && Date.now() - item.timestamp < item.ttl) {
|
|
237
|
+
return item.value;
|
|
238
|
+
}
|
|
239
|
+
if (item) {
|
|
240
|
+
this.cache.delete(key);
|
|
241
|
+
}
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 设置缓存
|
|
247
|
+
*/
|
|
248
|
+
private setCache(key: string, value: any): void {
|
|
249
|
+
this.cache.set(key, {
|
|
250
|
+
key,
|
|
251
|
+
value,
|
|
252
|
+
timestamp: Date.now(),
|
|
253
|
+
ttl: this.options.cacheTTL!
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 检查熔断器是否开启
|
|
259
|
+
*/
|
|
260
|
+
private isCircuitBreakerOpen(methodKey: string): boolean {
|
|
261
|
+
const state = this.circuitBreakerState.get(methodKey) || CircuitBreakerState.CLOSED;
|
|
262
|
+
const failures = this.circuitBreakerFailures.get(methodKey) || 0;
|
|
263
|
+
const lastFailure = this.circuitBreakerLastFailure.get(methodKey) || 0;
|
|
264
|
+
|
|
265
|
+
if (state === CircuitBreakerState.OPEN) {
|
|
266
|
+
// 检查是否可以尝试半开状态
|
|
267
|
+
if (Date.now() - lastFailure > 60000) { // 1分钟后尝试半开
|
|
268
|
+
this.circuitBreakerState.set(methodKey, CircuitBreakerState.HALF_OPEN);
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
return true;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* 记录熔断器失败
|
|
279
|
+
*/
|
|
280
|
+
private recordCircuitBreakerFailure(methodKey: string): void {
|
|
281
|
+
const failures = (this.circuitBreakerFailures.get(methodKey) || 0) + 1;
|
|
282
|
+
this.circuitBreakerFailures.set(methodKey, failures);
|
|
283
|
+
this.circuitBreakerLastFailure.set(methodKey, Date.now());
|
|
284
|
+
|
|
285
|
+
if (failures >= this.options.circuitBreakerThreshold!) {
|
|
286
|
+
this.circuitBreakerState.set(methodKey, CircuitBreakerState.OPEN);
|
|
287
|
+
logger.warn(`熔断器开启: ${methodKey}`, {
|
|
288
|
+
failures,
|
|
289
|
+
threshold: this.options.circuitBreakerThreshold
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* 重置熔断器
|
|
296
|
+
*/
|
|
297
|
+
private resetCircuitBreaker(methodKey: string): void {
|
|
298
|
+
this.circuitBreakerState.set(methodKey, CircuitBreakerState.CLOSED);
|
|
299
|
+
this.circuitBreakerFailures.set(methodKey, 0);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* 记录性能指标
|
|
304
|
+
*/
|
|
305
|
+
private recordPerformanceMetrics(methodKey: string, duration: number): void {
|
|
306
|
+
const slowCalls = this.slowCalls.get(methodKey) || 0;
|
|
307
|
+
|
|
308
|
+
if (duration > this.options.slowCallThreshold!) {
|
|
309
|
+
this.slowCalls.set(methodKey, slowCalls + 1);
|
|
310
|
+
logger.warn(`慢调用检测: ${methodKey}`, {
|
|
311
|
+
duration: `${duration}ms`,
|
|
312
|
+
threshold: `${this.options.slowCallThreshold}ms`,
|
|
313
|
+
slowCalls: slowCalls + 1
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 清理敏感参数
|
|
320
|
+
*/
|
|
321
|
+
private sanitizeParameters(params: any[]): any[] {
|
|
322
|
+
return params.map(param => {
|
|
323
|
+
if (typeof param === 'object' && param !== null) {
|
|
324
|
+
const sanitized = { ...param };
|
|
325
|
+
if ('password' in sanitized) sanitized.password = '***';
|
|
326
|
+
if ('token' in sanitized) sanitized.token = '***';
|
|
327
|
+
if ('secret' in sanitized) sanitized.secret = '***';
|
|
328
|
+
return sanitized;
|
|
329
|
+
}
|
|
330
|
+
return param;
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 获取拦截器状态
|
|
336
|
+
*/
|
|
337
|
+
public getStatus(): any {
|
|
338
|
+
return {
|
|
339
|
+
cacheSize: this.cache.size,
|
|
340
|
+
circuitBreakerStates: Object.fromEntries(this.circuitBreakerState),
|
|
341
|
+
circuitBreakerFailures: Object.fromEntries(this.circuitBreakerFailures),
|
|
342
|
+
slowCalls: Object.fromEntries(this.slowCalls),
|
|
343
|
+
options: this.options
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* 清理缓存
|
|
349
|
+
*/
|
|
350
|
+
public clearCache(): void {
|
|
351
|
+
this.cache.clear();
|
|
352
|
+
logger.info('拦截器缓存已清理');
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* 重置熔断器
|
|
357
|
+
*/
|
|
358
|
+
public resetCircuitBreakers(): void {
|
|
359
|
+
this.circuitBreakerState.clear();
|
|
360
|
+
this.circuitBreakerFailures.clear();
|
|
361
|
+
this.circuitBreakerLastFailure.clear();
|
|
362
|
+
logger.info('所有熔断器已重置');
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* 创建高级拦截器实例
|
|
368
|
+
*/
|
|
369
|
+
export const advancedServiceCallInterceptor = AdvancedServiceCallInterceptor.getInstance();
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* 导出高级拦截器创建函数
|
|
373
|
+
*/
|
|
374
|
+
export const createAdvancedServiceCallInterceptor = (options?: InterceptorOptions) =>
|
|
375
|
+
AdvancedServiceCallInterceptor.getInstance(options).createAdvancedInterceptor();
|