Created
August 16, 2021 11:30
-
-
Save malisetti/6c896e0c21177b0bc2a11bc1ffb9d184 to your computer and use it in GitHub Desktop.
Execute several functions in a transaction
This file contains hidden or 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 type fn = () => Error | null; | |
export type tfn = { run: fn, revert: fn }; | |
export const doInTransaction = async (i: tfn[]): Promise<Error | null> => { | |
const reverts: fn[] = []; | |
for (const fn of i) { | |
try { | |
const err = await fn.run(); | |
if (err) { | |
throw err; | |
} | |
reverts.push(fn.revert); | |
} catch (error) { | |
const rreverts = reverts.reverse(); | |
for (const rfn of rreverts) { | |
const err = await rfn(); | |
if (err) { | |
return err; | |
} | |
} | |
return error; | |
} | |
} | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment