typeorm-transactional-cls-hooked icon indicating copy to clipboard operation
typeorm-transactional-cls-hooked copied to clipboard

Transaction doesn't work

Open naorye opened this issue 3 years ago • 3 comments

I am using nestjs with typeorm and recentrly I added transaction support with typeorm-transactional-cls-hooked. I made the following method:

@Injectable()
class ConnectionService {
  constructor(
    @InjectRepository(Connection)
    private connectionsRepository: ConnectionsRepository,
  ) {}

  @Transactional()
  public async updateConnection(userId: string, connectionId: string) {
    const connection = await this.getConnectionById(userId, connectionId);

    connection.name = '111';
    await this.connectionsRepository.save(connection);

    throw new Error('error test');

    connection.name = '222';
    await this.connectionsRepository.save(connection);
  }
}

connectionsRepository is defined like that:

import { EntityRepository } from 'typeorm';
import { BaseRepository } from 'typeorm-transactional-cls-hooked';
import { Connection } from '../entities/connection.entity';

@EntityRepository(Connection)
export class ConnectionsRepository extends BaseRepository<Connection> {}

When I am calling updateConnection, I end up with connection.name equals to 111 even though the transaction was rejected. What I am missing?

naorye avatar May 03 '21 22:05 naorye

me too 👍

johntranz avatar Apr 07 '22 04:04 johntranz

@naorye @Jane-Tran Hello all, I solved the problem by writing the proper setting for the Nestjs TypeOrmModule when using Custom Repositories, please see the line of imports in the code below:

@Module({
  providers: [UsersService],
  imports: [TypeOrmModule.forFeature([UsersRepository])],
  exports: [UsersService],
  controllers: [UsersController],
})
export class UsersModule {}

The "Custom Repository" must be provided to when calling .forFeature()

Hope this helps!!!

maborroto avatar Apr 28 '22 10:04 maborroto

Hi all, I had the same problem and it turned out I was missing one thing, so this is an example of a service I had before adding typeorm-transactional-cls-hooked:

@Injectable()
export class MyEntityService {
  constructor(
    @InjectRepository(MyEntity)
    private readonly repository: Repository<MyEntity>,
  ) {}
  
  ...
  
  }

So after adding typeorm-transactional-cls-hooked it got changed to

@Injectable()
export class MyEntityService {
  constructor(
    @InjectRepository(MyEntity)
    private readonly repository: MyEntityRepository, // <--------------------------------- CHANGED HERE
  ) {}
  
  ...
  
  }

But what I missed was that I forgot to delete @InjectRepository(MyEntity), so the final working code looks like this:

@Injectable()
export class MyEntityService {
  constructor(
    // <--------------------------------- CHANGED HERE
    private readonly repository: MyEntityRepository,
  ) {}
  
  ...
  
  }

HappyHappy1996 avatar Aug 30 '22 11:08 HappyHappy1996