create-dp-koa 1.1.1 → 1.1.3

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 (84) hide show
  1. package/package.json +1 -1
  2. package/template/scripts/sync-template.mjs +21 -0
  3. package/template/src/app.ts +1 -2
  4. package/template/src/{framework/plugins → plugins}/registry.ts +2 -2
  5. package/template/src/plugins/weboffice/http/routes.ts +2 -2
  6. package/template/src/plugins/weboffice/index.ts +3 -3
  7. package/template/src/plugins/weboffice/services/webofficeCallback.service.ts +3 -4
  8. package/template/src/utils/testDataInitializer.ts +1 -1
  9. package/template/tsconfig.json +6 -0
  10. package/template/src/annotations/decorators/ConfigManagement.ts +0 -9
  11. package/template/src/annotations/decorators/DistributedTracing.ts +0 -9
  12. package/template/src/annotations/decorators/EnterprisePerformance.ts +0 -9
  13. package/template/src/annotations/decorators/PerformanceMonitor.ts +0 -32
  14. package/template/src/annotations/decorators/SecurityAudit.ts +0 -9
  15. package/template/src/annotations/index.ts +0 -50
  16. package/template/src/annotations/processors/ConfigManagementProcessor.ts +0 -369
  17. package/template/src/annotations/processors/DistributedTracingProcessor.ts +0 -288
  18. package/template/src/annotations/processors/EnterprisePerformanceProcessor.ts +0 -189
  19. package/template/src/annotations/processors/PerformanceMonitorProcessor.ts +0 -101
  20. package/template/src/annotations/processors/SecurityAuditProcessor.ts +0 -345
  21. package/template/src/annotations/processors/SwaggerProcessor.ts +0 -612
  22. package/template/src/annotations/processors/index.ts +0 -10
  23. package/template/src/examples/InterceptorExampleRunner.ts +0 -284
  24. package/template/src/examples/ServiceInterceptorExample.ts +0 -214
  25. package/template/src/examples/cacheExamples.ts +0 -155
  26. package/template/src/framework/decorator/controller.ts +0 -311
  27. package/template/src/framework/decorator/processor/AnnotationDecorators.ts +0 -100
  28. package/template/src/framework/decorator/processor/AnnotationProcessor.ts +0 -160
  29. package/template/src/framework/decorator/processor/AnnotationProcessorConfig.ts +0 -45
  30. package/template/src/framework/decorator/processor/AnnotationRegistry.ts +0 -117
  31. package/template/src/framework/decorator/processor/AnnotationSystemInitializer.ts +0 -95
  32. package/template/src/framework/decorator/processor/ProcessorManager.ts +0 -76
  33. package/template/src/framework/decorator/processor/processors/CustomProcessors.ts +0 -126
  34. package/template/src/framework/decorator/processor/processors/DefaultProcessors.ts +0 -207
  35. package/template/src/framework/decorator/refactored/DecoratorFactory.ts +0 -99
  36. package/template/src/framework/decorator/refactored/DecoratorMetadataManager.ts +0 -125
  37. package/template/src/framework/decorator/refactored/DecoratorValidator.ts +0 -128
  38. package/template/src/framework/decorator/refactored/TypeSafeDecorators.ts +0 -139
  39. package/template/src/framework/decorator/refactored/index.ts +0 -98
  40. package/template/src/framework/decorator/swagger.ts +0 -150
  41. package/template/src/framework/interceptors/AdvancedServiceCallInterceptor.ts +0 -375
  42. package/template/src/framework/interceptors/ServiceCallInterceptor.ts +0 -348
  43. package/template/src/framework/interceptors/index.ts +0 -19
  44. package/template/src/framework/plugins/types.ts +0 -15
  45. package/template/src/framework/types/ServiceResult.ts +0 -151
  46. package/template/src/framework/types/index.ts +0 -16
  47. package/template/src/framework/utils/CacheManager.ts +0 -430
  48. package/template/src/framework/utils/CacheService.ts +0 -248
  49. package/template/src/framework/utils/DtoValidator.ts +0 -164
  50. package/template/src/framework/utils/MigrationHelper.ts +0 -179
  51. package/template/src/framework/utils/MigrationManager.ts +0 -256
  52. package/template/src/framework/utils/NewRouter.ts +0 -207
  53. package/template/src/framework/utils/TransactionManager.ts +0 -172
  54. package/template/src/framework/utils/bootstrap.ts +0 -445
  55. package/template/src/framework/utils/cache.ts +0 -269
  56. package/template/src/framework/utils/databaseConfig.ts +0 -148
  57. package/template/src/framework/utils/db.ts +0 -39
  58. package/template/src/framework/utils/dbMonitor.ts +0 -106
  59. package/template/src/framework/utils/function.ts +0 -61
  60. package/template/src/framework/utils/gracefulShutdown.ts +0 -131
  61. package/template/src/framework/utils/logger.ts +0 -388
  62. package/template/src/framework/utils/metrics.ts +0 -182
  63. package/template/src/framework/utils/router.ts +0 -417
  64. package/template/src/framework/utils/swagger.ts +0 -184
  65. package/template/src/framework/utils/testDb.ts +0 -19
  66. package/template/src/framework/utils/token.ts +0 -23
  67. package/template/src/framework/utils/transform.ts +0 -17
  68. package/template/src/libs/aokEmailSender.ts +0 -42
  69. package/template/src/libs/captcha.ts +0 -37
  70. package/template/src/libs/cos.ts +0 -45
  71. package/template/src/libs/mCache.ts +0 -7
  72. package/template/src/libs/serviceValidate.ts +0 -3
  73. package/template/src/libs/tecentSms.ts +0 -51
  74. package/template/src/middlewares/a.middleware.ts +0 -6
  75. package/template/src/middlewares/error.middleware.ts +0 -14
  76. package/template/src/middlewares/logging.middleware.ts +0 -187
  77. package/template/src/middlewares/static.middleware.ts +0 -79
  78. package/template/src/middlewares/swagger.middleware.ts +0 -70
  79. package/template/src/middlewares/token.middleware.ts +0 -32
  80. package/template/src/migrations/1700000000000-InitialDatabaseStructure.ts +0 -172
  81. package/template/src/migrations/index.ts +0 -6
  82. package/template/src/repository/base/BaseRepository.ts +0 -124
  83. package/template/src/repository/interfaces/IBaseRepository.ts +0 -67
  84. package/template/src/service/base.service.ts +0 -116
@@ -1,172 +0,0 @@
1
- import { MigrationInterface, QueryRunner } from 'typeorm';
2
-
3
- /**
4
- * 初始数据库结构迁移
5
- * 创建所有基础表结构
6
- */
7
- export class InitialDatabaseStructure1700000000000 implements MigrationInterface {
8
- name = 'InitialDatabaseStructure1700000000000';
9
-
10
- public async up(queryRunner: QueryRunner): Promise<void> {
11
- // 创建用户表
12
- await queryRunner.query(`
13
- CREATE TABLE \`yt_user\` (
14
- \`id\` int NOT NULL AUTO_INCREMENT,
15
- \`nickName\` varchar(255) NOT NULL DEFAULT '',
16
- \`telnumber\` varchar(255) NOT NULL DEFAULT '',
17
- \`email\` varchar(255) NOT NULL DEFAULT '',
18
- \`password\` varchar(255) NOT NULL DEFAULT '',
19
- \`userType\` varchar(50) NOT NULL DEFAULT 'CUSTOMER',
20
- \`gender\` int NOT NULL DEFAULT '0',
21
- \`age\` int NOT NULL DEFAULT '0',
22
- \`constellation\` varchar(255) NOT NULL DEFAULT '',
23
- \`avatar\` varchar(255) NOT NULL DEFAULT '',
24
- \`status\` varchar(50) NOT NULL DEFAULT 'normal',
25
- \`updateDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
26
- \`createDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
27
- PRIMARY KEY (\`id\`),
28
- UNIQUE KEY \`IDX_yt_user_email\` (\`email\`),
29
- UNIQUE KEY \`IDX_yt_user_telnumber\` (\`telnumber\`),
30
- KEY \`IDX_yt_user_status\` (\`status\`),
31
- KEY \`IDX_yt_user_userType\` (\`userType\`)
32
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
33
- `);
34
-
35
- // 创建店铺表
36
- await queryRunner.query(`
37
- CREATE TABLE \`shop\` (
38
- \`id\` int NOT NULL AUTO_INCREMENT,
39
- \`name\` varchar(255) NOT NULL DEFAULT '',
40
- \`description\` varchar(255) NOT NULL DEFAULT '',
41
- \`status\` varchar(50) NOT NULL DEFAULT 'NORMAL',
42
- \`updateDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
43
- \`createDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
44
- PRIMARY KEY (\`id\`),
45
- KEY \`IDX_shop_status\` (\`status\`)
46
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
47
- `);
48
-
49
- // 创建店铺用户关联表
50
- await queryRunner.query(`
51
- CREATE TABLE \`shop_and_user\` (
52
- \`id\` int NOT NULL AUTO_INCREMENT,
53
- \`shopId\` int NOT NULL DEFAULT '0',
54
- \`userId\` int NOT NULL DEFAULT '0',
55
- \`updateDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
56
- \`createDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
57
- PRIMARY KEY (\`id\`),
58
- UNIQUE KEY \`IDX_shop_and_user_shopId\` (\`shopId\`),
59
- UNIQUE KEY \`IDX_shop_and_user_userId\` (\`userId\`),
60
- KEY \`IDX_shop_and_user_shopId_userId\` (\`shopId\`, \`userId\`)
61
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
62
- `);
63
-
64
- // 创建商品表
65
- await queryRunner.query(`
66
- CREATE TABLE \`yt_goods\` (
67
- \`id\` int NOT NULL AUTO_INCREMENT,
68
- \`name\` varchar(255) NOT NULL DEFAULT '',
69
- \`shopId\` int NOT NULL DEFAULT '0',
70
- \`albums\` text NOT NULL,
71
- \`price\` decimal(10,2) NOT NULL DEFAULT '0.00',
72
- \`tags\` text NOT NULL,
73
- \`description\` varchar(255) NOT NULL DEFAULT '',
74
- \`content\` text NOT NULL,
75
- \`imagesContent\` text NOT NULL,
76
- \`status\` varchar(50) NOT NULL DEFAULT 'NORMAL',
77
- \`updateDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
78
- \`createDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
79
- PRIMARY KEY (\`id\`),
80
- KEY \`IDX_yt_goods_name\` (\`name\`),
81
- KEY \`IDX_yt_goods_shopId\` (\`shopId\`),
82
- KEY \`IDX_yt_goods_status\` (\`status\`)
83
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
84
- `);
85
-
86
- // 创建商品解锁记录表
87
- await queryRunner.query(`
88
- CREATE TABLE \`yt_goods_unlock\` (
89
- \`id\` int NOT NULL AUTO_INCREMENT,
90
- \`goodsId\` int NOT NULL DEFAULT '0',
91
- \`ytUserId\` int NOT NULL DEFAULT '0',
92
- \`updateDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
93
- \`createDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
94
- PRIMARY KEY (\`id\`),
95
- KEY \`IDX_yt_goods_unlock_goodsId\` (\`goodsId\`),
96
- KEY \`IDX_yt_goods_unlock_ytUserId\` (\`ytUserId\`),
97
- UNIQUE KEY \`IDX_yt_goods_unlock_goods_user\` (\`goodsId\`, \`ytUserId\`)
98
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
99
- `);
100
-
101
- // 创建商品图片解锁密钥表
102
- await queryRunner.query(`
103
- CREATE TABLE \`goods_images_unlock_key\` (
104
- \`id\` int NOT NULL AUTO_INCREMENT,
105
- \`key\` varchar(255) NOT NULL DEFAULT '',
106
- \`goodsId\` int NOT NULL DEFAULT '0',
107
- \`isUse\` tinyint(1) NOT NULL DEFAULT '0',
108
- \`updateDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
109
- \`createDate\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
110
- PRIMARY KEY (\`id\`),
111
- UNIQUE KEY \`IDX_goods_images_unlock_key_key\` (\`key\`),
112
- KEY \`IDX_goods_images_unlock_key_goodsId\` (\`goodsId\`),
113
- KEY \`IDX_goods_images_unlock_key_isUse\` (\`isUse\`)
114
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
115
- `);
116
-
117
- // 添加外键约束
118
- await queryRunner.query(`
119
- ALTER TABLE \`shop_and_user\`
120
- ADD CONSTRAINT \`FK_shop_and_user_shopId\`
121
- FOREIGN KEY (\`shopId\`) REFERENCES \`shop\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE
122
- `);
123
-
124
- await queryRunner.query(`
125
- ALTER TABLE \`shop_and_user\`
126
- ADD CONSTRAINT \`FK_shop_and_user_userId\`
127
- FOREIGN KEY (\`userId\`) REFERENCES \`yt_user\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE
128
- `);
129
-
130
- await queryRunner.query(`
131
- ALTER TABLE \`yt_goods\`
132
- ADD CONSTRAINT \`FK_yt_goods_shopId\`
133
- FOREIGN KEY (\`shopId\`) REFERENCES \`shop\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE
134
- `);
135
-
136
- await queryRunner.query(`
137
- ALTER TABLE \`yt_goods_unlock\`
138
- ADD CONSTRAINT \`FK_yt_goods_unlock_goodsId\`
139
- FOREIGN KEY (\`goodsId\`) REFERENCES \`yt_goods\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE
140
- `);
141
-
142
- await queryRunner.query(`
143
- ALTER TABLE \`yt_goods_unlock\`
144
- ADD CONSTRAINT \`FK_yt_goods_unlock_ytUserId\`
145
- FOREIGN KEY (\`ytUserId\`) REFERENCES \`yt_user\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE
146
- `);
147
-
148
- await queryRunner.query(`
149
- ALTER TABLE \`goods_images_unlock_key\`
150
- ADD CONSTRAINT \`FK_goods_images_unlock_key_goodsId\`
151
- FOREIGN KEY (\`goodsId\`) REFERENCES \`yt_goods\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE
152
- `);
153
- }
154
-
155
- public async down(queryRunner: QueryRunner): Promise<void> {
156
- // 删除外键约束
157
- await queryRunner.query(`ALTER TABLE \`goods_images_unlock_key\` DROP FOREIGN KEY \`FK_goods_images_unlock_key_goodsId\``);
158
- await queryRunner.query(`ALTER TABLE \`yt_goods_unlock\` DROP FOREIGN KEY \`FK_yt_goods_unlock_ytUserId\``);
159
- await queryRunner.query(`ALTER TABLE \`yt_goods_unlock\` DROP FOREIGN KEY \`FK_yt_goods_unlock_goodsId\``);
160
- await queryRunner.query(`ALTER TABLE \`yt_goods\` DROP FOREIGN KEY \`FK_yt_goods_shopId\``);
161
- await queryRunner.query(`ALTER TABLE \`shop_and_user\` DROP FOREIGN KEY \`FK_shop_and_user_userId\``);
162
- await queryRunner.query(`ALTER TABLE \`shop_and_user\` DROP FOREIGN KEY \`FK_shop_and_user_shopId\``);
163
-
164
- // 删除表
165
- await queryRunner.query(`DROP TABLE \`goods_images_unlock_key\``);
166
- await queryRunner.query(`DROP TABLE \`yt_goods_unlock\``);
167
- await queryRunner.query(`DROP TABLE \`yt_goods\``);
168
- await queryRunner.query(`DROP TABLE \`shop_and_user\``);
169
- await queryRunner.query(`DROP TABLE \`shop\``);
170
- await queryRunner.query(`DROP TABLE \`yt_user\``);
171
- }
172
- }
@@ -1,6 +0,0 @@
1
- import { InitialDatabaseStructure1700000000000 } from "./1700000000000-InitialDatabaseStructure";
2
-
3
- /**
4
- * 显式注册迁移类,避免仅靠文件路径扫描导致 webpack 单文件部署下无法发现迁移。
5
- */
6
- export const APP_MIGRATIONS = [InitialDatabaseStructure1700000000000];
@@ -1,124 +0,0 @@
1
- import { Repository, EntityTarget, FindManyOptions, FindOneOptions, UpdateResult, DeleteResult, ObjectLiteral } from 'typeorm';
2
- import { IBaseRepository } from '@src/repository/interfaces/IBaseRepository';
3
- import { logger } from '@src/framework/utils/logger';
4
-
5
- /**
6
- * 基础Repository实现
7
- * 提供通用的数据访问操作
8
- */
9
- export abstract class BaseRepository<T extends ObjectLiteral> implements IBaseRepository<T> {
10
- protected repository: Repository<T>;
11
-
12
- constructor(entity: EntityTarget<T>, repository: Repository<T>) {
13
- this.repository = repository;
14
- }
15
-
16
- async findById(id: number): Promise<T | null> {
17
- try {
18
- return await this.repository.findOneBy({ id } as any);
19
- } catch (error) {
20
- logger.error(`查找实体失败 (ID: ${id}):`, error as Error);
21
- throw error;
22
- }
23
- }
24
-
25
- async findAll(options?: FindManyOptions<T>): Promise<T[]> {
26
- try {
27
- return await this.repository.find(options);
28
- } catch (error) {
29
- logger.error('查找所有实体失败:', error as Error);
30
- throw error;
31
- }
32
- }
33
-
34
- async findOne(options: FindOneOptions<T>): Promise<T | null> {
35
- try {
36
- return await this.repository.findOne(options);
37
- } catch (error) {
38
- logger.error('查找单个实体失败:', error as Error);
39
- throw error;
40
- }
41
- }
42
-
43
- async findMany(options: FindManyOptions<T>): Promise<T[]> {
44
- try {
45
- return await this.repository.find(options);
46
- } catch (error) {
47
- logger.error('查找多个实体失败:', error as Error);
48
- throw error;
49
- }
50
- }
51
-
52
- async save(entity: Partial<T>): Promise<T> {
53
- try {
54
- return await this.repository.save(entity as any);
55
- } catch (error) {
56
- logger.error('保存实体失败:', error as Error);
57
- throw error;
58
- }
59
- }
60
-
61
- async saveMany(entities: Partial<T>[]): Promise<T[]> {
62
- try {
63
- return await this.repository.save(entities as any);
64
- } catch (error) {
65
- logger.error('批量保存实体失败:', error as Error);
66
- throw error;
67
- }
68
- }
69
-
70
- async update(id: number, updateData: Partial<T>): Promise<UpdateResult> {
71
- try {
72
- return await this.repository.update(id, updateData as any);
73
- } catch (error) {
74
- logger.error(`更新实体失败 (ID: ${id}):`, error as Error);
75
- throw error;
76
- }
77
- }
78
-
79
- async delete(id: number): Promise<DeleteResult> {
80
- try {
81
- return await this.repository.delete(id);
82
- } catch (error) {
83
- logger.error(`删除实体失败 (ID: ${id}):`, error as Error);
84
- throw error;
85
- }
86
- }
87
-
88
- async softDelete(id: number): Promise<UpdateResult> {
89
- try {
90
- return await this.repository.softDelete(id);
91
- } catch (error) {
92
- logger.error(`软删除实体失败 (ID: ${id}):`, error as Error);
93
- throw error;
94
- }
95
- }
96
-
97
- async exists(id: number): Promise<boolean> {
98
- try {
99
- const count = await this.repository.count({ where: { id } as any });
100
- return count > 0;
101
- } catch (error) {
102
- logger.error(`检查实体存在性失败 (ID: ${id}):`, error as Error);
103
- throw error;
104
- }
105
- }
106
-
107
- async count(options?: FindManyOptions<T>): Promise<number> {
108
- try {
109
- return await this.repository.count(options);
110
- } catch (error) {
111
- logger.error('统计实体数量失败:', error as Error);
112
- throw error;
113
- }
114
- }
115
-
116
- async findAndCount(options: FindManyOptions<T>): Promise<[T[], number]> {
117
- try {
118
- return await this.repository.findAndCount(options);
119
- } catch (error) {
120
- logger.error('分页查询失败:', error as Error);
121
- throw error;
122
- }
123
- }
124
- }
@@ -1,67 +0,0 @@
1
- import { EntityTarget, FindManyOptions, FindOneOptions, UpdateResult, DeleteResult } from 'typeorm';
2
-
3
- /**
4
- * 基础Repository接口
5
- * 定义通用的数据访问操作
6
- */
7
- export interface IBaseRepository<T> {
8
- /**
9
- * 根据ID查找实体
10
- */
11
- findById(id: number): Promise<T | null>;
12
-
13
- /**
14
- * 查找所有实体
15
- */
16
- findAll(options?: FindManyOptions<T>): Promise<T[]>;
17
-
18
- /**
19
- * 根据条件查找单个实体
20
- */
21
- findOne(options: FindOneOptions<T>): Promise<T | null>;
22
-
23
- /**
24
- * 根据条件查找多个实体
25
- */
26
- findMany(options: FindManyOptions<T>): Promise<T[]>;
27
-
28
- /**
29
- * 保存实体
30
- */
31
- save(entity: Partial<T>): Promise<T>;
32
-
33
- /**
34
- * 批量保存实体
35
- */
36
- saveMany(entities: Partial<T>[]): Promise<T[]>;
37
-
38
- /**
39
- * 更新实体
40
- */
41
- update(id: number, updateData: Partial<T>): Promise<UpdateResult>;
42
-
43
- /**
44
- * 删除实体
45
- */
46
- delete(id: number): Promise<DeleteResult>;
47
-
48
- /**
49
- * 软删除实体
50
- */
51
- softDelete(id: number): Promise<UpdateResult>;
52
-
53
- /**
54
- * 检查实体是否存在
55
- */
56
- exists(id: number): Promise<boolean>;
57
-
58
- /**
59
- * 统计实体数量
60
- */
61
- count(options?: FindManyOptions<T>): Promise<number>;
62
-
63
- /**
64
- * 分页查询
65
- */
66
- findAndCount(options: FindManyOptions<T>): Promise<[T[], number]>;
67
- }
@@ -1,116 +0,0 @@
1
- import { Injectable } from "dp-ioc2";
2
- import { getDataSource } from "@src/framework/utils/db"
3
- import { ObjectLiteral, EntityTarget, Repository } from "typeorm"
4
- import { CommonServiceResultCode, CommonServiceResult } from "@src/framework/types/ServiceResult"
5
-
6
- @Injectable()
7
- export class BaseService {
8
-
9
- /**
10
- * 获取数据仓库
11
- * 延迟初始化,避免在数据库未初始化时出错
12
- */
13
- getDataRepository<T extends ObjectLiteral>(entity: EntityTarget<T>): Repository<T> {
14
- const dbDataSource = getDataSource();
15
- if (!dbDataSource || !dbDataSource.isInitialized) {
16
- throw new Error("数据库未初始化,请等待数据库初始化完成");
17
- }
18
- return dbDataSource.getRepository(entity);
19
- }
20
-
21
- /**
22
- * 创建懒加载的 Repository Getter
23
- * 通用方法,用于实例化自定义 Repository
24
- *
25
- * @template T Repository 类型
26
- * @template R Repository 构造函数类型
27
- * @param entity 实体类型
28
- * @param RepositoryClass Repository 类
29
- * @param cache Map 缓存对象
30
- * @returns Getter 函数
31
- *
32
- * @example
33
- * ```typescript
34
- * export class YtUserService extends BaseService {
35
- * private repositoryCache = new Map<string, any>();
36
- *
37
- * private get userRepository(): IUserRepository {
38
- * return this.createLazyRepository(
39
- * YtUserEntity,
40
- * UserRepository,
41
- * this.repositoryCache
42
- * );
43
- * }
44
- * }
45
- * ```
46
- */
47
- protected createLazyRepository<T extends ObjectLiteral, R>(
48
- entity: EntityTarget<T>,
49
- RepositoryClass: new (repository: Repository<T>) => R,
50
- cache: Map<string, R>
51
- ): R {
52
- // 使用 RepositoryClass 名称作为缓存键
53
- const cacheKey = RepositoryClass.name;
54
-
55
- if (!cache.has(cacheKey)) {
56
- const dataSource = getDataSource();
57
- if (!dataSource || !dataSource.isInitialized) {
58
- throw new Error("数据库未初始化,请等待数据库初始化完成");
59
- }
60
-
61
- const repository = dataSource.getRepository(entity);
62
- const instance = new RepositoryClass(repository);
63
- cache.set(cacheKey, instance);
64
- }
65
-
66
- return cache.get(cacheKey)!;
67
- }
68
-
69
- /**
70
- * 获取数据库管理器
71
- */
72
- getDbManager() {
73
- const dbDataSource = getDataSource();
74
- if (!dbDataSource || !dbDataSource.isInitialized) {
75
- throw new Error("数据库未初始化,请等待数据库初始化完成");
76
- }
77
- return dbDataSource.manager;
78
- }
79
-
80
- async add<T>(data: T): Promise<T> {
81
- return await this.getDbManager().save(data);
82
- // return {
83
- // code: CommonServiceResultCode.SUCCESS,
84
- // data: result,
85
- // }
86
- }
87
-
88
- async getById<T extends ObjectLiteral>(
89
- entity: EntityTarget<T>,
90
- id: number
91
- ): Promise<T | null> {
92
- const repository: Repository<T> = this.getDataRepository(entity);
93
- return await repository.findOneBy({ id } as any);
94
-
95
- // if (!result) {
96
- // return {
97
- // code: CommonServiceResultCode.NOT_FOUND,
98
- // data: null,
99
- // message: "数据不存在"
100
- // };
101
- // }
102
-
103
- // return {
104
- // code: CommonServiceResultCode.SUCCESS,
105
- // data: result
106
- // };
107
- }
108
-
109
- /**
110
- * 清理资源
111
- * 在应用关闭时调用,防止内存泄漏
112
- */
113
- cleanup(): void {
114
- // BaseService 本身不需要清理,子类可以重写此方法
115
- }
116
- }