@nest-omni/core 4.1.3-14 → 4.1.3-17

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 (54) hide show
  1. package/audit/audit.module.js +7 -0
  2. package/audit/services/entity-audit.service.js +2 -1
  3. package/audit/services/manual-audit-log.service.js +2 -2
  4. package/audit/services/multi-database.service.d.ts +0 -5
  5. package/audit/services/multi-database.service.js +0 -24
  6. package/audit/services/transaction-audit.service.js +3 -2
  7. package/cache/dependencies/db.dependency.d.ts +2 -2
  8. package/cache/dependencies/db.dependency.js +4 -4
  9. package/decorators/field.decorators.d.ts +1 -1
  10. package/http-client/examples/proxy-from-environment.example.d.ts +1 -1
  11. package/http-client/examples/proxy-from-environment.example.js +18 -19
  12. package/http-client/services/logging.service.js +2 -3
  13. package/index.d.ts +1 -1
  14. package/index.js +1 -1
  15. package/package.json +3 -2
  16. package/setup/bootstrap.setup.d.ts +1 -1
  17. package/shared/service-registry.module.js +2 -15
  18. package/shared/services/api-config.service.js +1 -0
  19. package/validators/is-exists.validator.d.ts +2 -7
  20. package/validators/is-exists.validator.js +2 -24
  21. package/validators/is-unique.validator.d.ts +2 -7
  22. package/validators/is-unique.validator.js +2 -24
  23. package/transaction/__tests__/mocks.d.ts +0 -9
  24. package/transaction/__tests__/mocks.js +0 -33
  25. package/transaction/base-service-transaction.d.ts +0 -99
  26. package/transaction/base-service-transaction.js +0 -286
  27. package/transaction/cls-compatibility.service.d.ts +0 -55
  28. package/transaction/cls-compatibility.service.js +0 -127
  29. package/transaction/data-source-registry.d.ts +0 -91
  30. package/transaction/data-source-registry.js +0 -349
  31. package/transaction/data-source.util.d.ts +0 -142
  32. package/transaction/data-source.util.js +0 -330
  33. package/transaction/database-adapter.d.ts +0 -44
  34. package/transaction/database-adapter.js +0 -240
  35. package/transaction/decorators/entity-datasource.decorator.d.ts +0 -62
  36. package/transaction/decorators/entity-datasource.decorator.js +0 -105
  37. package/transaction/index.d.ts +0 -15
  38. package/transaction/index.js +0 -68
  39. package/transaction/logging-transactional.interceptor.d.ts +0 -18
  40. package/transaction/logging-transactional.interceptor.js +0 -163
  41. package/transaction/transaction-context.service.d.ts +0 -137
  42. package/transaction/transaction-context.service.js +0 -411
  43. package/transaction/transaction-manager.d.ts +0 -230
  44. package/transaction/transaction-manager.js +0 -1001
  45. package/transaction/transaction-synchronization.d.ts +0 -171
  46. package/transaction/transaction-synchronization.js +0 -380
  47. package/transaction/transaction.errors.d.ts +0 -91
  48. package/transaction/transaction.errors.js +0 -206
  49. package/transaction/transaction.module.d.ts +0 -30
  50. package/transaction/transaction.module.js +0 -98
  51. package/transaction/transactional.decorator.d.ts +0 -82
  52. package/transaction/transactional.decorator.js +0 -319
  53. package/transaction/typeorm-module-wrapper.d.ts +0 -96
  54. package/transaction/typeorm-module-wrapper.js +0 -197
@@ -1,105 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseEntityWithDataSource = exports.ENTITY_DATASOURCE_METADATA_KEY = void 0;
4
- exports.DataSource = DataSource;
5
- exports.getEntityDataSource = getEntityDataSource;
6
- exports.hasEntityDataSource = hasEntityDataSource;
7
- exports.DynamicDataSource = DynamicDataSource;
8
- exports.isDynamicDataSourceEntity = isDynamicDataSourceEntity;
9
- require("reflect-metadata");
10
- /**
11
- * Entity 数据源装饰器
12
- * 用于指定 Entity 应该使用哪个数据源
13
- */
14
- exports.ENTITY_DATASOURCE_METADATA_KEY = 'entity:datasource';
15
- /**
16
- * 数据源装饰器 - 为 Entity 指定数据源
17
- *
18
- * @param dataSourceName 数据源名称
19
- *
20
- * 使用示例:
21
- * ```typescript
22
- * @Entity('users')
23
- * @DataSource('user_db')
24
- * export class User {
25
- * @PrimaryGeneratedColumn()
26
- * id: number;
27
- *
28
- * @Column()
29
- * name: string;
30
- * }
31
- * ```
32
- */
33
- function DataSource(dataSourceName) {
34
- return function (target) {
35
- // 使用 Reflect.metadata 存储数据源信息
36
- Reflect.defineMetadata(exports.ENTITY_DATASOURCE_METADATA_KEY, dataSourceName, target);
37
- // 同时在原型上设置属性,方便运行时访问
38
- target.prototype._dataSourceName = dataSourceName;
39
- // 静态属性,方便类级别访问
40
- target._dataSourceName = dataSourceName;
41
- // 如果类有 metadata 属性(一些 ORM 框架支持),也设置在那里
42
- if (target.metadata) {
43
- target.metadata.dataSource = dataSourceName;
44
- }
45
- };
46
- }
47
- /**
48
- * 获取 Entity 的数据源名称
49
- * @param entityClass Entity 类或构造函数
50
- * @returns 数据源名称,如果未指定则返回 null
51
- */
52
- function getEntityDataSource(entityClass) {
53
- if (!entityClass)
54
- return null;
55
- // 尝试从多个位置获取数据源名称
56
- // 1. 从 Reflect.metadata 获取
57
- const metadataSource = Reflect.getMetadata(exports.ENTITY_DATASOURCE_METADATA_KEY, entityClass);
58
- if (metadataSource)
59
- return metadataSource;
60
- // 2. 从静态属性获取
61
- if (entityClass._dataSourceName)
62
- return entityClass._dataSourceName;
63
- // 3. 从原型获取
64
- if (entityClass.prototype && entityClass.prototype._dataSourceName) {
65
- return entityClass.prototype._dataSourceName;
66
- }
67
- // 4. 从实例获取(如果传入的是实例)
68
- if (entityClass.constructor && entityClass.constructor._dataSourceName) {
69
- return entityClass.constructor._dataSourceName;
70
- }
71
- return null;
72
- }
73
- /**
74
- * 检查 Entity 是否指定了数据源
75
- * @param entityClass Entity 类或构造函数
76
- * @returns 是否指定了数据源
77
- */
78
- function hasEntityDataSource(entityClass) {
79
- return getEntityDataSource(entityClass) !== null;
80
- }
81
- /**
82
- * 带数据源的 Entity 基类
83
- * 继承这个基类的 Entity 可以通过实现 useDataSource 方法动态指定数据源
84
- */
85
- class BaseEntityWithDataSource {
86
- }
87
- exports.BaseEntityWithDataSource = BaseEntityWithDataSource;
88
- /**
89
- * 动态数据源装饰器
90
- * 标记 Entity 使用动态数据源(通过 useDataSource 方法指定)
91
- */
92
- function DynamicDataSource() {
93
- return function (target) {
94
- // 设置标记,表示使用动态数据源
95
- Reflect.defineMetadata('entity:dynamic-datasource', true, target);
96
- target._useDynamicDataSource = true;
97
- };
98
- }
99
- /**
100
- * 检查 Entity 是否使用动态数据源
101
- */
102
- function isDynamicDataSourceEntity(entityClass) {
103
- return Reflect.getMetadata('entity:dynamic-datasource', entityClass) === true ||
104
- entityClass._useDynamicDataSource === true;
105
- }
@@ -1,15 +0,0 @@
1
- export { TransactionManager, TransactionDefinition, TransactionStatus, Propagation, IsolationLevel, TransactionTimeoutCallback, TransactionContextManager } from './transaction-manager';
2
- export { TransactionSynchronizationManager, TransactionSynchronization, TransactionSynchronizationStatus, } from './transaction-synchronization';
3
- export { Transactional, ClassTransactional, TransactionalInterceptor, Tx, UseTransactional, TransactionalOptions } from './transactional.decorator';
4
- export { BaseService } from './base-service-transaction';
5
- export { TypeOrmModuleWrapper, TypeOrmDataSourceConfig, MultiTypeOrmModuleOptions, GlobalMultiTypeOrmModule } from './typeorm-module-wrapper';
6
- export { DataSourceRegistryService, DataSourceRegistryConfig, DataSourceHealthStatus } from './data-source-registry';
7
- export { TransactionContextService, DynamicDataSourceConfig } from './transaction-context.service';
8
- export { ClsCompatibilityService, ClsServiceManager } from './cls-compatibility.service';
9
- export { DataSource, DynamicDataSource, BaseEntityWithDataSource, getEntityDataSource, hasEntityDataSource, isDynamicDataSourceEntity } from './decorators/entity-datasource.decorator';
10
- export { LoggingTransactionalInterceptor } from './logging-transactional.interceptor';
11
- export { LoggingTransactionalInterceptor as TRANSACTION_LOGGING_INTERCEPTOR } from './logging-transactional.interceptor';
12
- export { TransactionError, TransactionErrorHandler } from './transaction.errors';
13
- export { DatabaseAdapter, DatabaseType } from './database-adapter';
14
- export { DataSourceUtil, getDataSource, getDataSourceSafe, getDefaultDataSource, isDataSourceAvailable, withDataSource, withTransaction, addDataSource, addDataSources, } from './data-source.util';
15
- export { TransactionModule } from './transaction.module';
@@ -1,68 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TransactionModule = exports.addDataSources = exports.addDataSource = exports.withTransaction = exports.withDataSource = exports.isDataSourceAvailable = exports.getDefaultDataSource = exports.getDataSourceSafe = exports.getDataSource = exports.DataSourceUtil = exports.DatabaseAdapter = exports.TransactionErrorHandler = exports.TransactionError = exports.TRANSACTION_LOGGING_INTERCEPTOR = exports.LoggingTransactionalInterceptor = exports.isDynamicDataSourceEntity = exports.hasEntityDataSource = exports.getEntityDataSource = exports.BaseEntityWithDataSource = exports.DynamicDataSource = exports.DataSource = exports.ClsServiceManager = exports.ClsCompatibilityService = exports.TransactionContextService = exports.DataSourceRegistryService = exports.GlobalMultiTypeOrmModule = exports.TypeOrmModuleWrapper = exports.BaseService = exports.UseTransactional = exports.Tx = exports.TransactionalInterceptor = exports.ClassTransactional = exports.Transactional = exports.TransactionSynchronizationStatus = exports.TransactionSynchronizationManager = exports.TransactionContextManager = exports.IsolationLevel = exports.Propagation = exports.TransactionManager = void 0;
4
- // 核心事务管理
5
- var transaction_manager_1 = require("./transaction-manager");
6
- Object.defineProperty(exports, "TransactionManager", { enumerable: true, get: function () { return transaction_manager_1.TransactionManager; } });
7
- Object.defineProperty(exports, "Propagation", { enumerable: true, get: function () { return transaction_manager_1.Propagation; } });
8
- Object.defineProperty(exports, "IsolationLevel", { enumerable: true, get: function () { return transaction_manager_1.IsolationLevel; } });
9
- Object.defineProperty(exports, "TransactionContextManager", { enumerable: true, get: function () { return transaction_manager_1.TransactionContextManager; } });
10
- // 事务同步机制(对标 Spring TransactionSynchronization)
11
- var transaction_synchronization_1 = require("./transaction-synchronization");
12
- Object.defineProperty(exports, "TransactionSynchronizationManager", { enumerable: true, get: function () { return transaction_synchronization_1.TransactionSynchronizationManager; } });
13
- Object.defineProperty(exports, "TransactionSynchronizationStatus", { enumerable: true, get: function () { return transaction_synchronization_1.TransactionSynchronizationStatus; } });
14
- // 装饰器
15
- var transactional_decorator_1 = require("./transactional.decorator");
16
- Object.defineProperty(exports, "Transactional", { enumerable: true, get: function () { return transactional_decorator_1.Transactional; } });
17
- Object.defineProperty(exports, "ClassTransactional", { enumerable: true, get: function () { return transactional_decorator_1.ClassTransactional; } });
18
- Object.defineProperty(exports, "TransactionalInterceptor", { enumerable: true, get: function () { return transactional_decorator_1.TransactionalInterceptor; } });
19
- Object.defineProperty(exports, "Tx", { enumerable: true, get: function () { return transactional_decorator_1.Tx; } });
20
- Object.defineProperty(exports, "UseTransactional", { enumerable: true, get: function () { return transactional_decorator_1.UseTransactional; } });
21
- var base_service_transaction_1 = require("./base-service-transaction");
22
- Object.defineProperty(exports, "BaseService", { enumerable: true, get: function () { return base_service_transaction_1.BaseService; } });
23
- // 数据源管理
24
- var typeorm_module_wrapper_1 = require("./typeorm-module-wrapper");
25
- Object.defineProperty(exports, "TypeOrmModuleWrapper", { enumerable: true, get: function () { return typeorm_module_wrapper_1.TypeOrmModuleWrapper; } });
26
- Object.defineProperty(exports, "GlobalMultiTypeOrmModule", { enumerable: true, get: function () { return typeorm_module_wrapper_1.GlobalMultiTypeOrmModule; } });
27
- var data_source_registry_1 = require("./data-source-registry");
28
- Object.defineProperty(exports, "DataSourceRegistryService", { enumerable: true, get: function () { return data_source_registry_1.DataSourceRegistryService; } });
29
- var transaction_context_service_1 = require("./transaction-context.service");
30
- Object.defineProperty(exports, "TransactionContextService", { enumerable: true, get: function () { return transaction_context_service_1.TransactionContextService; } });
31
- // 兼容性支持
32
- var cls_compatibility_service_1 = require("./cls-compatibility.service");
33
- Object.defineProperty(exports, "ClsCompatibilityService", { enumerable: true, get: function () { return cls_compatibility_service_1.ClsCompatibilityService; } });
34
- Object.defineProperty(exports, "ClsServiceManager", { enumerable: true, get: function () { return cls_compatibility_service_1.ClsServiceManager; } });
35
- // Entity 级别的数据源装饰器
36
- var entity_datasource_decorator_1 = require("./decorators/entity-datasource.decorator");
37
- Object.defineProperty(exports, "DataSource", { enumerable: true, get: function () { return entity_datasource_decorator_1.DataSource; } });
38
- Object.defineProperty(exports, "DynamicDataSource", { enumerable: true, get: function () { return entity_datasource_decorator_1.DynamicDataSource; } });
39
- Object.defineProperty(exports, "BaseEntityWithDataSource", { enumerable: true, get: function () { return entity_datasource_decorator_1.BaseEntityWithDataSource; } });
40
- Object.defineProperty(exports, "getEntityDataSource", { enumerable: true, get: function () { return entity_datasource_decorator_1.getEntityDataSource; } });
41
- Object.defineProperty(exports, "hasEntityDataSource", { enumerable: true, get: function () { return entity_datasource_decorator_1.hasEntityDataSource; } });
42
- Object.defineProperty(exports, "isDynamicDataSourceEntity", { enumerable: true, get: function () { return entity_datasource_decorator_1.isDynamicDataSourceEntity; } });
43
- // 日志增强
44
- var logging_transactional_interceptor_1 = require("./logging-transactional.interceptor");
45
- Object.defineProperty(exports, "LoggingTransactionalInterceptor", { enumerable: true, get: function () { return logging_transactional_interceptor_1.LoggingTransactionalInterceptor; } });
46
- var logging_transactional_interceptor_2 = require("./logging-transactional.interceptor");
47
- Object.defineProperty(exports, "TRANSACTION_LOGGING_INTERCEPTOR", { enumerable: true, get: function () { return logging_transactional_interceptor_2.LoggingTransactionalInterceptor; } });
48
- // 错误处理
49
- var transaction_errors_1 = require("./transaction.errors");
50
- Object.defineProperty(exports, "TransactionError", { enumerable: true, get: function () { return transaction_errors_1.TransactionError; } });
51
- Object.defineProperty(exports, "TransactionErrorHandler", { enumerable: true, get: function () { return transaction_errors_1.TransactionErrorHandler; } });
52
- // 数据库适配器
53
- var database_adapter_1 = require("./database-adapter");
54
- Object.defineProperty(exports, "DatabaseAdapter", { enumerable: true, get: function () { return database_adapter_1.DatabaseAdapter; } });
55
- // 数据源工具(可在任意位置获取数据源)
56
- var data_source_util_1 = require("./data-source.util");
57
- Object.defineProperty(exports, "DataSourceUtil", { enumerable: true, get: function () { return data_source_util_1.DataSourceUtil; } });
58
- Object.defineProperty(exports, "getDataSource", { enumerable: true, get: function () { return data_source_util_1.getDataSource; } });
59
- Object.defineProperty(exports, "getDataSourceSafe", { enumerable: true, get: function () { return data_source_util_1.getDataSourceSafe; } });
60
- Object.defineProperty(exports, "getDefaultDataSource", { enumerable: true, get: function () { return data_source_util_1.getDefaultDataSource; } });
61
- Object.defineProperty(exports, "isDataSourceAvailable", { enumerable: true, get: function () { return data_source_util_1.isDataSourceAvailable; } });
62
- Object.defineProperty(exports, "withDataSource", { enumerable: true, get: function () { return data_source_util_1.withDataSource; } });
63
- Object.defineProperty(exports, "withTransaction", { enumerable: true, get: function () { return data_source_util_1.withTransaction; } });
64
- Object.defineProperty(exports, "addDataSource", { enumerable: true, get: function () { return data_source_util_1.addDataSource; } });
65
- Object.defineProperty(exports, "addDataSources", { enumerable: true, get: function () { return data_source_util_1.addDataSources; } });
66
- // 模块导出
67
- var transaction_module_1 = require("./transaction.module");
68
- Object.defineProperty(exports, "TransactionModule", { enumerable: true, get: function () { return transaction_module_1.TransactionModule; } });
@@ -1,18 +0,0 @@
1
- import { ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';
2
- import { Observable } from 'rxjs';
3
- import { TransactionManager } from './transaction-manager';
4
- /**
5
- * 带日志的事务拦截器
6
- * 提供详细的事务执行日志
7
- */
8
- export declare class LoggingTransactionalInterceptor implements NestInterceptor {
9
- private readonly transactionManager;
10
- private readonly logger;
11
- constructor(transactionManager: TransactionManager);
12
- intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
13
- private handleTransaction;
14
- private getTransactionOptions;
15
- private getTransactionName;
16
- private setClsContext;
17
- private clearClsContext;
18
- }
@@ -1,163 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
- return new (P || (P = Promise))(function (resolve, reject) {
14
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
- step((generator = generator.apply(thisArg, _arguments || [])).next());
18
- });
19
- };
20
- var LoggingTransactionalInterceptor_1;
21
- Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.LoggingTransactionalInterceptor = void 0;
23
- const common_1 = require("@nestjs/common");
24
- const rxjs_1 = require("rxjs");
25
- const transaction_manager_1 = require("./transaction-manager");
26
- const nestjs_cls_1 = require("nestjs-cls");
27
- /**
28
- * 带日志的事务拦截器
29
- * 提供详细的事务执行日志
30
- */
31
- let LoggingTransactionalInterceptor = LoggingTransactionalInterceptor_1 = class LoggingTransactionalInterceptor {
32
- constructor(transactionManager) {
33
- this.transactionManager = transactionManager;
34
- this.logger = new common_1.Logger(LoggingTransactionalInterceptor_1.name);
35
- }
36
- intercept(context, next) {
37
- // 检查是否有事务元数据
38
- const options = this.getTransactionOptions(context);
39
- if (!options) {
40
- return next.handle();
41
- }
42
- // 异步执行事务处理
43
- return (0, rxjs_1.from)(this.handleTransaction(context, next, options));
44
- }
45
- handleTransaction(context, next, options) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- const startTime = Date.now();
48
- let status;
49
- try {
50
- // 获取事务定义
51
- const definition = {
52
- propagation: options.propagation || transaction_manager_1.Propagation.REQUIRED,
53
- isolationLevel: options.isolation,
54
- readOnly: options.readOnly || false,
55
- timeout: options.timeout || 30,
56
- name: this.getTransactionName(context, options),
57
- dataSourceName: options.dataSource || 'default',
58
- };
59
- // 记录事务开始
60
- this.logger.log(`Starting transaction: ${definition.name} ` +
61
- `(propagation: ${transaction_manager_1.Propagation[definition.propagation]}, ` +
62
- `dataSource: ${definition.dataSourceName}, ` +
63
- `timeout: ${definition.timeout}s)`);
64
- // 获取事务
65
- status = yield this.transactionManager.getTransaction(definition);
66
- // 记录事务状态
67
- if (status.isNewTransaction) {
68
- this.logger.debug(`New transaction created on ${definition.dataSourceName}`);
69
- }
70
- else {
71
- this.logger.debug(`Joined existing transaction on ${definition.dataSourceName} ` +
72
- `(level: ${status.nestingLevel})`);
73
- }
74
- // 设置 CLS 上下文
75
- yield this.setClsContext(status);
76
- // 执行方法
77
- const result = yield next.handle().toPromise();
78
- // 记录成功
79
- const duration = Date.now() - startTime;
80
- this.logger.log(`Transaction ${definition.name} completed successfully ` +
81
- `in ${duration}ms`);
82
- // 提交事务
83
- yield this.transactionManager.commit(status);
84
- this.logger.debug(`Transaction ${definition.name} committed`);
85
- return result;
86
- }
87
- catch (error) {
88
- // 记录错误
89
- const duration = Date.now() - startTime;
90
- this.logger.error(`Transaction failed: ${error.message} ` +
91
- `(duration: ${duration}ms)`, error.stack);
92
- // 回滚事务
93
- if (status) {
94
- try {
95
- yield this.transactionManager.rollback(status);
96
- this.logger.debug(`Transaction rolled back successfully`);
97
- }
98
- catch (rollbackError) {
99
- this.logger.error(`Failed to rollback transaction: ${rollbackError.message}`, rollbackError.stack);
100
- }
101
- }
102
- throw error;
103
- }
104
- finally {
105
- // 清理 CLS 上下文
106
- this.clearClsContext();
107
- }
108
- });
109
- }
110
- getTransactionOptions(context) {
111
- const handler = context.getHandler();
112
- const controller = context.getClass();
113
- // 检查方法级注解
114
- const methodOptions = Reflect.getMetadata('transactional', handler);
115
- if (methodOptions && !methodOptions.isClassLevel) {
116
- return methodOptions;
117
- }
118
- // 检查类级注解
119
- const classOptions = Reflect.getMetadata('transactional', controller);
120
- if (classOptions && (classOptions.isClassLevel || !methodOptions)) {
121
- return classOptions;
122
- }
123
- return null;
124
- }
125
- getTransactionName(context, options) {
126
- if (options.name) {
127
- return options.name;
128
- }
129
- const handler = context.getHandler();
130
- const controller = context.getClass();
131
- return `${controller.name}.${handler.name}`;
132
- }
133
- setClsContext(status) {
134
- return __awaiter(this, void 0, void 0, function* () {
135
- var _a;
136
- const clsService = (_a = nestjs_cls_1.ClsServiceManager.getClsService) === null || _a === void 0 ? void 0 : _a.call(nestjs_cls_1.ClsServiceManager);
137
- if (clsService) {
138
- const em = this.transactionManager.getCurrentEntityManager(status.dataSourceName);
139
- if (em) {
140
- clsService.set('entityManager', em);
141
- }
142
- clsService.set('transactionId', `${status.dataSourceName}_${Date.now()}`);
143
- clsService.set('dataSource', status.dataSourceName);
144
- clsService.set('startTime', status.startTime);
145
- }
146
- });
147
- }
148
- clearClsContext() {
149
- var _a;
150
- const clsService = (_a = nestjs_cls_1.ClsServiceManager.getClsService) === null || _a === void 0 ? void 0 : _a.call(nestjs_cls_1.ClsServiceManager);
151
- if (clsService) {
152
- clsService.set('entityManager', null);
153
- clsService.set('transactionId', null);
154
- clsService.set('dataSource', null);
155
- clsService.set('startTime', null);
156
- }
157
- }
158
- };
159
- exports.LoggingTransactionalInterceptor = LoggingTransactionalInterceptor;
160
- exports.LoggingTransactionalInterceptor = LoggingTransactionalInterceptor = LoggingTransactionalInterceptor_1 = __decorate([
161
- (0, common_1.Injectable)(),
162
- __metadata("design:paramtypes", [transaction_manager_1.TransactionManager])
163
- ], LoggingTransactionalInterceptor);
@@ -1,137 +0,0 @@
1
- import { OnModuleInit } from '@nestjs/common';
2
- import { DataSource, EntityManager, DataSourceOptions } from 'typeorm';
3
- import { ModuleRef } from '@nestjs/core';
4
- /**
5
- * 事务上下文信息
6
- */
7
- interface TransactionContext {
8
- dataSourceName: string;
9
- entityManager: EntityManager;
10
- dataSource: DataSource;
11
- }
12
- /**
13
- * 动态注册的数据源配置
14
- */
15
- export interface DynamicDataSourceConfig {
16
- name: string;
17
- dataSource: DataSource;
18
- options?: DataSourceOptions;
19
- metadata?: Record<string, any>;
20
- createdAt: Date;
21
- }
22
- /**
23
- * 事务上下文管理器
24
- * 使用 RequestScope 确保每个请求都有独立的事务上下文
25
- */
26
- export declare class TransactionContextService implements OnModuleInit {
27
- private readonly moduleRef;
28
- private readonly config?;
29
- private static readonly logger;
30
- private readonly contextMap;
31
- constructor(moduleRef: ModuleRef, config?: {
32
- defaultDataSource?: string;
33
- enableDynamicRegistration?: boolean;
34
- logDataSourceRegistration?: boolean;
35
- });
36
- onModuleInit(): Promise<void>;
37
- /**
38
- * 获取当前请求的事务上下文服务
39
- */
40
- static getCurrent(): TransactionContextService | undefined;
41
- /**
42
- * 获取当前请求的数据源
43
- * 方便其他模块快速访问数据源
44
- * @param dataSourceName 数据源名称,默认为 'default'
45
- * @returns DataSource 实例
46
- */
47
- static getDataSource(dataSourceName?: string): DataSource;
48
- /**
49
- * 设置事务上下文
50
- */
51
- setContext(dataSourceName: string, entityManager: EntityManager): void;
52
- /**
53
- * 获取事务上下文中的 EntityManager
54
- */
55
- getEntityManager(dataSourceName?: string): EntityManager | null;
56
- /**
57
- * 获取事务上下文中的 DataSource
58
- * 如果上下文中没有,则尝试从 TypeORM 模块或全局注册表获取
59
- */
60
- getDataSource(dataSourceName?: string): DataSource | null;
61
- /**
62
- * 检查是否在事务中
63
- */
64
- isInTransaction(dataSourceName?: string): boolean;
65
- /**
66
- * 获取所有活跃的事务上下文
67
- */
68
- getAllActiveContexts(): Map<string, TransactionContext>;
69
- /**
70
- * 清理所有事务上下文
71
- */
72
- clearContext(): void;
73
- /**
74
- * 清理指定数据源的事务上下文
75
- */
76
- clearContextForDataSource(dataSourceName: string): void;
77
- /**
78
- * 执行带事务的操作
79
- * 如果已在事务中,使用现有的事务管理器
80
- * 否则创建新事务
81
- */
82
- executeInTransaction<T>(dataSourceName: string, operation: (entityManager: EntityManager) => Promise<T>, isolationLevel?: any): Promise<T>;
83
- /**
84
- * 获取 DataSource 实例
85
- */
86
- private getDataSourceInstance;
87
- /**
88
- * 动态注册数据源
89
- */
90
- static addDataSource(name: string, dataSource: DataSource, options?: {
91
- options?: DataSourceOptions;
92
- metadata?: Record<string, any>;
93
- replaceExisting?: boolean;
94
- }): Promise<void>;
95
- /**
96
- * 移除动态注册的数据源
97
- */
98
- static removeDataSource(name: string): Promise<void>;
99
- /**
100
- * 获取所有已注册的数据源名称
101
- */
102
- static getRegisteredDataSources(): string[];
103
- /**
104
- * 获取动态数据源的配置
105
- */
106
- static getDataSourceConfig(name: string): DynamicDataSourceConfig | undefined;
107
- /**
108
- * 检查数据源是否已注册
109
- */
110
- static isDataSourceRegistered(name: string): boolean;
111
- /**
112
- * 批量注册数据源
113
- */
114
- static addDataSources(dataSources: Array<{
115
- name: string;
116
- dataSource: DataSource;
117
- options?: DataSourceOptions;
118
- metadata?: Record<string, any>;
119
- }>, options?: {
120
- replaceExisting?: boolean;
121
- continueOnError?: boolean;
122
- }): Promise<void>;
123
- /**
124
- * 清理全局注册表(用于测试)
125
- */
126
- static clearGlobalRegistry(): void;
127
- /**
128
- * 获取默认数据源名称
129
- */
130
- getDefaultDataSourceName(): string;
131
- /**
132
- * 跨多个数据源执行分布式事务
133
- * 使用两阶段提交模式
134
- */
135
- executeDistributedTransaction<T>(dataSourceNames: string[], operation: (entityManagers: Map<string, EntityManager>) => Promise<T>): Promise<T>;
136
- }
137
- export {};