mirror of
https://github.com/strapi/strapi.git
synced 2025-11-17 10:38:30 +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>;
|
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 {
|
||||||
|
|||||||
@ -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();
|
||||||
if (!cb) {
|
|
||||||
return {
|
async function commit() {
|
||||||
async commit() {
|
|
||||||
if (notNestedTransaction) {
|
if (notNestedTransaction) {
|
||||||
await trx.commit();
|
await trx.commit();
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
async rollback() {
|
|
||||||
|
async function rollback() {
|
||||||
if (notNestedTransaction) {
|
if (notNestedTransaction) {
|
||||||
await trx.rollback();
|
await trx.rollback();
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
|
if (!cb) {
|
||||||
|
return {
|
||||||
|
commit,
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user