typeorm-transactional-async-callbacks
Version:
A Transactional Method Decorator for typeorm that uses cls-hooked to handle and propagate transactions between different repositories and service methods. Inpired by Spring Trasnactional Annotation and Sequelize CLS
48 lines (37 loc) • 1.29 kB
text/typescript
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserReaderService } from './user-reader.service';
import { User } from '../entities/User.entity';
import { runOnTransactionCommit, runOnTransactionRollback, Transactional } from '../../src';
()
export class UserWriterService {
constructor(
private readonly repository: Repository<User>,
private readonly readerService: UserReaderService,
) {}
(User)
()
async createUser(name: string, hookHandler?: (isCommitted: boolean) => any): Promise<User> {
if (hookHandler) {
runOnTransactionCommit(() => hookHandler(true));
runOnTransactionRollback(() => hookHandler(false));
}
const user = new User(name, 0);
await this.repository.save(user);
return user;
}
()
async createUserAndThrow(
name: string,
hookHandler?: (isCommitted: boolean) => any,
): Promise<User> {
if (hookHandler) {
runOnTransactionCommit(() => hookHandler(true));
runOnTransactionRollback(() => hookHandler(false));
}
const user = new User(name, 0);
await this.repository.save(user);
throw new Error('Some error');
}
}