DEV Community

Ash
Ash

Posted on

How to run queries in a transaction on nest.js with TypeORM

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 {}
Enter fullscreen mode Exit fullscreen mode
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.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)