@duongtrungnguyen/next-helper
Version:
Helper library for Next.js 15
96 lines • 2.73 kB
JavaScript
import { queryCache } from "./cache";
class QueryClientImpl {
constructor() {
/**
* A set to keep track of currently fetching queries.
*/
this.fetchingQueries = /* @__PURE__ */ new Set();
}
/**
* Converts a query key to a string.
* @param queryKey - The key of the query.
* @returns The string representation of the query key.
*/
getKeyString(queryKey) {
return JSON.stringify(queryKey);
}
/**
* Retrieves the data for a given query key.
* @param queryKey - The key of the query.
* @returns The data associated with the query key, or undefined if not found.
*/
getQueryData(queryKey) {
return queryCache.get(queryKey);
}
/**
* Sets the data for a given query key.
* @param queryKey - The key of the query.
* @param data - The new data or a function that returns the new data based on the old data.
*/
setQueryData(queryKey, data) {
const currentData = queryCache.get(queryKey);
const newData = typeof data === "function" ? data(currentData) : data;
queryCache.set(queryKey, newData);
}
/**
* Invalidates all queries that match the given query key.
* @param queryKey - The key of the query.
*/
async invalidateQueries(queryKey) {
const matchingKeys = queryCache.getMatchingKeys(queryKey);
matchingKeys.forEach((key) => {
queryCache.invalidate(key);
});
}
/**
* Refetches all queries that match the given query key.
* @param queryKey - The key of the query.
*/
async refetchQueries(queryKey) {
const matchingKeys = queryCache.getMatchingKeys(queryKey);
matchingKeys.forEach((key) => {
queryCache.invalidate(key);
});
}
/**
* Removes all queries that match the given query key.
* @param queryKey - The key of the query.
*/
removeQueries(queryKey) {
const matchingKeys = queryCache.getMatchingKeys(queryKey);
matchingKeys.forEach((key) => {
queryCache.remove(key);
});
}
/**
* Clears all queries from the cache.
*/
clear() {
queryCache.clear();
}
/**
* Returns the number of currently fetching queries.
* @returns The number of fetching queries.
*/
isFetching() {
return this.fetchingQueries.size;
}
/**
* Sets the fetching state for a given query key.
* @param queryKey - The key of the query.
* @param isFetching - Whether the query is currently fetching.
*/
setFetching(queryKey, isFetching) {
const keyString = this.getKeyString(queryKey);
if (isFetching) {
this.fetchingQueries.add(keyString);
} else {
this.fetchingQueries.delete(keyString);
}
}
}
const queryClient = new QueryClientImpl();
export {
queryClient
};
//# sourceMappingURL=query-client.js.map