@tanstack/query-core
Version:
The framework agnostic core that powers TanStack Query
1 lines • 14.7 kB
Source Map (JSON)
{"version":3,"file":"queryCache.cjs","names":["Subscribable","hashQueryKeyByOptions","Query","matchQuery"],"sources":["../../src/queryCache.ts"],"sourcesContent":["import { hashQueryKeyByOptions, matchQuery } from './utils'\nimport { Query } from './query'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport type { QueryFilters } from './utils'\nimport type { Action, QueryState } from './query'\nimport type {\n DefaultError,\n NotifyEvent,\n QueryKey,\n QueryOptions,\n WithRequired,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { QueryObserver } from './queryObserver'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which\n * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can\n * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these\n * are fire-and-forget: their return value is not awaited before the query settles.\n */\nexport interface QueryCacheConfig {\n /** Called when any query in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n query: Query<unknown, unknown, unknown>,\n ) => void\n /** Called when any query in the cache is successful. */\n onSuccess?: (data: unknown, query: Query<unknown, unknown, unknown>) => void\n /** Called when any query in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n query: Query<unknown, unknown, unknown>,\n ) => void\n}\n\ninterface NotifyEventQueryAdded extends NotifyEvent {\n type: 'added'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryRemoved extends NotifyEvent {\n type: 'removed'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryUpdated extends NotifyEvent {\n type: 'updated'\n query: Query<any, any, any, any>\n action: Action<any, any>\n}\n\ninterface NotifyEventQueryObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverResultsUpdated extends NotifyEvent {\n type: 'observerResultsUpdated'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\n/**\n * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from\n * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or\n * one of its observers is added, removed, or has its results or options updated.\n */\nexport type QueryCacheNotifyEvent =\n | NotifyEventQueryAdded\n | NotifyEventQueryRemoved\n | NotifyEventQueryUpdated\n | NotifyEventQueryObserverAdded\n | NotifyEventQueryObserverRemoved\n | NotifyEventQueryObserverResultsUpdated\n | NotifyEventQueryObserverOptionsUpdated\n\ntype QueryCacheListener = (event: QueryCacheNotifyEvent) => void\n\n/**\n * The store a `QueryCache` keeps its queries in, keyed by query hash.\n */\nexport interface QueryStore {\n /**\n * Returns whether a query with the given hash is stored.\n */\n has: (queryHash: string) => boolean\n /**\n * Stores a query under its hash.\n */\n set: (queryHash: string, query: Query) => void\n /**\n * Returns the query with the given hash, if any.\n */\n get: (queryHash: string) => Query | undefined\n /**\n * Removes the query with the given hash.\n */\n delete: (queryHash: string) => void\n /**\n * Returns an iterator over all stored queries.\n */\n values: () => IterableIterator<Query>\n}\n\n// CLASS\n\n/**\n * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta\n * information, and state of the queries it contains.\n *\n * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`\n * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as queries being added, removed, or updated — updates made\n * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do\n * not notify subscribers.\n * @example\n * ```ts\n * const unsubscribe = queryCache.subscribe((event) => {\n * console.log(event.type, event.query)\n * })\n * ```\n */\nexport class QueryCache extends Subscribable<QueryCacheListener> {\n #queries: QueryStore\n\n constructor(public config: QueryCacheConfig = {}) {\n super()\n this.#queries = new Map<string, Query>()\n }\n\n /**\n * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or\n * builds and adds a new one to the cache if none exists yet. Used by framework adapters and\n * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing\n * the reactive `QueryObserver` machinery.\n * @param client - The client the query belongs to, used to default its options.\n * @param options - The query options, including the `queryKey`. A new query is created with the\n * options defaulted by {@link QueryClient#defaultQueryOptions}.\n * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the\n * query already exists.\n * @returns The existing or newly created query.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const query = queryCache.build(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n * ```\n */\n build<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n client: QueryClient,\n options: WithRequired<\n QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryKey'\n >,\n state?: QueryState<TData, TError>,\n ): Query<TQueryFnData, TError, TData, TQueryKey> {\n const queryKey = options.queryKey\n const queryHash =\n options.queryHash ?? hashQueryKeyByOptions(queryKey, options)\n let query = this.get<TQueryFnData, TError, TData, TQueryKey>(queryHash)\n\n if (!query) {\n query = new Query({\n client,\n queryKey,\n queryHash,\n options: client.defaultQueryOptions(options),\n state,\n defaultOptions: client.getQueryDefaults(queryKey),\n })\n this.add(query)\n }\n\n return query\n }\n\n /**\n * Adds a query to the cache.\n * @internal\n * @param query - The query to add. If a query with the same hash is already cached, nothing\n * happens.\n */\n add(query: Query<any, any, any, any>): void {\n if (!this.#queries.has(query.queryHash)) {\n this.#queries.set(query.queryHash, query)\n\n this.notify({\n type: 'added',\n query,\n })\n }\n }\n\n /**\n * Destroys the given `Query` and removes it from the cache, notifying subscribers with a\n * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash\n * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror\n * removals across `QueryCache` instances.\n * @param query - The query to remove.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * queryCache.remove(query)\n * }\n * ```\n */\n remove(query: Query<any, any, any, any>): void {\n const queryInMap = this.#queries.get(query.queryHash)\n\n if (queryInMap === query) {\n query.destroy()\n this.#queries.delete(query.queryHash)\n this.notify({ type: 'removed', query })\n }\n }\n\n /**\n * Removes all queries from the cache.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * queryCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n this.remove(query)\n })\n })\n }\n\n /**\n * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none\n * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather\n * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash\n * to look up directly.\n * @param queryHash - The hash of the query to look up.\n * @returns The query stored under the hash, or `undefined`.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const queryHash = hashKey(['posts'])\n *\n * const query = queryCache.get(queryHash)\n * ```\n */\n get<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n queryHash: string,\n ): Query<TQueryFnData, TError, TData, TQueryKey> | undefined {\n return this.#queries.get(queryHash) as\n | Query<TQueryFnData, TError, TData, TQueryKey>\n | undefined\n }\n\n /**\n * Returns all queries within the cache.\n * @returns Every query in the cache.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const queries = queryCache.getAll()\n * ```\n */\n getAll(): Array<Query> {\n return [...this.#queries.values()]\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing query instance from the\n * cache. This instance not only contains all the state for the query, but all of the instances,\n * and underlying guts of the query as well. If the query does not exist, `undefined` is\n * returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to\n * decide whether a query is fresh enough to be used as an initial value).\n * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to\n * `true`.\n * @returns The first matching query, or `undefined`.\n * @see {@link QueryCache#findAll}\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const query = queryCache.find({ queryKey: ['posts'] })\n * ```\n */\n find<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData>(\n filters: WithRequired<QueryFilters, 'queryKey'>,\n ): Query<TQueryFnData, TError, TData> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((query) =>\n matchQuery(defaultedFilters, query),\n ) as Query<TQueryFnData, TError, TData> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing query instances from the cache\n * that partially match a query key. If no queries match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about queries in rare scenarios.\n * @param filters - The filters to match. Without filters, every query is returned.\n * @returns The matching queries.\n * @see {@link QueryCache#find}\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const queries = queryCache.findAll({ queryKey: ['posts'] })\n * ```\n */\n findAll(filters: QueryFilters<any> = {}): Array<Query> {\n const queries = this.getAll()\n return Object.keys(filters).length > 0\n ? queries.filter((query) => matchQuery(filters, query))\n : queries\n }\n\n /**\n * Notifies every cache listener of an event, in one batch.\n * @internal\n * @param event - The event passed to every listener.\n */\n notify(event: QueryCacheNotifyEvent): void {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /**\n * Calls {@link Query#onFocus} on every cached query, in one batch.\n * @internal\n */\n onFocus(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onFocus()\n })\n })\n }\n\n /**\n * Calls {@link Query#onOnline} on every cached query, in one batch.\n * @internal\n */\n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