Skip to content

Commit

Permalink
Simplified transaction handling, now you don't need to always explici…
Browse files Browse the repository at this point in the history
…t result
  • Loading branch information
oskardudycz committed Aug 7, 2024
1 parent c36dd62 commit 87c058e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
22 changes: 17 additions & 5 deletions src/packages/dumbo/src/core/connections/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,38 @@ export interface DatabaseTransactionFactory<
> {
transaction: () => DatabaseTransaction<ConnectorType>;

withTransaction: <Result = unknown>(
withTransaction: <Result = never>(
handle: (
transaction: DatabaseTransaction<ConnectorType>,
) => Promise<{ success: boolean; result: Result }>,
) => Promise<TransactionResult<Result> | Result>,
) => Promise<Result>;
}

export type TransactionResult<Result> = { success: boolean; result: Result };

const toTransactionResult = <Result>(
transactionResult: TransactionResult<Result> | Result,
): TransactionResult<Result> =>
transactionResult !== undefined &&
transactionResult !== null &&
typeof transactionResult === 'object' &&
'success' in transactionResult
? transactionResult
: { success: true, result: transactionResult };

export const executeInTransaction = async <
ConnectorType extends string = string,
Result = unknown,
Result = void,
>(
transaction: DatabaseTransaction<ConnectorType>,
handle: (
transaction: DatabaseTransaction<ConnectorType>,
) => Promise<{ success: boolean; result: Result }>,
) => Promise<TransactionResult<Result> | Result>,
): Promise<Result> => {
await transaction.begin();

try {
const { success, result } = await handle(transaction);
const { success, result } = toTransactionResult(await handle(transaction));

if (success) await transaction.commit();
else await transaction.rollback();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,6 @@ void describe('Node Postgresql', () => {
});
try {
await pool.execute.query(rawSql('SELECT 1'));

return { success: true, result: undefined };
} finally {
await pool.close();
}
Expand Down

0 comments on commit 87c058e

Please sign in to comment.