Last active
June 30, 2020 12:43
-
-
Save ralexandr/b0ea0a0d2010bd7cffb9e0de1e385101 to your computer and use it in GitHub Desktop.
Simple wrapper to wrap multiple db-queries in db-transaction
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
import { Transaction } from 'sequelize'; | |
type DatabaseTransactionProps = { | |
transaction?: Transaction; | |
isolationLevel?: string; | |
autocommit?: boolean; | |
}; | |
type TransactionActionCallback = (transaction: Transaction) => Promise<any>; | |
const logger = console; // Here should be some custom logger (like pino, winston, etc) | |
async function wrapInTransaction(action: TransactionActionCallback, opts?: DatabaseTransactionProps) { | |
const { isolationLevel, autocommit = false } = opts || {}; | |
// If no parent transaction has been passed inside "opts" | |
// init new transaction | |
const transaction = | |
opts?.transaction || | |
(await connection.transaction({ | |
isolationLevel: Transaction.ISOLATION_LEVELS[isolationLevel], | |
autocommit, | |
})); | |
try { | |
const result = await action(transaction); | |
// If no parent transaction has been passed inside "opts" | |
// commit inner transaction | |
if (!opts?.transaction) { | |
await transaction.commit(); | |
} | |
return result; | |
} catch (error) { | |
// If no parent transaction has been passed inside "opts" | |
// rollback inner transaction | |
if (!opts?.transaction) { | |
try { | |
await transaction.rollback(); | |
} catch (err) { | |
logger.error('Failed to rollback failed transaction', err); | |
} | |
} | |
throw error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment