@pinia/colada-plugin-auto-refetch
Version:
Automatically refetch queries when they become stale in Pinia Colada
64 lines (63 loc) • 2.13 kB
JavaScript
import { _toValueWithArgs } from "@pinia/colada";
import { toValue } from "vue";
//#region src/auto-refetch.ts
/**
* Pinia Colada Auto Refetch plugin.
*
* Automatically refreshes queries when they become stale.
*
* @module @pinia/colada-plugin-auto-refetch
*/
/**
* To store timeouts in the entry extensions.
*
* @internal
*/
const REFETCH_TIMEOUT_KEY = Symbol();
/**
* Plugin that automatically refreshes queries when they become stale
*/
function PiniaColadaAutoRefetch(options = {}) {
const { autoRefetch = false } = options;
return ({ queryCache }) => {
if (typeof document === "undefined") return;
function scheduleRefetch(entry, delayMs) {
if (!entry.active) return;
clearTimeout(entry.ext[REFETCH_TIMEOUT_KEY]);
const timeout = setTimeout(() => {
if (entry?.active && entry.options && toValue(entry.options.enabled)) queryCache.fetch(entry).catch(console.error);
}, delayMs);
entry.ext[REFETCH_TIMEOUT_KEY] = timeout;
}
queryCache.$onAction(({ name, args, after }) => {
/**
* Whether to schedule a refetch for the given entry and determine the interval
* Returns { shouldSchedule: boolean, interval?: number }
*/
function shouldScheduleRefetch({ state, options }) {
const autoRefetchValue = !!options && _toValueWithArgs(options.autoRefetch ?? autoRefetch, state.value);
return !!options && toValue(options.enabled) && (autoRefetchValue === true ? options.staleTime : autoRefetchValue);
}
if (name === "ensure") after((entry) => {
const interval = shouldScheduleRefetch(entry);
if (interval) scheduleRefetch(entry, interval);
});
if (name === "fetch") {
const [entry] = args;
clearTimeout(entry.ext[REFETCH_TIMEOUT_KEY]);
after(async () => {
if (!entry.options) return;
const interval = shouldScheduleRefetch(entry);
if (interval) scheduleRefetch(entry, interval);
});
}
if (name === "remove") {
const [entry] = args;
clearTimeout(entry.ext[REFETCH_TIMEOUT_KEY]);
}
});
};
}
//#endregion
export { PiniaColadaAutoRefetch, REFETCH_TIMEOUT_KEY as _REFETCH_TIMEOUT_KEY };
//# sourceMappingURL=index.mjs.map