refactor transactions:

- fix the typings
- add rollback and commit to the callback params
This commit is contained in:
Bassel 2023-01-23 18:43:14 +02:00
parent 24fd4a0c1b
commit 4af04c483e
2 changed files with 23 additions and 19 deletions

View File

@ -164,9 +164,13 @@ export interface Database {
query<T extends keyof AllTypes>(uid: T): QueryFromContentType<T>; query<T extends keyof AllTypes>(uid: T): QueryFromContentType<T>;
transaction( transaction(
cb?: (trx: Knex.Transaction) => Promise<any> cb?: (params: {
trx: Knex.Transaction;
rollback: () => Promise<void>;
commit: () => Promise<void>;
}) => Promise<void>
): ):
| Promise<void> | Promise<unknown>
| { get: () => Knex.Transaction; rollback: () => Promise<void>; commit: () => Promise<void> }; | { get: () => Knex.Transaction; rollback: () => Promise<void>; commit: () => Promise<void> };
} }
export class Database implements Database { export class Database implements Database {

View File

@ -54,35 +54,35 @@ class Database {
async transaction(cb) { async transaction(cb) {
const notNestedTransaction = !transactionCtx.get(); const notNestedTransaction = !transactionCtx.get();
const trx = notNestedTransaction ? await this.connection.transaction() : 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) { if (!cb) {
return { return {
async commit() { commit,
if (notNestedTransaction) { rollback,
await trx.commit();
}
},
async rollback() {
if (notNestedTransaction) {
await trx.rollback();
}
},
get() { get() {
return trx; return trx;
}, },
}; };
} }
return transactionCtx.run(trx, async () => { return transactionCtx.run({ trx, commit, rollback }, async () => {
try { try {
const res = await cb(trx); const res = await cb(trx);
if (notNestedTransaction) { await commit();
await trx.commit();
}
return res; return res;
} catch (error) { } catch (error) {
if (notNestedTransaction) { await rollback();
await trx.rollback();
}
throw error; throw error;
} }
}); });