strapi/packages/core/database/lib/transaction-context.js

69 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-09-12 15:24:53 +02:00
'use strict';
const { AsyncLocalStorage } = require('async_hooks');
const storage = new AsyncLocalStorage();
const transactionCtx = {
async run(store, cb) {
return storage.run({ trx: store, commitCallbacks: [], rollbackCallbacks: [] }, cb);
2022-09-12 15:24:53 +02:00
},
get() {
const store = storage.getStore();
return store?.trx;
},
async commit(trx) {
const store = storage.getStore();
// Clear transaction from store
if (store?.trx) {
store.trx = null;
}
// Commit transaction
await trx.commit();
2023-05-22 15:19:53 +02:00
if (!store?.commitCallbacks.length) 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();
2023-05-22 15:19:53 +02:00
if (!store?.rollbackCallbacks.length) return;
// Run callbacks
store.rollbackCallbacks.forEach((cb) => cb());
store.rollbackCallbacks = [];
},
onCommit(cb) {
const store = storage.getStore();
2023-05-22 15:19:53 +02:00
if (store?.commitCallbacks) {
store.commitCallbacks.push(cb);
}
},
onRollback(cb) {
const store = storage.getStore();
2023-05-22 15:19:53 +02:00
if (store?.rollbackCallbacks) {
store.rollbackCallbacks.push(cb);
}
2022-09-12 15:24:53 +02:00
},
};
module.exports = transactionCtx;