Created
December 2, 2020 22:13
-
-
Save ezzabuzaid/8d980277c5364645404cb6779740b670 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Wrap database calls within transaction | |
* | |
* @param computation an action function with {EntityManager} argument that will be executed after starting the transaction | |
* | |
*/ | |
export async function useTransaction<TResult>(computation: (manager: EntityManager) => Promise<TResult>) { | |
let queryRunner = getConnection().createQueryRunner(); | |
await queryRunner.connect(); | |
await queryRunner.startTransaction(); | |
try { | |
const result = await computation(queryRunner.manager); | |
await queryRunner.commitTransaction(); | |
return result; | |
} catch (error) { | |
await queryRunner.rollbackTransaction(); | |
await queryRunner.release(); | |
queryRunner = null; | |
throw error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment