From: Ardis Lu Date: Wed, 26 Feb 2025 05:56:37 +0000 (-0800) Subject: Add `interval` option to `retry` strategy X-Git-Tag: v0.1.0~38 X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=bc87491e7c8eccc8d4206254dc487a910c4778ca;p=csvio Add `interval` option to `retry` strategy --- diff --git a/src/errorStrategies.js b/src/errorStrategies.js index 508fa4d..b9a24a2 100644 --- a/src/errorStrategies.js +++ b/src/errorStrategies.js @@ -33,6 +33,8 @@ function placeholder(value) { /** * @typedef {Object} RetryOptions + * @property {number} [interval] The duration (in milliseconds) to wait in between each retry. The default value is `0` + * (retry immediately). * @property {string} [placeholder] A placeholder value to set if the function still errors after the final iteration. * If unset, the final error thrown by the function is re-thrown. */ @@ -47,8 +49,10 @@ function placeholder(value) { * @throws If `value` is unset and the function throws an error after the final iteration, the error is re-thrown. */ function retry(iterations, options = {}) { + options.interval ??= 0; return async (row, e, fn) => { while (iterations--) { + await utils.sleep(options.interval); try { return await fn(row); } catch { } } diff --git a/test/errorStrategies.test.js b/test/errorStrategies.test.js index 54eda6e..2ea3b98 100644 --- a/test/errorStrategies.test.js +++ b/test/errorStrategies.test.js @@ -133,6 +133,19 @@ suite('ErrorStrategies.retry', { concurrency: true }, () => { [10] ])); }); + test('retries with interval', async (t) => { + assertSleep(t, { min: 10 * 1000, max: 10 * 1000 + 1000 }); + const fn = retryFactory(11); // 1st try + 10 retries = pass on 11th with extra retries available + await createCSVMockStream([ + ['header'], + ['0'] + ]) + .pipeThrough(new CSVTransformer(fn, { onError: retry(10, { interval: 1000 }) })) + .pipeTo(csvStreamEqualWritable([ + ['header'], + [11] + ])); + }); test('sets placeholder if failed after last iteration and placeholder is given', async () => { const fn = retryFactory(100); await createCSVMockStream([