I have a custom repository class like this with NestJS/Typeorm:
import { Repository, EntityRepository, getConnection } from 'typeorm';
import { RefreshToken } from './refresh-token.entity';
import { User } from './user.entity';
import { InternalServerErrorException } from '@nestjs/common';
@EntityRepository(RefreshToken)
export class RefreshTokenRepository extends Repository<RefreshToken> {
async refreshToken({ token, user }: RefreshToken): Promise<RefreshToken> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
// establish real database connection using our new query runner
await queryRunner.connect();
// lets now open a new transaction:
await queryRunner.startTransaction();
try {
// execute some operations on this transaction:
await queryRunner.manager.delete(RefreshToken, { token });
const refreshToken = await queryRunner.manager.save(
this.buildToken(user),
);
// commit transaction now:
await queryRunner.commitTransaction();
return refreshToken;
} catch (err) {
// since we have errors lets rollback changes we made
await queryRunner.rollbackTransaction();
} finally {
// you need to release query runner which is manually created:
await queryRunner.release();
}
}
}
Is there a different way to make/build a transaction than the one I did in refreshToken()
method please? Because getting a connection feels broken and not appropriate with the way NestJS works.
Thanks.