Skip to content

Instantly share code, notes, and snippets.

@uladkasach
Last active July 23, 2020 23:36
Show Gist options
  • Save uladkasach/e2f602553a07cae29700b70729b2e332 to your computer and use it in GitHub Desktop.
Save uladkasach/e2f602553a07cae29700b70729b2e332 to your computer and use it in GitHub Desktop.
export const withDbTransaction = <
P extends { dbConnection: DatabaseConnection },
R,
T extends (args: P) => Promise<R>
>(
logic: T,
): T => {
return (async (args: Parameters<T>[0]) => {
await args.dbConnection.beginTransaction(); // begin transaction
try {
const result = await logic({ ...args }); // run the request
await args.dbConnection.commit(); // commit if successful
return result;
} catch (error) {
await args.dbConnection.rollback(); // rollback if not successful
throw error;
}
}) as T;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment