From 4af04c483e26998c6fcc2ac712a108c43e685e6e Mon Sep 17 00:00:00 2001 From: Bassel Date: Mon, 23 Jan 2023 18:43:14 +0200 Subject: [PATCH] refactor transactions: - fix the typings - add rollback and commit to the callback params --- packages/core/database/lib/index.d.ts | 8 +++++-- packages/core/database/lib/index.js | 34 +++++++++++++-------------- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/packages/core/database/lib/index.d.ts b/packages/core/database/lib/index.d.ts index 406869e0a9..552ae8f02a 100644 --- a/packages/core/database/lib/index.d.ts +++ b/packages/core/database/lib/index.d.ts @@ -164,9 +164,13 @@ export interface Database { query(uid: T): QueryFromContentType; transaction( - cb?: (trx: Knex.Transaction) => Promise + cb?: (params: { + trx: Knex.Transaction; + rollback: () => Promise; + commit: () => Promise; + }) => Promise ): - | Promise + | Promise | { get: () => Knex.Transaction; rollback: () => Promise; commit: () => Promise }; } export class Database implements Database { diff --git a/packages/core/database/lib/index.js b/packages/core/database/lib/index.js index 24339d27ce..1ed94d068e 100644 --- a/packages/core/database/lib/index.js +++ b/packages/core/database/lib/index.js @@ -54,35 +54,35 @@ class Database { async transaction(cb) { const notNestedTransaction = !transactionCtx.get(); const trx = notNestedTransaction ? await this.connection.transaction() : transactionCtx.get(); + + async function commit() { + if (notNestedTransaction) { + await trx.commit(); + } + } + + async function rollback() { + if (notNestedTransaction) { + await trx.rollback(); + } + } if (!cb) { return { - async commit() { - if (notNestedTransaction) { - await trx.commit(); - } - }, - async rollback() { - if (notNestedTransaction) { - await trx.rollback(); - } - }, + commit, + rollback, get() { return trx; }, }; } - return transactionCtx.run(trx, async () => { + return transactionCtx.run({ trx, commit, rollback }, async () => { try { const res = await cb(trx); - if (notNestedTransaction) { - await trx.commit(); - } + await commit(); return res; } catch (error) { - if (notNestedTransaction) { - await trx.rollback(); - } + await rollback(); throw error; } });