mirror of
https://github.com/strapi/strapi.git
synced 2025-11-01 18:33:55 +00:00
refactor transactions:
- fix the typings - add rollback and commit to the callback params
This commit is contained in:
parent
24fd4a0c1b
commit
4af04c483e
8
packages/core/database/lib/index.d.ts
vendored
8
packages/core/database/lib/index.d.ts
vendored
@ -164,9 +164,13 @@ export interface Database {
|
||||
|
||||
query<T extends keyof AllTypes>(uid: T): QueryFromContentType<T>;
|
||||
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> };
|
||||
}
|
||||
export class Database implements Database {
|
||||
|
||||
@ -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;
|
||||
}
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user