@pinia/colada-plugin-auto-refetch
Version:
Automatically refetch queries when they become stale in Pinia Colada
81 lines (80 loc) • 2.91 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
PiniaColadaAutoRefetch: () => PiniaColadaAutoRefetch,
_REFETCH_TIMEOUT_KEY: () => REFETCH_TIMEOUT_KEY
});
module.exports = __toCommonJS(index_exports);
var import_vue = require("vue");
var REFETCH_TIMEOUT_KEY = Symbol();
function PiniaColadaAutoRefetch(options = {}) {
const { autoRefetch = false } = options;
return ({ queryCache }) => {
if (typeof document === "undefined") return;
function scheduleRefetch(entry, options2) {
if (!entry.active) return;
clearTimeout(entry.ext[REFETCH_TIMEOUT_KEY]);
const timeout = setTimeout(() => {
if (options2) {
const entry2 = queryCache.getEntries({
key: (0, import_vue.toValue)(options2.key)
})?.[0];
if (entry2 && entry2.active) {
queryCache.refresh(entry2).catch(console.error);
}
}
}, options2.staleTime);
entry.ext[REFETCH_TIMEOUT_KEY] = timeout;
}
queryCache.$onAction(({ name, args, after }) => {
function shouldScheduleRefetch(options2) {
const queryEnabled = (0, import_vue.toValue)(options2.autoRefetch) ?? autoRefetch;
const staleTime = options2.staleTime;
return Boolean(queryEnabled && staleTime);
}
if (name === "ensure") {
const [options2] = args;
after((entry) => {
if (!shouldScheduleRefetch(options2)) return;
scheduleRefetch(entry, options2);
});
}
if (name === "fetch") {
const [entry] = args;
clearTimeout(entry.ext[REFETCH_TIMEOUT_KEY]);
after(async () => {
if (!entry.options) return;
if (!shouldScheduleRefetch(entry.options)) return;
scheduleRefetch(entry, entry.options);
});
}
if (name === "remove") {
const [entry] = args;
clearTimeout(entry.ext[REFETCH_TIMEOUT_KEY]);
}
});
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PiniaColadaAutoRefetch,
_REFETCH_TIMEOUT_KEY
});
//# sourceMappingURL=index.cjs.map