UNPKG

@tanstack/query-core

Version:

The framework agnostic core that powers TanStack Query

322 lines (321 loc) 11.1 kB
"use strict"; 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/queryClient.ts var queryClient_exports = {}; __export(queryClient_exports, { QueryClient: () => QueryClient }); module.exports = __toCommonJS(queryClient_exports); var import_utils = require("./utils.cjs"); var import_queryCache = require("./queryCache.cjs"); var import_mutationCache = require("./mutationCache.cjs"); var import_focusManager = require("./focusManager.cjs"); var import_onlineManager = require("./onlineManager.cjs"); var import_notifyManager = require("./notifyManager.cjs"); var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs"); var QueryClient = class { #queryCache; #mutationCache; #defaultOptions; #queryDefaults; #mutationDefaults; #mountCount; #unsubscribeFocus; #unsubscribeOnline; constructor(config = {}) { this.#queryCache = config.queryCache || new import_queryCache.QueryCache(); this.#mutationCache = config.mutationCache || new import_mutationCache.MutationCache(); this.#defaultOptions = config.defaultOptions || {}; this.#queryDefaults = /* @__PURE__ */ new Map(); this.#mutationDefaults = /* @__PURE__ */ new Map(); this.#mountCount = 0; } mount() { this.#mountCount++; if (this.#mountCount !== 1) return; this.#unsubscribeFocus = import_focusManager.focusManager.subscribe(async (focused) => { if (focused) { await this.resumePausedMutations(); this.#queryCache.onFocus(); } }); this.#unsubscribeOnline = import_onlineManager.onlineManager.subscribe(async (online) => { if (online) { await this.resumePausedMutations(); this.#queryCache.onOnline(); } }); } unmount() { this.#mountCount--; if (this.#mountCount !== 0) return; this.#unsubscribeFocus?.(); this.#unsubscribeFocus = void 0; this.#unsubscribeOnline?.(); this.#unsubscribeOnline = void 0; } isFetching(filters) { return this.#queryCache.findAll({ ...filters, fetchStatus: "fetching" }).length; } isMutating(filters) { return this.#mutationCache.findAll({ ...filters, status: "pending" }).length; } /** * Imperative (non-reactive) way to retrieve data for a QueryKey. * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. * * Hint: Do not use this function inside a component, because it won't receive updates. * Use `useQuery` to create a `QueryObserver` that subscribes to changes. */ getQueryData(queryKey) { const options = this.defaultQueryOptions({ queryKey }); return this.#queryCache.get(options.queryHash)?.state.data; } ensureQueryData(options) { const defaultedOptions = this.defaultQueryOptions(options); const query = this.#queryCache.build(this, defaultedOptions); const cachedData = query.state.data; if (cachedData === void 0) { return this.fetchQuery(options); } if (options.revalidateIfStale && query.isStaleByTime((0, import_utils.resolveStaleTime)(defaultedOptions.staleTime, query))) { void this.prefetchQuery(defaultedOptions); } return Promise.resolve(cachedData); } getQueriesData(filters) { return this.#queryCache.findAll(filters).map(({ queryKey, state }) => { const data = state.data; return [queryKey, data]; }); } setQueryData(queryKey, updater, options) { const defaultedOptions = this.defaultQueryOptions({ queryKey }); const query = this.#queryCache.get( defaultedOptions.queryHash ); const prevData = query?.state.data; const data = (0, import_utils.functionalUpdate)(updater, prevData); if (data === void 0) { return void 0; } return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true }); } setQueriesData(filters, updater, options) { return import_notifyManager.notifyManager.batch( () => this.#queryCache.findAll(filters).map(({ queryKey }) => [ queryKey, this.setQueryData(queryKey, updater, options) ]) ); } getQueryState(queryKey) { const options = this.defaultQueryOptions({ queryKey }); return this.#queryCache.get( options.queryHash )?.state; } removeQueries(filters) { const queryCache = this.#queryCache; import_notifyManager.notifyManager.batch(() => { queryCache.findAll(filters).forEach((query) => { queryCache.remove(query); }); }); } resetQueries(filters, options) { const queryCache = this.#queryCache; return import_notifyManager.notifyManager.batch(() => { queryCache.findAll(filters).forEach((query) => { query.reset(); }); return this.refetchQueries( { type: "active", ...filters }, options ); }); } cancelQueries(filters, cancelOptions = {}) { const defaultedCancelOptions = { revert: true, ...cancelOptions }; const promises = import_notifyManager.notifyManager.batch( () => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions)) ); return Promise.all(promises).then(import_utils.noop).catch(import_utils.noop); } invalidateQueries(filters, options = {}) { return import_notifyManager.notifyManager.batch(() => { this.#queryCache.findAll(filters).forEach((query) => { query.invalidate(); }); if (filters?.refetchType === "none") { return Promise.resolve(); } return this.refetchQueries( { ...filters, type: filters?.refetchType ?? filters?.type ?? "active" }, options ); }); } refetchQueries(filters, options = {}) { const fetchOptions = { ...options, cancelRefetch: options.cancelRefetch ?? true }; const promises = import_notifyManager.notifyManager.batch( () => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled()).map((query) => { let promise = query.fetch(void 0, fetchOptions); if (!fetchOptions.throwOnError) { promise = promise.catch(import_utils.noop); } return query.state.fetchStatus === "paused" ? Promise.resolve() : promise; }) ); return Promise.all(promises).then(import_utils.noop); } fetchQuery(options) { const defaultedOptions = this.defaultQueryOptions(options); if (defaultedOptions.retry === void 0) { defaultedOptions.retry = false; } const query = this.#queryCache.build(this, defaultedOptions); return query.isStaleByTime( (0, import_utils.resolveStaleTime)(defaultedOptions.staleTime, query) ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); } prefetchQuery(options) { return this.fetchQuery(options).then(import_utils.noop).catch(import_utils.noop); } fetchInfiniteQuery(options) { options.behavior = (0, import_infiniteQueryBehavior.infiniteQueryBehavior)(options.pages); return this.fetchQuery(options); } prefetchInfiniteQuery(options) { return this.fetchInfiniteQuery(options).then(import_utils.noop).catch(import_utils.noop); } ensureInfiniteQueryData(options) { options.behavior = (0, import_infiniteQueryBehavior.infiniteQueryBehavior)(options.pages); return this.ensureQueryData(options); } resumePausedMutations() { if (import_onlineManager.onlineManager.isOnline()) { return this.#mutationCache.resumePausedMutations(); } return Promise.resolve(); } getQueryCache() { return this.#queryCache; } getMutationCache() { return this.#mutationCache; } getDefaultOptions() { return this.#defaultOptions; } setDefaultOptions(options) { this.#defaultOptions = options; } setQueryDefaults(queryKey, options) { this.#queryDefaults.set((0, import_utils.hashKey)(queryKey), { queryKey, defaultOptions: options }); } getQueryDefaults(queryKey) { const defaults = [...this.#queryDefaults.values()]; const result = {}; defaults.forEach((queryDefault) => { if ((0, import_utils.partialMatchKey)(queryKey, queryDefault.queryKey)) { Object.assign(result, queryDefault.defaultOptions); } }); return result; } setMutationDefaults(mutationKey, options) { this.#mutationDefaults.set((0, import_utils.hashKey)(mutationKey), { mutationKey, defaultOptions: options }); } getMutationDefaults(mutationKey) { const defaults = [...this.#mutationDefaults.values()]; const result = {}; defaults.forEach((queryDefault) => { if ((0, import_utils.partialMatchKey)(mutationKey, queryDefault.mutationKey)) { Object.assign(result, queryDefault.defaultOptions); } }); return result; } defaultQueryOptions(options) { if (options._defaulted) { return options; } const defaultedOptions = { ...this.#defaultOptions.queries, ...this.getQueryDefaults(options.queryKey), ...options, _defaulted: true }; if (!defaultedOptions.queryHash) { defaultedOptions.queryHash = (0, import_utils.hashQueryKeyByOptions)( defaultedOptions.queryKey, defaultedOptions ); } if (defaultedOptions.refetchOnReconnect === void 0) { defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always"; } if (defaultedOptions.throwOnError === void 0) { defaultedOptions.throwOnError = !!defaultedOptions.suspense; } if (!defaultedOptions.networkMode && defaultedOptions.persister) { defaultedOptions.networkMode = "offlineFirst"; } if (defaultedOptions.queryFn === import_utils.skipToken) { defaultedOptions.enabled = false; } return defaultedOptions; } defaultMutationOptions(options) { if (options?._defaulted) { return options; } return { ...this.#defaultOptions.mutations, ...options?.mutationKey && this.getMutationDefaults(options.mutationKey), ...options, _defaulted: true }; } clear() { this.#queryCache.clear(); this.#mutationCache.clear(); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { QueryClient }); //# sourceMappingURL=queryClient.cjs.map