UNPKG

@cdellacqua/knex-transact

Version:

transact function that provides a simple mechanism to translate SQL transactions into code

38 lines (34 loc) 1.19 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const config = {}; async function transact(provider, trx) { const transaction = trx || (await config.knexInstance?.transaction()); if (!transaction) { throw new Error("missing knex instance in config object, try assigning your knex instance to the config.knexInstance property of this package"); } const ownTransaction = !trx; const providers = Array.isArray(provider) ? provider : [provider]; try { let result = await providers[0](transaction); // eslint-disable-next-line for (const p of providers.slice(1)) { // eslint-disable-next-line result = await p(transaction, result); } if (ownTransaction) { await transaction.commit(); } return result; } catch (err) { if (ownTransaction) { await transaction.rollback(); } throw new Error("an error occurred while executing the transaction" + (ownTransaction ? ", rolled back" : ""), { cause: err, }); } } exports.config = config; exports.transact = transact;