Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ezzabuzaid/8d980277c5364645404cb6779740b670 to your computer and use it in GitHub Desktop.
Save ezzabuzaid/8d980277c5364645404cb6779740b670 to your computer and use it in GitHub Desktop.
/**
*
* 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