picotx
Version:
A minimal library to create atomic transaction for any function
46 lines (42 loc) • 2.46 kB
TypeScript
/**
* Represents a transaction context that accumulates compensation (rollback) functions.
*
* @property {Array<() => Promise<void>>} compensations - An array of functions to perform rollback operations.
*/
interface TransactionContext {
compensations: Array<() => Promise<void>>;
}
type AtomicFunction<A extends any[], R> = (...args: A) => Promise<R>;
/**
* Creates an atomic function that automatically retrieves the current transaction context.
*
* @template A - The type of the arguments for the action.
* @template R - The return type of the action.
* @param action - The asynchronous action to execute.
* @param compensation - The asynchronous compensation (rollback) function to execute if needed.
* @returns An atomic function that accepts the action arguments.
*/
declare function atomic<A extends any[], R>(action: (...args: A) => Promise<R>, compensation: (result: R, ...args: A) => Promise<void>): AtomicFunction<A, R>;
type ExplicitAtomicFunction<A extends any[], R> = (ctx: TransactionContext) => (...args: A) => Promise<R>;
/**
* Creates an atomic function that requires an explicit transaction context.
*
* @template A - The type of the arguments for the action.
* @template R - The return type of the action.
* @param action - The asynchronous action to execute.
* @param compensation - The asynchronous compensation (rollback) function to execute if needed.
* @returns A curried atomic function that must first be invoked with a transaction context and then the action arguments.
*/
declare function atomicExplicit<A extends any[], R>(action: (...args: A) => Promise<R>, compensation: (result: R, ...args: A) => Promise<void>): ExplicitAtomicFunction<A, R>;
/**
* Executes a transactional operation by managing a global transaction context.
* If the provided callback function expects an argument, it is called with the transaction context.
* Otherwise, the function is invoked without arguments.
*
* @template T - The type of the transaction result.
* @param fn - The asynchronous function containing transactional logic.
* If it declares a parameter, it will be called with the transaction context.
* @returns A promise that resolves to the transaction result.
*/
declare function transaction<T>(fn: ((ctx: TransactionContext) => Promise<T>) | (() => Promise<T>)): Promise<T>;
export { type AtomicFunction, type ExplicitAtomicFunction, type TransactionContext, atomic, atomicExplicit, transaction };