@duraxis/nestjs 0.1.1 → 0.2.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # @duraxis/nestjs changelog
2
2
 
3
+ ## 0.2.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 8c357b5: fix: padronize the published versions
8
+ - 8c357b5: adjust the release version
9
+ - 8c357b5: fix: padronize the published versions
10
+ - Updated dependencies [8c357b5]
11
+ - Updated dependencies [8c357b5]
12
+ - @duraxis/core@0.2.2
13
+ - @duraxis/orm@0.2.2
14
+ - @duraxis/storage@0.1.2
15
+
16
+ ## 0.2.3
17
+
18
+ ### Patch Changes
19
+
20
+ - e6facc7: fix: padronize the published versions
21
+ - e6facc7: adjust the release version
22
+ - Updated dependencies [e6facc7]
23
+ - @duraxis/core@0.2.1
24
+ - @duraxis/orm@0.2.1
25
+ - @duraxis/storage@0.1.1
26
+
27
+ ## 0.2.2
28
+
29
+ ### Patch Changes
30
+
31
+ - c8d2a63: adjust the release version
32
+
33
+ ## 0.2.1
34
+
35
+ ### Patch Changes
36
+
37
+ - 5b88773: adjust the release version
38
+
39
+ ## 0.2.0
40
+
41
+ ### Minor Changes
42
+
43
+ - 6123078: Add transactional foreign-key integrity, referential actions, ORM relationship decorators, batched relation loading, and ManyToMany association operations.
44
+
45
+ ### Patch Changes
46
+
47
+ - Updated dependencies [6123078]
48
+ - @duraxis/core@0.2.0
49
+ - @duraxis/orm@0.2.0
50
+
51
+ ## 0.1.2
52
+
53
+ ### Patch Changes
54
+
55
+ - a447bb5: Activate declarative transactions automatically for standard Nest class providers using application-scoped property injection. Preserve provider identity and support singleton, transient and request scopes, lifecycle calls after injection, inherited metadata and self-invocation. Deprecate the transactional registration helpers while retaining their named-connection defaults for migration. Self-invocation now honors inner transaction boundaries; constructor-time transactions remain unsupported and are documented explicitly.
56
+
3
57
  ## 0.1.1
4
58
 
5
59
  ### Patch Changes
package/README.md CHANGED
@@ -50,8 +50,9 @@ class UserService {
50
50
  entities: [User],
51
51
  schema: { mode: "create" },
52
52
  }),
53
- DuraxisModule.forTransactionalFeature([User], [UserService]),
53
+ DuraxisModule.forFeature([User]),
54
54
  ],
55
+ providers: [UserService],
55
56
  })
56
57
  export class AppModule {}
57
58
  ```
@@ -74,8 +75,8 @@ DuraxisModule.forRootAsync({
74
75
  });
75
76
  ```
76
77
 
77
- Com `autoLoadEntities: true`, entidades declaradas por `forFeature` ou
78
- `forTransactionalFeature` para a mesma conexão são agregadas durante a inicialização. Sem essa
78
+ Com `autoLoadEntities: true`, entidades declaradas por `forFeature` para a mesma conexão são
79
+ agregadas durante a inicialização. Sem essa
79
80
  opção, elas também devem constar em `entities` no root.
80
81
 
81
82
  ## Injeção e transações
@@ -83,13 +84,63 @@ opção, elas também devem constar em `entities` no root.
83
84
  As APIs públicas incluem `InjectDuraxisRepository`, `InjectDuraxisOrm`,
84
85
  `InjectDuraxisDatabase`, `InjectDuraxisTransactionManager` e seus geradores de token.
85
86
 
86
- `@Transactional()` é aplicado por proxy: registre o provider com
87
- `forTransactionalFeature(entities, providers)` ou
88
- `forTransactionalProviders(providers)`. Métodos transacionais devem retornar `Promise`. A API
87
+ `@Transactional()` funciona automaticamente em classes registradas no array `providers` de
88
+ `@Module()`. Use apenas `forFeature([Entity])` para disponibilizar os repositórios; nenhum registro
89
+ transacional adicional é necessário. A instância criada pelo Nest mantém sua identidade e injeção
90
+ de dependências. Chamadas por controllers, outros serviços e `this.metodo()` passam pelo mesmo
91
+ limite transacional, inclusive em providers singleton, transient e request-scoped.
92
+
93
+ O decorator também pode ser aplicado à classe. Metadados de classe são herdados e as opções do
94
+ método prevalecem sobre as da classe. Métodos herdados preservam seus decorators; ao substituir
95
+ um método com decorator de método em uma subclasse, reaplique o decorator na nova implementação.
96
+ Métodos transacionais devem retornar `Promise`. A API
89
97
  implementa propagação `REQUIRED`, `REQUIRES_NEW`, `SUPPORTS`, `MANDATORY`, `NOT_SUPPORTED` e
90
98
  `NEVER`; `NESTED`, timeout e níveis além de `DEFAULT`/`SNAPSHOT` são rejeitados. `readOnly`,
91
99
  `rollbackFor` e `noRollbackFor` também estão disponíveis.
92
100
 
101
+ Para conexões nomeadas, declare `@Transactional({ connectionName: "primary" })` no método ou na
102
+ classe e use o mesmo nome na injeção do repositório. Sem essa opção, a conexão é `default`;
103
+ `forFeature([Entity], "primary")` não altera a conexão padrão do decorator.
104
+
105
+ Uma exceção que sai de um limite `REQUIRED` participante marca a transação compartilhada como
106
+ rollback-only, salvo exclusão pelas regras de rollback. Capturá-la no chamador não remove essa
107
+ marca. Uma exceção capturada inteiramente dentro de um único método não chega ao gerenciador.
108
+ `noRollbackFor` permite commit somente para erros correspondentes e nunca anula rollback-only.
109
+
110
+ ### Inicialização e limites
111
+
112
+ A ligação com o gerenciador usa injeção de propriedade do Nest antes dos hooks de inicialização.
113
+ Chamadas a métodos transacionais em `onModuleInit` e `onApplicationBootstrap` são suportadas,
114
+ inclusive antes de `app.init()` quando o provider já terminou a injeção. Hooks não são incluídos
115
+ implicitamente pelo decorator de classe; podem receber `@Transactional()` explicitamente.
116
+
117
+ Não execute trabalho transacional em construtores ou inicializadores de campos. Antes da injeção,
118
+ métodos já decorados lançam `TransactionalProviderNotReadyError`; novos métodos/overrides de uma
119
+ subclasse com apenas metadados de classe herdados e funções de instância só recebem wrappers
120
+ ao terminar a construção. Essas chamadas durante a construção podem escapar da interceptação.
121
+ Não há promessa de interceptação completa durante a construção, nem garantia de disponibilidade
122
+ do gerenciador em factories de inicialização ou construtores de outros providers.
123
+
124
+ Use providers de classe (`providers: [Service]` ou `useClass`). Instâncias criadas manualmente,
125
+ `useValue` e resultados de `useFactory` não recebem injeção de propriedades do Nest; métodos
126
+ decorados falham explicitamente quando invocados sem essa ligação. Nessas instâncias, novos
127
+ métodos/overrides de subclasses com apenas metadados de classe herdados e funções de instância
128
+ permanecem sem wrappers e podem escapar da interceptação. Getters, setters, métodos
129
+ estáticos e substituição de métodos após a injeção não são suportados. Ao desligar, o gerenciador
130
+ aguarda transações em andamento e rejeita novas transações; depois de remover a conexão, chamadas
131
+ decoradas falham com `TransactionManagerNotFoundError`.
132
+
133
+ ### Migração
134
+
135
+ `forTransactionalFeature(entities, providers, connectionName)` e
136
+ `forTransactionalProviders(providers, connectionName)` estão depreciados e continuam disponíveis
137
+ para migração. Troque-os por `forFeature(entities, connectionName)` e mova os serviços para
138
+ `providers` do módulo consumidor. Para conexões nomeadas, explicite `connectionName` no decorator.
139
+ A remoção dos métodos antigos fica para uma versão incompatível futura. Chamadas por `this` agora
140
+ aplicam as opções transacionais do método interno, inclusive propagação e regras de rollback.
141
+
142
+ Veja a [decisão de arquitetura](../../docs/NESTJS_TRANSACTIONS.md) para a análise do ciclo de vida.
143
+
93
144
  Transações declarativas dependem de metadados e inicialização do Nest; o pacote não é marcado
94
145
  como livre de efeitos colaterais. Ele não adiciona coordenação distribuída. Requer Node.js
95
146
  22.12+.
@@ -9,9 +9,6 @@ export interface DuraxisModuleOptions {
9
9
  readonly autoLoadEntities?: boolean;
10
10
  readonly database?: Omit<DuraxisDatabaseOptions, "storage">;
11
11
  readonly schema?: DuraxisOrmOptions["schema"];
12
- /**
13
- * Defaults to true for a driver factory and false for a supplied driver instance.
14
- */
15
12
  readonly closeStorage?: boolean;
16
13
  }
17
14
  export interface DuraxisRootModuleOptions extends DuraxisModuleOptions {
@@ -5,6 +5,8 @@ export declare class DuraxisModule {
5
5
  static forRoot(options: DuraxisRootModuleOptions): DynamicModule;
6
6
  static forRootAsync<TArguments extends readonly unknown[]>(options: DuraxisModuleAsyncOptions<TArguments>): DynamicModule;
7
7
  static forFeature(entities: readonly EntityClass[], connectionName?: string): DynamicModule;
8
+ /** @deprecated Use forFeature(entities, connectionName) and regular module providers. */
8
9
  static forTransactionalFeature(entities: readonly EntityClass[], providers: readonly Type<object>[], connectionName?: string): DynamicModule;
10
+ /** @deprecated Declare services in the consuming module's providers array. */
9
11
  static forTransactionalProviders(providers: readonly Type<object>[], connectionName?: string): DynamicModule;
10
12
  }
package/dist/index.cjs CHANGED
@@ -163,6 +163,11 @@ var TransactionContextManager = class {
163
163
  }
164
164
  };
165
165
  // src/transactions/transaction.errors.ts
166
+ var TransactionalProviderNotReadyError = class extends DuraxisNestError {
167
+ constructor(methodName) {
168
+ super(`Transactional provider ${methodName} is not ready: Nest must complete property injection before invocation. Constructor calls, manual construction, useValue and useFactory instances are unsupported`);
169
+ }
170
+ };
166
171
  var TransactionRequiredError = class extends DuraxisNestError {
167
172
  constructor(connectionName) {
168
173
  super(`An active Duraxis transaction is required for connection ${connectionName}`);
@@ -368,8 +373,25 @@ function transactionAwareBuilder(entity, baseRepository, transactions, captured,
368
373
  } });
369
374
  }
370
375
  function createTransactionAwareRepository(entity, baseRepository, transactions) {
371
- return new Proxy(baseRepository, { get(target, property) {
376
+ return new Proxy(baseRepository, { get(_, property) {
372
377
  if (property == "createQueryBuilder") return () => transactionAwareBuilder(entity, baseRepository, transactions, transactions.currentContext());
378
+ if (property == "relations") return (...arguments_) => {
379
+ const captured = transactions.currentContext();
380
+ return new Proxy(Object.create(null), { get(_target, operation) {
381
+ return (...operationArguments) => {
382
+ transactions.assertCapturedContext(captured);
383
+ if (operation == "add" || operation == "remove") transactions.assertWriteAllowed(`relations.${String(operation)}`);
384
+ const current = transactions.resolveRepository(entity, baseRepository);
385
+ const relationMethod = Reflect.get(current, property, current);
386
+ if (typeof relationMethod != "function") throw new TypeError("Invalid Repository relation method");
387
+ const operations = Reflect.apply(relationMethod, current, arguments_);
388
+ const value = Reflect.get(operations, operation, operations);
389
+ if (typeof value != "function") throw new TypeError("Invalid relation operation");
390
+ const result = Reflect.apply(value, operations, operationArguments);
391
+ return isPromiseLike$1(result) ? transactions.track(result) : result;
392
+ };
393
+ } });
394
+ };
373
395
  const effective = transactions.resolveRepository(entity, baseRepository);
374
396
  const value = Reflect.get(effective, property, effective);
375
397
  if (typeof value != "function") return value;
@@ -424,7 +446,7 @@ function shouldRollback(error, options) {
424
446
  }
425
447
  for (const constructor of options.noRollbackFor ?? []) {
426
448
  const distance = inheritanceDistance(error, constructor);
427
- if (distance <= bestDistance) {
449
+ if (Number.isFinite(distance) && distance <= bestDistance) {
428
450
  bestDistance = distance;
429
451
  rollback = false;
430
452
  }
@@ -560,6 +582,7 @@ var TransactionManager = class {
560
582
  } catch (error) {
561
583
  await this.rejectPendingOperations(physical);
562
584
  if (error instanceof RollbackOnlyAbort || shouldRollback(error, options)) throw error;
585
+ if (physical.rollbackOnly) throw new RollbackOnlyAbort();
563
586
  return {
564
587
  type: "committed-error",
565
588
  error
@@ -613,26 +636,22 @@ var TransactionManager = class {
613
636
  if (options.connectionName != null) normalizeDuraxisConnectionName(options.connectionName);
614
637
  }
615
638
  };
616
- // src/transactions/transactional.decorator.ts
639
+ // src/transactions/transactional.metadata.ts
617
640
  var TRANSACTIONAL_METADATA = Symbol.for("@duraxis/nestjs/transactional");
618
- function Transactional(options = {}) {
619
- return (target, _propertyKey, descriptor) => {
620
- const metadataTarget = descriptor?.value ?? target;
621
- Reflect.defineMetadata(TRANSACTIONAL_METADATA, Object.freeze({ ...options }), metadataTarget);
622
- };
623
- }
624
- /** Alias of `@Transactional()`. It is unrelated to `Transaction` from `@duraxis/core`. */
625
- var Transaction = Transactional;
626
641
  function transactionalOptions(instance, method) {
627
642
  const classOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, instance.constructor);
628
643
  const methodOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, method);
629
- if (!classOptions && !methodOptions) return void 0;
630
- return {
644
+ return !classOptions && !methodOptions ? void 0 : {
631
645
  ...classOptions,
632
646
  ...methodOptions
633
647
  };
634
648
  }
635
- // src/transactions/transactional.proxy.ts
649
+ // src/transactions/transactional.instrumentation.ts
650
+ var MANAGERS = Symbol("Duraxis transaction managers");
651
+ var bindings = /* @__PURE__ */ new WeakMap();
652
+ var defaultConnections = /* @__PURE__ */ new WeakMap();
653
+ var injectablePrototypes = /* @__PURE__ */ new WeakSet();
654
+ var wrappers = /* @__PURE__ */ new WeakSet();
636
655
  var LIFECYCLE_METHODS = /* @__PURE__ */ new Set([
637
656
  "onModuleInit",
638
657
  "onApplicationBootstrap",
@@ -640,28 +659,47 @@ var LIFECYCLE_METHODS = /* @__PURE__ */ new Set([
640
659
  "beforeApplicationShutdown",
641
660
  "onApplicationShutdown"
642
661
  ]);
643
- function createTransactionalServiceProxy(instance, managers, defaultConnectionName) {
644
- const methods = /* @__PURE__ */ new Map();
645
- return new Proxy(instance, { get(target, property) {
646
- const cached = methods.get(property);
647
- if (cached) return cached;
648
- const value = Reflect.get(target, property, target);
649
- if (typeof value != "function") return value;
650
- const options = LIFECYCLE_METHODS.has(property) ? void 0 : transactionalOptions(target, value);
651
- const method = options ? (...arguments_) => {
652
- const connectionName = normalizeDuraxisConnectionName(options.connectionName ?? defaultConnectionName);
653
- return managers.get(connectionName).execute(options, `${target.constructor.name}.${String(property)}`, () => Reflect.apply(value, target, arguments_));
654
- } : value.bind(target);
655
- methods.set(property, method);
656
- return method;
662
+ function injectTransactionManagers(prototype) {
663
+ if (injectablePrototypes.has(prototype)) return;
664
+ injectablePrototypes.add(prototype);
665
+ Object.defineProperty(prototype, MANAGERS, { set(managers) {
666
+ bindings.set(this, managers);
667
+ instrumentTransactionalMethods(this);
657
668
  } });
669
+ (0, _nestjs_common.Inject)(TransactionManagerRegistry)(prototype, MANAGERS);
658
670
  }
659
- function transactionalServiceProvider(service, defaultConnectionName) {
660
- return {
661
- provide: service,
662
- inject: [_nestjs_core.ModuleRef, TransactionManagerRegistry],
663
- useFactory: async (moduleRef, managers) => createTransactionalServiceProxy(await moduleRef.create(service), managers, defaultConnectionName)
671
+ function setTransactionalDefaultConnection(instance, name) {
672
+ defaultConnections.set(instance, name);
673
+ }
674
+ function wrapTransactionalMethod(method, property) {
675
+ if (wrappers.has(method)) return method;
676
+ const wrapped = function(...arguments_) {
677
+ const methodName = `${this.constructor.name}.${String(property)}`;
678
+ const managers = bindings.get(this);
679
+ if (!managers) throw new TransactionalProviderNotReadyError(methodName);
680
+ const options = transactionalOptions(this, wrapped) ?? {};
681
+ const name = normalizeDuraxisConnectionName(options.connectionName ?? defaultConnections.get(this));
682
+ return managers.get(name).execute(options, methodName, () => Reflect.apply(method, this, arguments_));
664
683
  };
684
+ for (const key of Reflect.getOwnMetadataKeys(method)) Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, method), wrapped);
685
+ wrappers.add(wrapped);
686
+ return wrapped;
687
+ }
688
+ function instrumentTransactionalMethods(target) {
689
+ const visited = /* @__PURE__ */ new Set();
690
+ for (let prototype = target; prototype && prototype != Object.prototype; prototype = Object.getPrototypeOf(prototype)) for (const property of Reflect.ownKeys(prototype)) {
691
+ if (visited.has(property)) continue;
692
+ visited.add(property);
693
+ if (property == "constructor" || LIFECYCLE_METHODS.has(property)) continue;
694
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
695
+ const method = descriptor?.value;
696
+ if (typeof method != "function" || !transactionalOptions(target, method)) continue;
697
+ if (wrappers.has(method)) continue;
698
+ Object.defineProperty(target, property, {
699
+ ...descriptor,
700
+ value: wrapTransactionalMethod(method, property)
701
+ });
702
+ }
665
703
  }
666
704
  // src/duraxis.module.ts
667
705
  function rootProviders(name, optionsProvider) {
@@ -738,7 +776,20 @@ function featureModule(entities, services, connectionName) {
738
776
  const uniqueEntities = [...new Set(entities)];
739
777
  const uniqueServices = [...new Set(services)];
740
778
  const repositoryProviders = uniqueEntities.map((entity) => repositoryProvider(entity, name));
741
- const serviceProviders = uniqueServices.map((service) => transactionalServiceProvider(service, name));
779
+ const serviceProviders = uniqueServices.flatMap((service) => {
780
+ return [{
781
+ provide: service,
782
+ useClass: service,
783
+ scope: _nestjs_common.Scope.DEFAULT
784
+ }, {
785
+ provide: Symbol(`${service.name} default transaction connection`),
786
+ inject: [service],
787
+ useFactory: (instance) => {
788
+ setTransactionalDefaultConnection(instance, name);
789
+ return name;
790
+ }
791
+ }];
792
+ });
742
793
  let DuraxisFeatureEntitiesMarker = class DuraxisFeatureEntitiesMarker {};
743
794
  DuraxisFeatureEntitiesMarker = __decorate([DuraxisFeatureEntities({
744
795
  connectionName: name,
@@ -788,9 +839,11 @@ var DuraxisModule = class DuraxisModule {
788
839
  static forFeature(entities, connectionName) {
789
840
  return featureModule(entities, [], connectionName);
790
841
  }
842
+ /** @deprecated Use forFeature(entities, connectionName) and regular module providers. */
791
843
  static forTransactionalFeature(entities, providers, connectionName) {
792
844
  return featureModule(entities, providers, connectionName);
793
845
  }
846
+ /** @deprecated Declare services in the consuming module's providers array. */
794
847
  static forTransactionalProviders(providers, connectionName) {
795
848
  return featureModule([], providers, connectionName);
796
849
  }
@@ -809,6 +862,21 @@ function InjectDuraxisDatabase(connectionName) {
809
862
  function InjectDuraxisTransactionManager(connectionName) {
810
863
  return (0, _nestjs_common.Inject)(getDuraxisTransactionManagerToken(connectionName));
811
864
  }
865
+ // src/transactions/transactional.decorator.ts
866
+ function Transactional(options = {}) {
867
+ return (target, _propertyKey, descriptor) => {
868
+ const metadataTarget = descriptor?.value ?? target;
869
+ Reflect.defineMetadata(TRANSACTIONAL_METADATA, Object.freeze({ ...options }), metadataTarget);
870
+ if (descriptor && _propertyKey != null) {
871
+ if (typeof descriptor.value != "function" || typeof target == "function") throw new TypeError("@Transactional() requires an instance method");
872
+ injectTransactionManagers(target);
873
+ descriptor.value = wrapTransactionalMethod(descriptor.value, _propertyKey);
874
+ } else if (typeof target == "function") {
875
+ injectTransactionManagers(target.prototype);
876
+ instrumentTransactionalMethods(target.prototype);
877
+ }
878
+ };
879
+ }
812
880
  exports.DEFAULT_DURAXIS_CONNECTION = DEFAULT_DURAXIS_CONNECTION;
813
881
  exports.DuplicateDuraxisConnectionError = DuplicateDuraxisConnectionError;
814
882
  Object.defineProperty(exports, "DuraxisModule", {
@@ -825,7 +893,6 @@ exports.InjectDuraxisRepository = InjectDuraxisRepository;
825
893
  exports.InjectDuraxisTransactionManager = InjectDuraxisTransactionManager;
826
894
  exports.NestedTransactionNotSupportedError = NestedTransactionNotSupportedError;
827
895
  exports.ReadOnlyTransactionError = ReadOnlyTransactionError;
828
- exports.Transaction = Transaction;
829
896
  exports.TransactionContextClosedError = TransactionContextClosedError;
830
897
  exports.TransactionContextManager = TransactionContextManager;
831
898
  exports.TransactionIsolation = TransactionIsolation;
@@ -836,6 +903,7 @@ exports.TransactionPropagation = TransactionPropagation;
836
903
  exports.TransactionRequiredError = TransactionRequiredError;
837
904
  exports.Transactional = Transactional;
838
905
  exports.TransactionalMethodReturnTypeError = TransactionalMethodReturnTypeError;
906
+ exports.TransactionalProviderNotReadyError = TransactionalProviderNotReadyError;
839
907
  exports.UnawaitedTransactionOperationError = UnawaitedTransactionOperationError;
840
908
  exports.UnexpectedTransactionRollbackError = UnexpectedTransactionRollbackError;
841
909
  exports.UnsupportedMixedTransactionError = UnsupportedMixedTransactionError;