Last active
July 23, 2020 23:36
-
-
Save uladkasach/e2f602553a07cae29700b70729b2e332 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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