@pinia/colada-plugin-retry 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023-present Eduardo San Martin Morote
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ <h1>
2
+ <img height="76" src="https://github.com/posva/pinia-colada/assets/664177/02011637-f94d-4a35-854a-02f7aed86a3c" alt="Pinia Colada logo">
3
+ Pinia Colada Retry
4
+ </h1>
5
+
6
+ <a href="https://npmjs.com/package/@pinia/colada-plugin-retry">
7
+ <img src="https://badgen.net/npm/v/@pinia/colada-plugin-retry/latest" alt="npm package">
8
+ </a>
9
+
10
+ Retry failed queries or mutations with your Pinia Colada.
11
+
12
+ ## Installation
13
+
14
+ ```sh
15
+ npm install @pinia/colada-plugin-retry
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```js
21
+ import { PiniaColadaRetry } from '@pinia/colada-plugin-retry'
22
+
23
+ // Pass the plugin to Pinia Colada options
24
+ app.use(PiniaColadaRetry, {
25
+ // ...
26
+ plugins: [
27
+ PiniaColadaRetry({
28
+ // Pinia Colada Retry options
29
+ }),
30
+ ],
31
+ })
32
+ ```
33
+
34
+ You can customize the retry behavior individually for each query/mutation with the `retry` option:
35
+
36
+ ```ts
37
+ // TODO:
38
+ ```
39
+
40
+ ## License
41
+
42
+ [MIT](http://opensource.org/licenses/MIT)
package/dist/index.cjs ADDED
@@ -0,0 +1,111 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.ts
20
+ var src_exports = {};
21
+ __export(src_exports, {
22
+ PiniaColadaRetry: () => PiniaColadaRetry
23
+ });
24
+ module.exports = __toCommonJS(src_exports);
25
+ var RETRY_OPTIONS_DEFAULTS = {
26
+ delay: (attempt) => {
27
+ const time = Math.min(
28
+ 2 ** attempt * 1e3,
29
+ // never more than 30 seconds
30
+ 3e4
31
+ );
32
+ console.log(`\u23F2\uFE0F delaying attempt #${attempt + 1} by ${time}ms`);
33
+ return time;
34
+ },
35
+ retry: (count) => {
36
+ console.log(
37
+ `\u{1F504} Retrying ${"\u{1F7E8}".repeat(count + 1)}${"\u2B1C\uFE0F".repeat(2 - count)}`
38
+ );
39
+ return count < 2;
40
+ }
41
+ };
42
+ function PiniaColadaRetry(globalOptions) {
43
+ const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions };
44
+ return ({ queryCache }) => {
45
+ const retryMap = /* @__PURE__ */ new Map();
46
+ let isInternalCall = false;
47
+ queryCache.$onAction(({ name, args, after, onError }) => {
48
+ if (name === "remove") {
49
+ const [cacheEntry] = args;
50
+ const key2 = cacheEntry.key.join("/");
51
+ const entry = retryMap.get(key2);
52
+ if (entry) {
53
+ clearTimeout(entry.timeoutId);
54
+ retryMap.delete(key2);
55
+ }
56
+ }
57
+ if (name !== "fetch") return;
58
+ const [queryEntry] = args;
59
+ const localOptions = queryEntry.options?.retry;
60
+ const options = {
61
+ ...typeof localOptions === "object" ? localOptions : {
62
+ retry: localOptions
63
+ }
64
+ };
65
+ const retry = options.retry ?? defaults.retry;
66
+ const delay = options.delay ?? defaults.delay;
67
+ if (retry === 0) return;
68
+ const key = queryEntry.key.join("/");
69
+ clearTimeout(retryMap.get(key)?.timeoutId);
70
+ if (!isInternalCall) {
71
+ retryMap.delete(key);
72
+ }
73
+ const retryFetch = () => {
74
+ if (queryEntry.state.value.status === "error") {
75
+ const error = queryEntry.state.value.error;
76
+ let entry = retryMap.get(key);
77
+ if (!entry) {
78
+ entry = { retryCount: 0 };
79
+ retryMap.set(key, entry);
80
+ }
81
+ const shouldRetry = typeof retry === "number" ? retry > entry.retryCount : retry(entry.retryCount, error);
82
+ if (shouldRetry) {
83
+ const delayTime = typeof delay === "function" ? delay(entry.retryCount) : delay;
84
+ entry.timeoutId = setTimeout(() => {
85
+ isInternalCall = true;
86
+ Promise.resolve(queryCache.fetch(queryEntry)).catch(
87
+ process.env.NODE_ENV !== "test" ? console.error : () => {
88
+ }
89
+ );
90
+ isInternalCall = false;
91
+ if (entry) {
92
+ entry.retryCount++;
93
+ }
94
+ }, delayTime);
95
+ } else {
96
+ retryMap.delete(key);
97
+ }
98
+ } else {
99
+ retryMap.delete(key);
100
+ }
101
+ };
102
+ onError(retryFetch);
103
+ after(retryFetch);
104
+ });
105
+ };
106
+ }
107
+ // Annotate the CommonJS export names for ESM import in node:
108
+ 0 && (module.exports = {
109
+ PiniaColadaRetry
110
+ });
111
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { PiniaColadaPluginContext } from '@pinia/colada'\n/**\n * @module @pinia/colada-plugin-retry\n */\n\n/**\n * Options for the Pinia Colada Retry plugin.\n */\nexport interface RetryOptions {\n /**\n * The delay between retries. Can be a duration in ms or a function that receives the attempt number (starts at 0) and returns a duration in ms. By default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.\n * @param attempt -\n * @returns\n */\n delay?: number | ((attempt: number) => number)\n\n /**\n * The maximum number of times to retry the operation. Set to 0 to disable or to Infinity to retry forever. It can also be a function that receives the failure count and the error and returns if it should retry. Defaults to 3. **Must be a positive number**.\n */\n retry?: number | ((failureCount: number, error: unknown) => boolean)\n}\n\nexport interface RetryEntry {\n retryCount: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nconst RETRY_OPTIONS_DEFAULTS = {\n delay: (attempt: number) => {\n const time = Math.min(\n 2 ** attempt * 1000,\n // never more than 30 seconds\n 30_000,\n )\n console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`)\n return time\n },\n retry: (count) => {\n console.log(\n `🔄 Retrying ${'🟨'.repeat(count + 1)}${'⬜️'.repeat(2 - count)}`,\n )\n return count < 2\n },\n} satisfies Required<RetryOptions>\n\n/**\n * Plugin that adds the ability to retry failed queries.\n *\n * @param globalOptions - global options for the retries\n */\nexport function PiniaColadaRetry(\n globalOptions?: RetryOptions,\n): (context: PiniaColadaPluginContext) => void {\n const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions }\n\n return ({ queryCache }) => {\n const retryMap = new Map<string, RetryEntry>()\n\n let isInternalCall = false\n queryCache.$onAction(({ name, args, after, onError }) => {\n // cleanup all pending retries when data is deleted (means the data is not needed anymore)\n if (name === 'remove') {\n const [cacheEntry] = args\n const key = cacheEntry.key.join('/')\n const entry = retryMap.get(key)\n if (entry) {\n clearTimeout(entry.timeoutId)\n retryMap.delete(key)\n }\n }\n\n if (name !== 'fetch') return\n const [queryEntry] = args\n const localOptions = queryEntry.options?.retry\n\n const options = {\n ...(typeof localOptions === 'object'\n ? localOptions\n : {\n retry: localOptions,\n }),\n } satisfies RetryOptions\n\n const retry = options.retry ?? defaults.retry\n const delay = options.delay ?? defaults.delay\n // avoid setting up anything at all\n if (retry === 0) return\n\n const key = queryEntry.key.join('/')\n\n // clear any pending retry\n clearTimeout(retryMap.get(key)?.timeoutId)\n // if the user manually calls the action, reset the retry count\n if (!isInternalCall) {\n retryMap.delete(key)\n }\n\n const retryFetch = () => {\n if (queryEntry.state.value.status === 'error') {\n const error = queryEntry.state.value.error\n // ensure the entry exists\n let entry = retryMap.get(key)\n if (!entry) {\n entry = { retryCount: 0 }\n retryMap.set(key, entry)\n }\n\n const shouldRetry\n = typeof retry === 'number'\n ? retry > entry.retryCount\n : retry(entry.retryCount, error)\n\n if (shouldRetry) {\n const delayTime\n = typeof delay === 'function' ? delay(entry.retryCount) : delay\n entry.timeoutId = setTimeout(() => {\n // NOTE: we could add some default error handler\n isInternalCall = true\n Promise.resolve(queryCache.fetch(queryEntry)).catch(\n process.env.NODE_ENV !== 'test' ? console.error : () => {},\n )\n isInternalCall = false\n if (entry) {\n entry.retryCount++\n }\n }, delayTime)\n } else {\n // remove the entry if we are not going to retry\n retryMap.delete(key)\n }\n } else {\n // remove the entry if it worked out to reset it\n retryMap.delete(key)\n }\n }\n onError(retryFetch)\n after(retryFetch)\n })\n }\n}\n\ndeclare module '@pinia/colada' {\n // eslint-disable-next-line unused-imports/no-unused-vars\n export interface UseQueryOptions<TResult, TError> {\n /**\n * Options for the retries of this query added by `@pinia/colada-plugin-retry`.\n */\n retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2BA,IAAM,yBAAyB;AAAA,EAC7B,OAAO,CAAC,YAAoB;AAC1B,UAAM,OAAO,KAAK;AAAA,MAChB,KAAK,UAAU;AAAA;AAAA,MAEf;AAAA,IACF;AACA,YAAQ,IAAI,kCAAwB,UAAU,CAAC,OAAO,IAAI,IAAI;AAC9D,WAAO;AAAA,EACT;AAAA,EACA,OAAO,CAAC,UAAU;AAChB,YAAQ;AAAA,MACN,sBAAe,YAAK,OAAO,QAAQ,CAAC,CAAC,GAAG,eAAK,OAAO,IAAI,KAAK,CAAC;AAAA,IAChE;AACA,WAAO,QAAQ;AAAA,EACjB;AACF;AAOO,SAAS,iBACd,eAC6C;AAC7C,QAAM,WAAW,EAAE,GAAG,wBAAwB,GAAG,cAAc;AAE/D,SAAO,CAAC,EAAE,WAAW,MAAM;AACzB,UAAM,WAAW,oBAAI,IAAwB;AAE7C,QAAI,iBAAiB;AACrB,eAAW,UAAU,CAAC,EAAE,MAAM,MAAM,OAAO,QAAQ,MAAM;AAEvD,UAAI,SAAS,UAAU;AACrB,cAAM,CAAC,UAAU,IAAI;AACrB,cAAMA,OAAM,WAAW,IAAI,KAAK,GAAG;AACnC,cAAM,QAAQ,SAAS,IAAIA,IAAG;AAC9B,YAAI,OAAO;AACT,uBAAa,MAAM,SAAS;AAC5B,mBAAS,OAAOA,IAAG;AAAA,QACrB;AAAA,MACF;AAEA,UAAI,SAAS,QAAS;AACtB,YAAM,CAAC,UAAU,IAAI;AACrB,YAAM,eAAe,WAAW,SAAS;AAEzC,YAAM,UAAU;AAAA,QACd,GAAI,OAAO,iBAAiB,WACxB,eACA;AAAA,UACE,OAAO;AAAA,QACT;AAAA,MACN;AAEA,YAAM,QAAQ,QAAQ,SAAS,SAAS;AACxC,YAAM,QAAQ,QAAQ,SAAS,SAAS;AAExC,UAAI,UAAU,EAAG;AAEjB,YAAM,MAAM,WAAW,IAAI,KAAK,GAAG;AAGnC,mBAAa,SAAS,IAAI,GAAG,GAAG,SAAS;AAEzC,UAAI,CAAC,gBAAgB;AACnB,iBAAS,OAAO,GAAG;AAAA,MACrB;AAEA,YAAM,aAAa,MAAM;AACvB,YAAI,WAAW,MAAM,MAAM,WAAW,SAAS;AAC7C,gBAAM,QAAQ,WAAW,MAAM,MAAM;AAErC,cAAI,QAAQ,SAAS,IAAI,GAAG;AAC5B,cAAI,CAAC,OAAO;AACV,oBAAQ,EAAE,YAAY,EAAE;AACxB,qBAAS,IAAI,KAAK,KAAK;AAAA,UACzB;AAEA,gBAAM,cACF,OAAO,UAAU,WACf,QAAQ,MAAM,aACd,MAAM,MAAM,YAAY,KAAK;AAEnC,cAAI,aAAa;AACf,kBAAM,YACF,OAAO,UAAU,aAAa,MAAM,MAAM,UAAU,IAAI;AAC5D,kBAAM,YAAY,WAAW,MAAM;AAEjC,+BAAiB;AACjB,sBAAQ,QAAQ,WAAW,MAAM,UAAU,CAAC,EAAE;AAAA,gBAC5C,QAAQ,IAAI,aAAa,SAAS,QAAQ,QAAQ,MAAM;AAAA,gBAAC;AAAA,cAC3D;AACA,+BAAiB;AACjB,kBAAI,OAAO;AACT,sBAAM;AAAA,cACR;AAAA,YACF,GAAG,SAAS;AAAA,UACd,OAAO;AAEL,qBAAS,OAAO,GAAG;AAAA,UACrB;AAAA,QACF,OAAO;AAEL,mBAAS,OAAO,GAAG;AAAA,QACrB;AAAA,MACF;AACA,cAAQ,UAAU;AAClB,YAAM,UAAU;AAAA,IAClB,CAAC;AAAA,EACH;AACF;","names":["key"]}
@@ -0,0 +1,40 @@
1
+ import { PiniaColadaPluginContext } from '@pinia/colada';
2
+
3
+ /**
4
+ * @module @pinia/colada-plugin-retry
5
+ */
6
+ /**
7
+ * Options for the Pinia Colada Retry plugin.
8
+ */
9
+ interface RetryOptions {
10
+ /**
11
+ * The delay between retries. Can be a duration in ms or a function that receives the attempt number (starts at 0) and returns a duration in ms. By default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.
12
+ * @param attempt -
13
+ * @returns
14
+ */
15
+ delay?: number | ((attempt: number) => number);
16
+ /**
17
+ * The maximum number of times to retry the operation. Set to 0 to disable or to Infinity to retry forever. It can also be a function that receives the failure count and the error and returns if it should retry. Defaults to 3. **Must be a positive number**.
18
+ */
19
+ retry?: number | ((failureCount: number, error: unknown) => boolean);
20
+ }
21
+ interface RetryEntry {
22
+ retryCount: number;
23
+ timeoutId?: ReturnType<typeof setTimeout>;
24
+ }
25
+ /**
26
+ * Plugin that adds the ability to retry failed queries.
27
+ *
28
+ * @param globalOptions - global options for the retries
29
+ */
30
+ declare function PiniaColadaRetry(globalOptions?: RetryOptions): (context: PiniaColadaPluginContext) => void;
31
+ declare module '@pinia/colada' {
32
+ interface UseQueryOptions<TResult, TError> {
33
+ /**
34
+ * Options for the retries of this query added by `@pinia/colada-plugin-retry`.
35
+ */
36
+ retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>;
37
+ }
38
+ }
39
+
40
+ export { PiniaColadaRetry, type RetryEntry, type RetryOptions };
@@ -0,0 +1,40 @@
1
+ import { PiniaColadaPluginContext } from '@pinia/colada';
2
+
3
+ /**
4
+ * @module @pinia/colada-plugin-retry
5
+ */
6
+ /**
7
+ * Options for the Pinia Colada Retry plugin.
8
+ */
9
+ interface RetryOptions {
10
+ /**
11
+ * The delay between retries. Can be a duration in ms or a function that receives the attempt number (starts at 0) and returns a duration in ms. By default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.
12
+ * @param attempt -
13
+ * @returns
14
+ */
15
+ delay?: number | ((attempt: number) => number);
16
+ /**
17
+ * The maximum number of times to retry the operation. Set to 0 to disable or to Infinity to retry forever. It can also be a function that receives the failure count and the error and returns if it should retry. Defaults to 3. **Must be a positive number**.
18
+ */
19
+ retry?: number | ((failureCount: number, error: unknown) => boolean);
20
+ }
21
+ interface RetryEntry {
22
+ retryCount: number;
23
+ timeoutId?: ReturnType<typeof setTimeout>;
24
+ }
25
+ /**
26
+ * Plugin that adds the ability to retry failed queries.
27
+ *
28
+ * @param globalOptions - global options for the retries
29
+ */
30
+ declare function PiniaColadaRetry(globalOptions?: RetryOptions): (context: PiniaColadaPluginContext) => void;
31
+ declare module '@pinia/colada' {
32
+ interface UseQueryOptions<TResult, TError> {
33
+ /**
34
+ * Options for the retries of this query added by `@pinia/colada-plugin-retry`.
35
+ */
36
+ retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>;
37
+ }
38
+ }
39
+
40
+ export { PiniaColadaRetry, type RetryEntry, type RetryOptions };
package/dist/index.js ADDED
@@ -0,0 +1,87 @@
1
+ // src/index.ts
2
+ var RETRY_OPTIONS_DEFAULTS = {
3
+ delay: (attempt) => {
4
+ const time = Math.min(
5
+ 2 ** attempt * 1e3,
6
+ // never more than 30 seconds
7
+ 3e4
8
+ );
9
+ console.log(`\u23F2\uFE0F delaying attempt #${attempt + 1} by ${time}ms`);
10
+ return time;
11
+ },
12
+ retry: (count) => {
13
+ console.log(
14
+ `\u{1F504} Retrying ${"\u{1F7E8}".repeat(count + 1)}${"\u2B1C\uFE0F".repeat(2 - count)}`
15
+ );
16
+ return count < 2;
17
+ }
18
+ };
19
+ function PiniaColadaRetry(globalOptions) {
20
+ const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions };
21
+ return ({ queryCache }) => {
22
+ const retryMap = /* @__PURE__ */ new Map();
23
+ let isInternalCall = false;
24
+ queryCache.$onAction(({ name, args, after, onError }) => {
25
+ if (name === "remove") {
26
+ const [cacheEntry] = args;
27
+ const key2 = cacheEntry.key.join("/");
28
+ const entry = retryMap.get(key2);
29
+ if (entry) {
30
+ clearTimeout(entry.timeoutId);
31
+ retryMap.delete(key2);
32
+ }
33
+ }
34
+ if (name !== "fetch") return;
35
+ const [queryEntry] = args;
36
+ const localOptions = queryEntry.options?.retry;
37
+ const options = {
38
+ ...typeof localOptions === "object" ? localOptions : {
39
+ retry: localOptions
40
+ }
41
+ };
42
+ const retry = options.retry ?? defaults.retry;
43
+ const delay = options.delay ?? defaults.delay;
44
+ if (retry === 0) return;
45
+ const key = queryEntry.key.join("/");
46
+ clearTimeout(retryMap.get(key)?.timeoutId);
47
+ if (!isInternalCall) {
48
+ retryMap.delete(key);
49
+ }
50
+ const retryFetch = () => {
51
+ if (queryEntry.state.value.status === "error") {
52
+ const error = queryEntry.state.value.error;
53
+ let entry = retryMap.get(key);
54
+ if (!entry) {
55
+ entry = { retryCount: 0 };
56
+ retryMap.set(key, entry);
57
+ }
58
+ const shouldRetry = typeof retry === "number" ? retry > entry.retryCount : retry(entry.retryCount, error);
59
+ if (shouldRetry) {
60
+ const delayTime = typeof delay === "function" ? delay(entry.retryCount) : delay;
61
+ entry.timeoutId = setTimeout(() => {
62
+ isInternalCall = true;
63
+ Promise.resolve(queryCache.fetch(queryEntry)).catch(
64
+ process.env.NODE_ENV !== "test" ? console.error : () => {
65
+ }
66
+ );
67
+ isInternalCall = false;
68
+ if (entry) {
69
+ entry.retryCount++;
70
+ }
71
+ }, delayTime);
72
+ } else {
73
+ retryMap.delete(key);
74
+ }
75
+ } else {
76
+ retryMap.delete(key);
77
+ }
78
+ };
79
+ onError(retryFetch);
80
+ after(retryFetch);
81
+ });
82
+ };
83
+ }
84
+ export {
85
+ PiniaColadaRetry
86
+ };
87
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { PiniaColadaPluginContext } from '@pinia/colada'\n/**\n * @module @pinia/colada-plugin-retry\n */\n\n/**\n * Options for the Pinia Colada Retry plugin.\n */\nexport interface RetryOptions {\n /**\n * The delay between retries. Can be a duration in ms or a function that receives the attempt number (starts at 0) and returns a duration in ms. By default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.\n * @param attempt -\n * @returns\n */\n delay?: number | ((attempt: number) => number)\n\n /**\n * The maximum number of times to retry the operation. Set to 0 to disable or to Infinity to retry forever. It can also be a function that receives the failure count and the error and returns if it should retry. Defaults to 3. **Must be a positive number**.\n */\n retry?: number | ((failureCount: number, error: unknown) => boolean)\n}\n\nexport interface RetryEntry {\n retryCount: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nconst RETRY_OPTIONS_DEFAULTS = {\n delay: (attempt: number) => {\n const time = Math.min(\n 2 ** attempt * 1000,\n // never more than 30 seconds\n 30_000,\n )\n console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`)\n return time\n },\n retry: (count) => {\n console.log(\n `🔄 Retrying ${'🟨'.repeat(count + 1)}${'⬜️'.repeat(2 - count)}`,\n )\n return count < 2\n },\n} satisfies Required<RetryOptions>\n\n/**\n * Plugin that adds the ability to retry failed queries.\n *\n * @param globalOptions - global options for the retries\n */\nexport function PiniaColadaRetry(\n globalOptions?: RetryOptions,\n): (context: PiniaColadaPluginContext) => void {\n const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions }\n\n return ({ queryCache }) => {\n const retryMap = new Map<string, RetryEntry>()\n\n let isInternalCall = false\n queryCache.$onAction(({ name, args, after, onError }) => {\n // cleanup all pending retries when data is deleted (means the data is not needed anymore)\n if (name === 'remove') {\n const [cacheEntry] = args\n const key = cacheEntry.key.join('/')\n const entry = retryMap.get(key)\n if (entry) {\n clearTimeout(entry.timeoutId)\n retryMap.delete(key)\n }\n }\n\n if (name !== 'fetch') return\n const [queryEntry] = args\n const localOptions = queryEntry.options?.retry\n\n const options = {\n ...(typeof localOptions === 'object'\n ? localOptions\n : {\n retry: localOptions,\n }),\n } satisfies RetryOptions\n\n const retry = options.retry ?? defaults.retry\n const delay = options.delay ?? defaults.delay\n // avoid setting up anything at all\n if (retry === 0) return\n\n const key = queryEntry.key.join('/')\n\n // clear any pending retry\n clearTimeout(retryMap.get(key)?.timeoutId)\n // if the user manually calls the action, reset the retry count\n if (!isInternalCall) {\n retryMap.delete(key)\n }\n\n const retryFetch = () => {\n if (queryEntry.state.value.status === 'error') {\n const error = queryEntry.state.value.error\n // ensure the entry exists\n let entry = retryMap.get(key)\n if (!entry) {\n entry = { retryCount: 0 }\n retryMap.set(key, entry)\n }\n\n const shouldRetry\n = typeof retry === 'number'\n ? retry > entry.retryCount\n : retry(entry.retryCount, error)\n\n if (shouldRetry) {\n const delayTime\n = typeof delay === 'function' ? delay(entry.retryCount) : delay\n entry.timeoutId = setTimeout(() => {\n // NOTE: we could add some default error handler\n isInternalCall = true\n Promise.resolve(queryCache.fetch(queryEntry)).catch(\n process.env.NODE_ENV !== 'test' ? console.error : () => {},\n )\n isInternalCall = false\n if (entry) {\n entry.retryCount++\n }\n }, delayTime)\n } else {\n // remove the entry if we are not going to retry\n retryMap.delete(key)\n }\n } else {\n // remove the entry if it worked out to reset it\n retryMap.delete(key)\n }\n }\n onError(retryFetch)\n after(retryFetch)\n })\n }\n}\n\ndeclare module '@pinia/colada' {\n // eslint-disable-next-line unused-imports/no-unused-vars\n export interface UseQueryOptions<TResult, TError> {\n /**\n * Options for the retries of this query added by `@pinia/colada-plugin-retry`.\n */\n retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>\n }\n}\n"],"mappings":";AA2BA,IAAM,yBAAyB;AAAA,EAC7B,OAAO,CAAC,YAAoB;AAC1B,UAAM,OAAO,KAAK;AAAA,MAChB,KAAK,UAAU;AAAA;AAAA,MAEf;AAAA,IACF;AACA,YAAQ,IAAI,kCAAwB,UAAU,CAAC,OAAO,IAAI,IAAI;AAC9D,WAAO;AAAA,EACT;AAAA,EACA,OAAO,CAAC,UAAU;AAChB,YAAQ;AAAA,MACN,sBAAe,YAAK,OAAO,QAAQ,CAAC,CAAC,GAAG,eAAK,OAAO,IAAI,KAAK,CAAC;AAAA,IAChE;AACA,WAAO,QAAQ;AAAA,EACjB;AACF;AAOO,SAAS,iBACd,eAC6C;AAC7C,QAAM,WAAW,EAAE,GAAG,wBAAwB,GAAG,cAAc;AAE/D,SAAO,CAAC,EAAE,WAAW,MAAM;AACzB,UAAM,WAAW,oBAAI,IAAwB;AAE7C,QAAI,iBAAiB;AACrB,eAAW,UAAU,CAAC,EAAE,MAAM,MAAM,OAAO,QAAQ,MAAM;AAEvD,UAAI,SAAS,UAAU;AACrB,cAAM,CAAC,UAAU,IAAI;AACrB,cAAMA,OAAM,WAAW,IAAI,KAAK,GAAG;AACnC,cAAM,QAAQ,SAAS,IAAIA,IAAG;AAC9B,YAAI,OAAO;AACT,uBAAa,MAAM,SAAS;AAC5B,mBAAS,OAAOA,IAAG;AAAA,QACrB;AAAA,MACF;AAEA,UAAI,SAAS,QAAS;AACtB,YAAM,CAAC,UAAU,IAAI;AACrB,YAAM,eAAe,WAAW,SAAS;AAEzC,YAAM,UAAU;AAAA,QACd,GAAI,OAAO,iBAAiB,WACxB,eACA;AAAA,UACE,OAAO;AAAA,QACT;AAAA,MACN;AAEA,YAAM,QAAQ,QAAQ,SAAS,SAAS;AACxC,YAAM,QAAQ,QAAQ,SAAS,SAAS;AAExC,UAAI,UAAU,EAAG;AAEjB,YAAM,MAAM,WAAW,IAAI,KAAK,GAAG;AAGnC,mBAAa,SAAS,IAAI,GAAG,GAAG,SAAS;AAEzC,UAAI,CAAC,gBAAgB;AACnB,iBAAS,OAAO,GAAG;AAAA,MACrB;AAEA,YAAM,aAAa,MAAM;AACvB,YAAI,WAAW,MAAM,MAAM,WAAW,SAAS;AAC7C,gBAAM,QAAQ,WAAW,MAAM,MAAM;AAErC,cAAI,QAAQ,SAAS,IAAI,GAAG;AAC5B,cAAI,CAAC,OAAO;AACV,oBAAQ,EAAE,YAAY,EAAE;AACxB,qBAAS,IAAI,KAAK,KAAK;AAAA,UACzB;AAEA,gBAAM,cACF,OAAO,UAAU,WACf,QAAQ,MAAM,aACd,MAAM,MAAM,YAAY,KAAK;AAEnC,cAAI,aAAa;AACf,kBAAM,YACF,OAAO,UAAU,aAAa,MAAM,MAAM,UAAU,IAAI;AAC5D,kBAAM,YAAY,WAAW,MAAM;AAEjC,+BAAiB;AACjB,sBAAQ,QAAQ,WAAW,MAAM,UAAU,CAAC,EAAE;AAAA,gBAC5C,QAAQ,IAAI,aAAa,SAAS,QAAQ,QAAQ,MAAM;AAAA,gBAAC;AAAA,cAC3D;AACA,+BAAiB;AACjB,kBAAI,OAAO;AACT,sBAAM;AAAA,cACR;AAAA,YACF,GAAG,SAAS;AAAA,UACd,OAAO;AAEL,qBAAS,OAAO,GAAG;AAAA,UACrB;AAAA,QACF,OAAO;AAEL,mBAAS,OAAO,GAAG;AAAA,QACrB;AAAA,MACF;AACA,cAAQ,UAAU;AAClB,YAAM,UAAU;AAAA,IAClB,CAAC;AAAA,EACH;AACF;","names":["key"]}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@pinia/colada-plugin-retry",
3
+ "type": "module",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "version": "0.0.0",
8
+ "description": "Retry failed requests with Pinia Colada",
9
+ "author": {
10
+ "name": "Eduardo San Martin Morote",
11
+ "email": "posva13@gmail.com"
12
+ },
13
+ "license": "MIT",
14
+ "funding": "https://github.com/sponsors/posva",
15
+ "homepage": "https://github.com/posva/pinia-colada/plugins/retry#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/posva/pinia-colada.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/posva/pinia-colada/issues"
22
+ },
23
+ "keywords": [
24
+ "pinia",
25
+ "plugin",
26
+ "data",
27
+ "fetching",
28
+ "query",
29
+ "mutation",
30
+ "cache",
31
+ "layer"
32
+ ],
33
+ "sideEffects": false,
34
+ "exports": {
35
+ ".": {
36
+ "types": {
37
+ "import": "./dist/index.d.ts",
38
+ "require": "./dist/index.d.cts"
39
+ },
40
+ "import": "./dist/index.js",
41
+ "require": "./dist/index.cjs"
42
+ }
43
+ },
44
+ "main": "./dist/index.cjs",
45
+ "module": "./dist/index.js",
46
+ "types": "./dist/index.d.ts",
47
+ "typesVersions": {
48
+ "*": {
49
+ "*": [
50
+ "./dist/*",
51
+ "./*"
52
+ ]
53
+ }
54
+ },
55
+ "files": [
56
+ "LICENSE",
57
+ "README.md",
58
+ "dist"
59
+ ],
60
+ "peerDependencies": {
61
+ "@pinia/colada": "^0.10.0"
62
+ },
63
+ "devDependencies": {
64
+ "@pinia/colada": "^0.10.0"
65
+ },
66
+ "scripts": {
67
+ "build": "tsup",
68
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . -l @pinia/colada-plugin-retry -r 1",
69
+ "test": "echo \"Error: no test specified\" && exit 1"
70
+ }
71
+ }