diff options
author | Lizzy Hunt <logan.hunt@usu.edu> | 2023-02-15 18:03:46 -0700 |
---|---|---|
committer | Lizzy Hunt <logan.hunt@usu.edu> | 2023-02-15 18:05:55 -0700 |
commit | 32803c441678cd640e46153688d26c4c0746d7b3 (patch) | |
tree | f2f186df72073be9ca712d98dff7d180eaa34371 /src/exponential_retry.js | |
parent | 30cbc219e68ef5fc7da56e322e1aeca102bdb479 (diff) | |
download | aggietimed-32803c441678cd640e46153688d26c4c0746d7b3.tar.gz aggietimed-32803c441678cd640e46153688d26c4c0746d7b3.zip |
We do a little logging, but cringe OpenAPI errors be making me want to shoot myself. We have some shit working though.
Diffstat (limited to 'src/exponential_retry.js')
-rw-r--r-- | src/exponential_retry.js | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/exponential_retry.js b/src/exponential_retry.js new file mode 100644 index 0000000..96ca979 --- /dev/null +++ b/src/exponential_retry.js @@ -0,0 +1,35 @@ +import { + MAX_DEFAULT_RETRY_AMOUNT, + WAIT_MS, + RETRY_EXPONENT, + RETRY_EXPONENTIAL_FACTOR, +} from "./constants.js"; + +const wait_for = (ms) => new Promise((rs) => setTimeout(rs, ms)); + +export const with_exponential_retry = async ( + promise_fn, + validation_fn = (x) => Promise.resolve(!!x), + max_retries = MAX_DEFAULT_RETRY_AMOUNT, + retries = 0 +) => { + try { + if (retries) + await wait_for( + WAIT_MS * Math.pow(RETRY_EXPONENT, RETRY_EXPONENTIAL_FACTOR * retries) + ); + + const res = await promise_fn(); + if (await validation_fn(res)) return res; + + throw new Error("Validation predicate not satisfied"); + } catch (e) { + if (retries >= max_retries) throw e; + return with_exponential_retry( + promise_fn, + validation_fn, + max_retries, + retries + 1 + ); + } +}; |