When we use nest.js in TypeORM app, we may use Repository in Service modules.
But, how about transactions? I found an easy way to do it.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { FooService } from './foo.service';
//TODO: import Foo and Bar entities.
@Module({
imports: [TypeOrmModule.forFeature([Foo, Bar])],
providers: [SurveysService],
// TBD: controllers: [FooController],
})
export class FooModule {}
import { InjectRepository } from '@nestjs/typeorm';
import { Connection, Repository } from 'typeorm';
//TODO: import Foo and Bar entities.
@Injectable()
export class FooService {
constructor(
private connection: Connection
) {}
async doAwesome(): Promise<void> {
await this.connection.transaction(async manager => {
const fooRepository = manager.getRepository<Foo>('foo');
const barRepository = manager.getRepository<Bar>('bar');
await fooRepository.updateSomething();
await barRepository.deleteSomething();
}
}
}
// NOTE: Of course, you need to add `TypeOrmModule.forRoot` with foo and bar entities as nest.js the document says.
Top comments (0)