forked from syntaxbullet/AuroraBot-discord
26 lines
779 B
TypeScript
26 lines
779 B
TypeScript
import { DrizzleClient } from "@shared/db/DrizzleClient";
|
|
import type { Transaction } from "@shared/lib/types";
|
|
import { isShuttingDown, incrementTransactions, decrementTransactions } from "./shutdown";
|
|
|
|
export const withTransaction = async <T>(
|
|
callback: (tx: Transaction) => Promise<T>,
|
|
tx?: Transaction
|
|
): Promise<T> => {
|
|
if (tx) {
|
|
return await callback(tx);
|
|
} else {
|
|
if (isShuttingDown()) {
|
|
throw new Error("System is shutting down, no new transactions allowed.");
|
|
}
|
|
|
|
incrementTransactions();
|
|
try {
|
|
return await DrizzleClient.transaction(async (newTx) => {
|
|
return await callback(newTx);
|
|
});
|
|
} finally {
|
|
decrementTransactions();
|
|
}
|
|
}
|
|
};
|