feature: onCommit , onCallback transaction methods

This commit is contained in:
Marc-Roig 2023-05-18 12:57:47 +02:00
parent 5d645f2103
commit 180d61dc0c
No known key found for this signature in database
GPG Key ID: FB4E2C43A0BEE249
4 changed files with 63 additions and 15 deletions

View File

@ -124,7 +124,12 @@ const createAuditLogsService = (strapi) => {
const processedEvent = processEvent(name, ...args);
if (processedEvent) {
await state.provider.saveEvent(processedEvent);
// This avoids saving logs during a transaction that was previously being committed.
// handleEvent is asynchronous, so there is a change that there is transaction being committed
// strapi.db.onTransactionEnd(() => state.provider.saveEvent(processedEvent));
await strapi.db.transaction(({ onCommit }) => {
onCommit(() => state.provider.saveEvent(processedEvent));
});
}
}

View File

@ -168,6 +168,8 @@ export interface Database {
trx: Knex.Transaction;
rollback: () => Promise<void>;
commit: () => Promise<void>;
onCommit: (cb) => void;
onRollback: (cb) => void;
}) => Promise<unknown>
):
| Promise<unknown>

View File

@ -61,31 +61,29 @@ class Database {
async function commit() {
if (notNestedTransaction) {
transactionCtx.clear();
await trx.commit();
await transactionCtx.commit(trx);
}
}
async function rollback() {
if (notNestedTransaction) {
transactionCtx.clear();
await trx.rollback();
await transactionCtx.rollback(trx);
}
}
if (!cb) {
return {
commit,
rollback,
get() {
return trx;
},
};
return { commit, rollback, get: () => trx };
}
return transactionCtx.run(trx, async () => {
try {
const callbackParams = { trx, commit, rollback };
const callbackParams = {
trx,
commit,
rollback,
onCommit: transactionCtx.onCommit,
onRollback: transactionCtx.onRollback,
};
const res = await cb(callbackParams);
await commit();
return res;

View File

@ -6,7 +6,7 @@ const storage = new AsyncLocalStorage();
const transactionCtx = {
async run(store, cb) {
return storage.run({ trx: store }, cb);
return storage.run({ trx: store, commitCallbacks: [], rollbackCallbacks: [] }, cb);
},
get() {
@ -14,11 +14,54 @@ const transactionCtx = {
return store?.trx;
},
clear() {
async commit(trx) {
const store = storage.getStore();
// Clear transaction from store
if (store?.trx) {
store.trx = null;
}
// Commit transaction
await trx.commit();
if (!store?.commitCallbacks) return;
// Run callbacks
store.commitCallbacks.forEach((cb) => cb());
store.commitCallbacks = [];
},
async rollback(trx) {
const store = storage.getStore();
// Clear transaction from store
if (store?.trx) {
store.trx = null;
}
// Rollback transaction
await trx.rollback();
if (!store?.rollbackCallbacks) return;
// Run callbacks
store.rollbackCallbacks.forEach((cb) => cb());
store.rollbackCallbacks = [];
},
onCommit(cb) {
const store = storage.getStore();
if (store?.callbacks) {
store.callbacks.push(cb);
}
},
onRollback(cb) {
const store = storage.getStore();
if (store?.callbacks) {
store.callbacks.push(cb);
}
},
};