Function: Transactional()
Transactional(
source?,options?): (target,propertyKey,descriptor) =>PropertyDescriptor
Defined in: service-core/src/decorators/DatabaseDecorators.ts:207
Apply this to perform all operations in a single transaction. The specified source can
be the name of a connection or the class type of a persistent data model. If no source is specified it is inferred
by lookup via this.modelClass which is injected when @Model is added to a class.
For MongoDB, this has the effect of creating a new session and wrapping the function call in
session.withTransaction(). Note that you must pass in the session to each MongoRepository function you wish
to use the transaction. The session is automatically made available for the duration of the call via
transactionContext (an AsyncLocalStorage that is scoped to this call). Optionally, it can also be injected to a
function argument that is decorated with @MongoSession.
For TypeORM, this has the effect of creating a new transaction and wrapping the function call in
datasource.transaction(). Note that you must use the provided EntityManager for all database actions. The
entityManager is automatically made available for the duration of the call via transactionContext. Optionally,
it can be injected to a function argument that is decorated with @EntityManager.
If @Transactional was already in effect earlier in the current call stack (e.g. a RepoUtils method called
from a ModelRoute method that's also @Transactional), the existing transaction is reused by default rather
than opening a second, nested one. See TransactionalOptions.mode.
Note: A @Transactional method MUST always return a promise (e.g. is async).
Parameters
source?
any
The name of the datasource or the class type that a transaction will be created for. If none specified,
the source is inferred using this.modelClass.
options?
The transcation options to pass to the underlying datasource connection.
Returns
(target, propertyKey, descriptor) => PropertyDescriptor
Examples
@Model(MongoModel)
class MyClass {
@Repository(MongoModel)
private myRepo: MongoRepository<MongoModel>;
@Transactional()
public myFunc(obj: MongoModel, @MongoSession() session) {
await this.myRepo.save(obj, { session });
}
}
class MyClass {
@Repository(MongoModel)
private myRepo: MongoRepository<MongoModel>;
@Repository(MongoModel2)
private myRepo2: MongoRepository<MongoModel2>;
@Transactional(MongoModel)
public myFunc(obj: MongoModel, @MongoSession() session) {
await this.myRepo.save(obj, { session });
}
}
class MyClass {
@Repository(SQLModel)
private myRepo: Repository<SQLModel>;
@Transactional(SQLModel)
public myFunc(obj: SQLModel, @EntityManager() em) {
await em.save(obj);
}
}