I would like to be able to perform queries to the db inside a method of a Typeorm entity when it is about to be saved.
The problem is if the entity will be saved within a transaction, I can't access this transaction to perform my queries and I can get weird results because I am not using the right transactionalEntityManager.
My entity :
class User {
@PrimaryGeneratedColumn()
id: number;
....
@BeforeUpdate()
@BeforeInsert() // this method will be executed before the entity is saved in db
async validateBefore(): Promise<void> {
await getManager().find(.....)
/*
I use getManager to perform a query on the db,
but this just gives me a new entityManager different from the current transaction
*/
}
}
Controller:
await getManager().transaction(async (transactionalEntityManager) => {
const newUser: User = plainToClass(User, {.....})
// I use plainToClass from class-transformer to instantiate a User entity from a plain object
await transactionalEntityManager.save(newUSer) // I save the entity to the db with the transaction manager
// this will fail because this will trigger the validateBefore method which doesn't use the right transactionalEntityManager
})
Is there a way to pass the entity manager to the entity method ?