Skip to content

Instantly share code, notes, and snippets.

@ash-r1
Last active July 25, 2020 06:34
Show Gist options
  • Save ash-r1/d89f9ca447780dfe984acd152721038e to your computer and use it in GitHub Desktop.
Save ash-r1/d89f9ca447780dfe984acd152721038e to your computer and use it in GitHub Desktop.
Exec queries in a transaction on nest.js with TypeORM
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: Ofcourse, you need to add `TypeOrmModule.forRoot` with foo and bar entities as nest.js document says.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment