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,123 @@
|
|
|
1
|
+
import { DataSourceOptions } from "typeorm";
|
|
2
|
+
import { bootstrap, setAfterBootstrap, setBeforeBootstrap } from "./framework/utils/bootstrap";
|
|
3
|
+
import { initDb, closeDb, getDataSource } from "@src/framework/utils/db";
|
|
4
|
+
import { clearAllCaches } from "@src/framework/utils/cache";
|
|
5
|
+
import { databaseConfigManager } from "@src/framework/utils/databaseConfig";
|
|
6
|
+
import { migrationManager } from "@src/framework/utils/MigrationManager";
|
|
7
|
+
import { transactionManager } from "@src/framework/utils/TransactionManager";
|
|
8
|
+
import { cacheManager } from "@src/framework/utils/CacheManager";
|
|
9
|
+
import { testDataInitializer } from "@src/utils/testDataInitializer";
|
|
10
|
+
import { isDebug, sleep } from "@src/framework/utils/function";
|
|
11
|
+
import { logger } from "@src/framework/utils/logger";
|
|
12
|
+
import { MigrationHelper } from "@src/framework/utils/MigrationHelper";
|
|
13
|
+
import { AnnotationSystemInitializer } from "@src/framework/decorator/processor/AnnotationSystemInitializer";
|
|
14
|
+
import { annotationRegistry } from "@src/framework/decorator/processor/AnnotationRegistry";
|
|
15
|
+
import { createGracefulShutdownController } from "@src/framework/utils/gracefulShutdown";
|
|
16
|
+
import Router from "@src/routers";
|
|
17
|
+
import dbEntities from "@src/entity"
|
|
18
|
+
import { router } from "@src/framework/utils/router";
|
|
19
|
+
import {
|
|
20
|
+
collectPluginEntities,
|
|
21
|
+
getEnabledPlugins,
|
|
22
|
+
registerPluginRoutes,
|
|
23
|
+
runAfterBootstrapHooks,
|
|
24
|
+
runBeforeBootstrapHooks,
|
|
25
|
+
} from "@src/framework/plugins/registry";
|
|
26
|
+
import Koa from "koa";
|
|
27
|
+
import path from "path";
|
|
28
|
+
import staticMiddleware from "@src/middlewares/static.middleware";
|
|
29
|
+
|
|
30
|
+
const shutdown = createGracefulShutdownController({ logger });
|
|
31
|
+
|
|
32
|
+
setBeforeBootstrap(async function (app: Koa) {
|
|
33
|
+
// await sleep(3000)
|
|
34
|
+
|
|
35
|
+
// 尽早注册优雅关闭(避免启动期间 SIGINT/SIGTERM 丢失)
|
|
36
|
+
shutdown.register();
|
|
37
|
+
|
|
38
|
+
// 关闭时需要清理的核心资源(与启动流程解耦)
|
|
39
|
+
shutdown.addHook('annotationRegistry.cleanup', () => annotationRegistry.cleanup());
|
|
40
|
+
shutdown.addHook('transactionManager.cleanup', () => transactionManager.cleanup());
|
|
41
|
+
shutdown.addHook('clearAllCaches', () => clearAllCaches());
|
|
42
|
+
shutdown.addHook('closeDb', () => closeDb());
|
|
43
|
+
|
|
44
|
+
const enabledPlugins = getEnabledPlugins();
|
|
45
|
+
(app as any).plugins = enabledPlugins;
|
|
46
|
+
await runBeforeBootstrapHooks(app, enabledPlugins);
|
|
47
|
+
|
|
48
|
+
// 静态资源映射:默认 /static -> ./static
|
|
49
|
+
// 可通过环境变量覆盖:STATIC_URL_PREFIX、STATIC_DIR、STATIC_MAX_AGE_SECONDS、STATIC_INDEX
|
|
50
|
+
app.use(staticMiddleware({
|
|
51
|
+
urlPrefix: '/static',
|
|
52
|
+
dir: path.join(process.cwd(), 'static'),
|
|
53
|
+
maxAgeSeconds: 60 * 60 * 24 * 30,
|
|
54
|
+
index: 'index.html',
|
|
55
|
+
defer: false,
|
|
56
|
+
hidden: false,
|
|
57
|
+
}));
|
|
58
|
+
|
|
59
|
+
// 初始化新注解处理器系统
|
|
60
|
+
MigrationHelper.initializeNewSystem();
|
|
61
|
+
|
|
62
|
+
// 初始化注解系统(注册所有处理器)
|
|
63
|
+
AnnotationSystemInitializer.initialize();
|
|
64
|
+
|
|
65
|
+
// 记录系统状态
|
|
66
|
+
const systemStatus = MigrationHelper.getSystemStatus();
|
|
67
|
+
logger.info(`注解系统状态: ${systemStatus.newSystemEnabled ? '新系统' : '旧系统'}, 环境: ${systemStatus.environment}`);
|
|
68
|
+
|
|
69
|
+
Router();
|
|
70
|
+
registerPluginRoutes(router, enabledPlugins);
|
|
71
|
+
if (databaseConfigManager.isDatabaseEnabled()) {
|
|
72
|
+
try {
|
|
73
|
+
// 根据环境选择数据库配置(支持内存数据库模式)
|
|
74
|
+
const allEntities = [...dbEntities, ...collectPluginEntities(enabledPlugins)];
|
|
75
|
+
const dbconfig = databaseConfigManager.getDatabaseConfig(allEntities);
|
|
76
|
+
|
|
77
|
+
await initDb(dbconfig);
|
|
78
|
+
logger.info(`数据库初始化成功 - 模式: ${databaseConfigManager.getDatabaseTypeDescription()}`);
|
|
79
|
+
|
|
80
|
+
// 设置事务管理器的数据源
|
|
81
|
+
const dataSource = getDataSource();
|
|
82
|
+
if (dataSource) {
|
|
83
|
+
transactionManager.setDataSource(dataSource);
|
|
84
|
+
migrationManager.setDataSource(dataSource);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 非 debug(生产口径)执行迁移
|
|
88
|
+
if (!isDebug()) {
|
|
89
|
+
await migrationManager.runMigrations();
|
|
90
|
+
logger.info('数据库迁移执行完成');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// 如果是内存数据库模式,初始化测试数据
|
|
94
|
+
if (databaseConfigManager.isMemoryDatabaseMode()) {
|
|
95
|
+
await testDataInitializer.initializeTestData();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
} catch (err) {
|
|
99
|
+
logger.error("数据库初始化异常", err as Error)
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
logger.info("启动前初始化完毕");
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
setAfterBootstrap(async function (app: Koa) {
|
|
107
|
+
logger.info("启动后执行");
|
|
108
|
+
const enabledPlugins = getEnabledPlugins();
|
|
109
|
+
await runAfterBootstrapHooks(app, enabledPlugins);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// 应用启动
|
|
113
|
+
(async () => {
|
|
114
|
+
try {
|
|
115
|
+
logger.info("启动应用");
|
|
116
|
+
await bootstrap();
|
|
117
|
+
logger.info("启动成功");
|
|
118
|
+
} catch (error) {
|
|
119
|
+
logger.error("启动失败", error as Error);
|
|
120
|
+
process.exit(1);
|
|
121
|
+
}
|
|
122
|
+
})()
|
|
123
|
+
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
|
|
2
|
+
/**
|
|
3
|
+
* 基础controller类
|
|
4
|
+
*/
|
|
5
|
+
export class ControllerResponse<T> {
|
|
6
|
+
|
|
7
|
+
code = 0;
|
|
8
|
+
data: T | null = null;
|
|
9
|
+
message: string = ""
|
|
10
|
+
|
|
11
|
+
constructor(code: number, data: T | null, message?: string) {
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.data = data;
|
|
14
|
+
if (message) {
|
|
15
|
+
this.message = message;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export class BaseController {
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 响应成功
|
|
23
|
+
* @param data
|
|
24
|
+
* @param message
|
|
25
|
+
* @returns
|
|
26
|
+
*/
|
|
27
|
+
success<T>(data: T, message?: string) {
|
|
28
|
+
return new ControllerResponse<T>(0, data, message);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 响应失败
|
|
34
|
+
* @param code
|
|
35
|
+
* @param message
|
|
36
|
+
* @returns
|
|
37
|
+
*/
|
|
38
|
+
fail<T>(code: number, message?: string) {
|
|
39
|
+
return new ControllerResponse<T>(code, null, message);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Get, Post } from '@src/framework/decorator/controller';
|
|
2
|
+
import { Body } from '@src/framework/decorator/controller';
|
|
3
|
+
import { BaseController } from '@src/controllers/base.controller';
|
|
4
|
+
import { getCache, deleteCache, getCacheStats, getCacheMemoryUsage, clearAllCaches } from '@src/framework/utils/cache';
|
|
5
|
+
import { logger } from '@src/framework/utils/logger';
|
|
6
|
+
|
|
7
|
+
export class CacheManagementController extends BaseController {
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 获取所有缓存统计信息
|
|
11
|
+
*/
|
|
12
|
+
@Get('/cache/stats')
|
|
13
|
+
async getCacheStats() {
|
|
14
|
+
const stats = getCacheStats();
|
|
15
|
+
const memory = getCacheMemoryUsage();
|
|
16
|
+
|
|
17
|
+
return this.success({
|
|
18
|
+
stats,
|
|
19
|
+
memory,
|
|
20
|
+
timestamp: new Date().toISOString()
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 清理指定缓存
|
|
26
|
+
*/
|
|
27
|
+
@Post('/cache/clear')
|
|
28
|
+
async clearCache(@Body() body: { cacheName: string }) {
|
|
29
|
+
const { cacheName } = body;
|
|
30
|
+
|
|
31
|
+
if (!cacheName) {
|
|
32
|
+
return this.fail(400, '缓存名称不能为空');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
const cache = getCache(cacheName);
|
|
37
|
+
if (!cache) {
|
|
38
|
+
return this.fail(404, `缓存 ${cacheName} 不存在`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 清空缓存内容
|
|
42
|
+
cache.flushAll();
|
|
43
|
+
logger.info(`手动清理缓存: ${cacheName}`);
|
|
44
|
+
|
|
45
|
+
return this.success({
|
|
46
|
+
message: `缓存 ${cacheName} 已清理`,
|
|
47
|
+
cacheName,
|
|
48
|
+
timestamp: new Date().toISOString()
|
|
49
|
+
});
|
|
50
|
+
} catch (error) {
|
|
51
|
+
logger.error(`清理缓存 ${cacheName} 失败:`, error as Error);
|
|
52
|
+
return this.fail(500, `清理缓存失败: ${error instanceof Error ? error.message : '未知错误'}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 删除指定缓存实例
|
|
58
|
+
*/
|
|
59
|
+
@Post('/cache/delete')
|
|
60
|
+
async deleteCache(@Body() body: { cacheName: string }) {
|
|
61
|
+
const { cacheName } = body;
|
|
62
|
+
|
|
63
|
+
if (!cacheName) {
|
|
64
|
+
return this.fail(400, '缓存名称不能为空');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
deleteCache(cacheName);
|
|
69
|
+
logger.info(`删除缓存实例: ${cacheName}`);
|
|
70
|
+
|
|
71
|
+
return this.success({
|
|
72
|
+
message: `缓存实例 ${cacheName} 已删除`,
|
|
73
|
+
cacheName,
|
|
74
|
+
timestamp: new Date().toISOString()
|
|
75
|
+
});
|
|
76
|
+
} catch (error) {
|
|
77
|
+
logger.error(`删除缓存实例 ${cacheName} 失败:`, error as Error);
|
|
78
|
+
return this.fail(500, `删除缓存实例失败: ${error instanceof Error ? error.message : '未知错误'}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 清理所有缓存
|
|
84
|
+
*/
|
|
85
|
+
@Post('/cache/clear-all')
|
|
86
|
+
async clearAllCache() {
|
|
87
|
+
try {
|
|
88
|
+
clearAllCaches();
|
|
89
|
+
logger.info('手动清理所有缓存');
|
|
90
|
+
|
|
91
|
+
return this.success({
|
|
92
|
+
message: '所有缓存已清理',
|
|
93
|
+
timestamp: new Date().toISOString()
|
|
94
|
+
});
|
|
95
|
+
} catch (error) {
|
|
96
|
+
logger.error('清理所有缓存失败:', error as Error);
|
|
97
|
+
return this.fail(500, `清理所有缓存失败: ${error instanceof Error ? error.message : '未知错误'}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 获取特定缓存的详细信息
|
|
103
|
+
*/
|
|
104
|
+
@Get('/cache/info')
|
|
105
|
+
async getCacheInfo(@Body() body: { cacheName: string }) {
|
|
106
|
+
const { cacheName } = body;
|
|
107
|
+
|
|
108
|
+
if (!cacheName) {
|
|
109
|
+
return this.fail(400, '缓存名称不能为空');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const cache = getCache(cacheName);
|
|
113
|
+
if (!cache) {
|
|
114
|
+
return this.fail(404, `缓存 ${cacheName} 不存在`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const keys = cache.keys();
|
|
118
|
+
const stats = getCacheStats();
|
|
119
|
+
const memory = getCacheMemoryUsage();
|
|
120
|
+
|
|
121
|
+
return this.success({
|
|
122
|
+
cacheName,
|
|
123
|
+
keys: keys.slice(0, 10), // 只显示前10个键
|
|
124
|
+
totalKeys: keys.length,
|
|
125
|
+
stats: stats[cacheName] || null,
|
|
126
|
+
memory: memory[cacheName] || null,
|
|
127
|
+
config: cache.options,
|
|
128
|
+
timestamp: new Date().toISOString()
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
|
|
2
|
+
import { Get, Post } from '@src/framework/decorator/controller';
|
|
3
|
+
import { Body } from '@src/framework/decorator/controller';
|
|
4
|
+
import { CaptchaGenerator } from '@src/libs/captcha';
|
|
5
|
+
import { Inject } from 'dp-ioc2';
|
|
6
|
+
import { createCache, CacheType } from '@src/framework/utils/cache';
|
|
7
|
+
|
|
8
|
+
// 创建验证码缓存实例
|
|
9
|
+
const captchaCache = createCache('captcha-controller', CacheType.CAPTCHA, {
|
|
10
|
+
stdTTL: 300, // 5分钟过期
|
|
11
|
+
maxKeys: 100 // 最多100个验证码
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export class CaptchaController {
|
|
15
|
+
|
|
16
|
+
// @Inject(CaptchaGenerator)
|
|
17
|
+
// captchaGenerator: CaptchaGenerator;
|
|
18
|
+
|
|
19
|
+
@Get('/captcha')
|
|
20
|
+
async getCaptcha() {
|
|
21
|
+
const { image, token } = CaptchaGenerator.generate();
|
|
22
|
+
return {
|
|
23
|
+
image,
|
|
24
|
+
token,
|
|
25
|
+
contentType: 'image/svg+xml'
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
@Post('/captcha/verify')
|
|
30
|
+
async verifyCaptcha(
|
|
31
|
+
@Body() body: { captcha: string, token: string }
|
|
32
|
+
) {
|
|
33
|
+
const { captcha, token } = body;
|
|
34
|
+
if (!token) {
|
|
35
|
+
return {
|
|
36
|
+
status: 400,
|
|
37
|
+
body: { success: false, message: 'Missing captcha token' }
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 检查是否已经验证过(防止重复验证)
|
|
42
|
+
const verifyKey = `verify_${token}`;
|
|
43
|
+
if (captchaCache.get(verifyKey)) {
|
|
44
|
+
return { success: false, message: '验证码已使用' };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const isValid = CaptchaGenerator.verify(token, captcha);
|
|
48
|
+
|
|
49
|
+
if (isValid) {
|
|
50
|
+
// 验证成功后标记为已使用,防止重复验证
|
|
51
|
+
captchaCache.set(verifyKey, true, 300); // 5分钟内不能重复验证
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return { success: isValid };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Get, Query, State } from '@src/framework/decorator/controller';
|
|
2
|
+
import { Logging, Permission, RateLimit } from '@src/framework/decorator/processor/AnnotationDecorators';
|
|
3
|
+
import { PerformanceMonitor } from '@src/annotations/decorators/PerformanceMonitor';
|
|
4
|
+
import { BaseController } from '@src/controllers/base.controller';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 注解演示控制器
|
|
8
|
+
* 展示业务层自定义注解的使用方法
|
|
9
|
+
*/
|
|
10
|
+
export class AnnotationDemoController extends BaseController {
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 示例1: 基础性能监控
|
|
14
|
+
* 使用默认配置的性能监控注解
|
|
15
|
+
*/
|
|
16
|
+
@Get('/demo/performance/basic')
|
|
17
|
+
@PerformanceMonitor()
|
|
18
|
+
async getBasicPerformanceData(@Query() query: any) {
|
|
19
|
+
// 模拟一些处理时间
|
|
20
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
code: 0,
|
|
24
|
+
data: {
|
|
25
|
+
message: '基础性能监控示例',
|
|
26
|
+
query,
|
|
27
|
+
timestamp: Date.now()
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 示例2: 带配置的性能监控
|
|
34
|
+
* 设置执行时间和内存使用阈值
|
|
35
|
+
*/
|
|
36
|
+
@Get('/demo/performance/configured')
|
|
37
|
+
@PerformanceMonitor({
|
|
38
|
+
maxExecutionTime: 200,
|
|
39
|
+
maxMemoryUsage: 5,
|
|
40
|
+
verbose: true
|
|
41
|
+
})
|
|
42
|
+
async getConfiguredPerformanceData(@Query() query: any) {
|
|
43
|
+
// 模拟较重的操作
|
|
44
|
+
const data = [];
|
|
45
|
+
for (let i = 0; i < 10000; i++) {
|
|
46
|
+
data.push({ id: i, value: Math.random() });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
code: 0,
|
|
51
|
+
data: {
|
|
52
|
+
message: '配置化性能监控示例',
|
|
53
|
+
query,
|
|
54
|
+
dataLength: data.length,
|
|
55
|
+
timestamp: Date.now()
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 示例3: 组合注解使用
|
|
62
|
+
* 同时使用性能监控、日志记录、权限检查和限流
|
|
63
|
+
*/
|
|
64
|
+
@Get('/demo/performance/combined')
|
|
65
|
+
@PerformanceMonitor({ maxExecutionTime: 500 })
|
|
66
|
+
@Logging()
|
|
67
|
+
@Permission({ requiredPermission: 'read:performance' })
|
|
68
|
+
@RateLimit({ maxRequests: 5, windowMs: 60000 })
|
|
69
|
+
async getCombinedAnnotationData(@Query() query: any, @State() state: any, ctx: any) {
|
|
70
|
+
// 模拟复杂业务逻辑
|
|
71
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
72
|
+
|
|
73
|
+
const result = {
|
|
74
|
+
code: 0,
|
|
75
|
+
data: {
|
|
76
|
+
message: '组合注解示例',
|
|
77
|
+
query,
|
|
78
|
+
user: state.user,
|
|
79
|
+
timestamp: Date.now(),
|
|
80
|
+
performance: 'monitored'
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// 性能监控结果现在会自动记录,无需手动调用
|
|
85
|
+
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 示例4: 性能警告触发
|
|
91
|
+
* 故意触发性能警告的示例
|
|
92
|
+
*/
|
|
93
|
+
@Get('/demo/performance/warning')
|
|
94
|
+
@PerformanceMonitor({
|
|
95
|
+
maxExecutionTime: 50, // 设置很低的阈值
|
|
96
|
+
maxMemoryUsage: 1 // 设置很低的内存阈值
|
|
97
|
+
})
|
|
98
|
+
async getPerformanceWarningData(@Query() query: any) {
|
|
99
|
+
// 故意执行耗时操作
|
|
100
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
101
|
+
|
|
102
|
+
// 故意使用大量内存
|
|
103
|
+
const largeArray = new Array(100000).fill(0).map((_, i) => ({
|
|
104
|
+
id: i,
|
|
105
|
+
data: 'x'.repeat(100)
|
|
106
|
+
}));
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
code: 0,
|
|
110
|
+
data: {
|
|
111
|
+
message: '性能警告触发示例',
|
|
112
|
+
query,
|
|
113
|
+
arrayLength: largeArray.length,
|
|
114
|
+
timestamp: Date.now()
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|