import { Propagation , Transactional } from 'typeorm-transactional-cls-hooked' ; import { RollbackErrorException } from './exceptions/rollback-error-exception' ; import { createNamespace } from 'cls-hooked' ; export type RunFunction = ( ) => Promise < void > | void ; const scope = createNamespace ( 'recursiveContext' ) ; param func export function runInTransaction ( func ) { return async ( ) => { try { await TransactionCreator . run ( func ) ; } catch ( e ) { if ( e instanceof RollbackErrorException ) { } else { throw e ; } } } ; } param connections param func Dzeri96 export function runInMultiConnectionTransaction ( connections , func ) { return async ( ) => { if ( connections && connections . length != 0 ) { await scope . runPromise ( async ( ) => { scope . set ( 'connections' , connections ) ; try { await TransactionCreator . runWithMultipleConnections ( func ) ; } catch ( e ) { if ( e instanceof RollbackErrorException ) { } else { throw e ; } } } ) ; } else { throw 'Connection array is empty. Consider using runInTransaction() instead.' ; } } ; } class TransactionCreator { @ Transactional ( ) static async run ( func ) { await func ( ) ; throw new RollbackErrorException ( `This is thrown to cause a rollback on the transaction.` ) ; } @ Transactional ( { connectionName : ( ) => scope . get ( 'connections' ) . pop ( ) , propagation : Propagation . NESTED , } ) static async runWithConnection ( func ) { await func ( ) ; throw new RollbackErrorException ( `This is thrown to cause a rollback on the transaction.` ) ; } static async runWithMultipleConnections ( func ) { const connections = scope . get ( 'connections' ) || [ ] ; if ( connections . length != 0 ) { await TransactionCreator . runWithConnection ( async ( ) => await TransactionCreator . runWithMultipleConnections ( func ) ) ; } else { await TransactionCreator . runWithConnection ( func ) ; } } }