@jay-js/system
Version:
A powerful and flexible TypeScript library for UI, state management, lazy loading, routing and managing draggable elements in modern web applications.
79 lines • 2.84 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { queryCache } from "./cache.js";
import { defaultRetryDelay, executeFetch, executeWithRetry, resolveQueryKey } from "./utils.js";
/**
* Default prefetch options
*/
const DEFAULT_OPTIONS = {
staleTime: 0,
cacheTime: 300000,
force: false,
};
/**
* Prefetch query data before component mounts
* Populates cache for later use by query()
*
* Unlike query(), prefetchQuery doesn't create a reactive store.
* It simply loads data into the cache for instant availability when query() is called.
*
* @param key Query key to prefetch
* @param fetcher Async function to fetch data
* @param options Prefetch configuration options
* @returns Promise that resolves when prefetch completes (or fails silently)
*
* @example
* Basic usage:
* ```typescript
* // Prefetch on route change
* router.beforeEach(async (to) => {
* if (to.path === '/users') {
* await prefetchQuery('users', fetchUsers);
* }
* });
*
* // Later, component mounts
* const usersQuery = query('users', fetchUsers);
* // → isLoading = false (cache hit!)
* // → data = [prefetched users]
* ```
*
* @example
* With staleTime:
* ```typescript
* // Only prefetch if data is stale
* await prefetchQuery('users', fetchUsers, { staleTime: 5000 });
* ```
*
* @example
* Force refetch:
* ```typescript
* // Always fetch regardless of cache
* await prefetchQuery('users', fetchUsers, { force: true });
* ```
*/
export function prefetchQuery(key_1, fetcher_1) {
return __awaiter(this, arguments, void 0, function* (key, fetcher, options = {}) {
const opts = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
const queryKey = resolveQueryKey(key);
const cached = queryCache.get(queryKey);
if (!opts.force && cached && !queryCache.isStale(queryKey, opts.staleTime)) {
return;
}
try {
const data = yield executeFetch(queryKey, (signal) => executeWithRetry(fetcher, 3, defaultRetryDelay, signal));
queryCache.set(queryKey, data, opts.cacheTime);
}
catch (_a) {
//
}
});
}
//# sourceMappingURL=prefetch.js.map