react-query
Version:
Hooks for managing, caching and syncing asynchronous and remote data in React
358 lines (277 loc) • 11.6 kB
JavaScript
"use strict";
exports.__esModule = true;
exports.QueryClient = void 0;
var _utils = require("./utils");
var _queryCache = require("./queryCache");
var _mutationCache = require("./mutationCache");
var _focusManager = require("./focusManager");
var _onlineManager = require("./onlineManager");
var _notifyManager = require("./notifyManager");
var _infiniteQueryBehavior = require("./infiniteQueryBehavior");
var _logger = require("./logger");
// CLASS
class QueryClient {
constructor(config = {}) {
this.queryCache = config.queryCache || new _queryCache.QueryCache();
this.mutationCache = config.mutationCache || new _mutationCache.MutationCache();
this.logger = config.logger || _logger.defaultLogger;
this.defaultOptions = config.defaultOptions || {};
this.queryDefaults = [];
this.mutationDefaults = [];
}
mount() {
this.unsubscribeFocus = _focusManager.focusManager.subscribe(() => {
if (_focusManager.focusManager.isFocused()) {
this.resumePausedMutations();
this.queryCache.onFocus();
}
});
this.unsubscribeOnline = _onlineManager.onlineManager.subscribe(() => {
if (_onlineManager.onlineManager.isOnline()) {
this.resumePausedMutations();
this.queryCache.onOnline();
}
});
}
unmount() {
var _this$unsubscribeFocu, _this$unsubscribeOnli;
(_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
(_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
}
isFetching(arg1, arg2) {
const [filters] = (0, _utils.parseFilterArgs)(arg1, arg2);
filters.fetchStatus = 'fetching';
return this.queryCache.findAll(filters).length;
}
isMutating(filters) {
return this.mutationCache.findAll({ ...filters,
fetching: true
}).length;
}
getQueryData(queryKey, filters) {
var _this$queryCache$find;
return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
}
getQueriesData(queryKeyOrFilters) {
return this.getQueryCache().findAll(queryKeyOrFilters).map(({
queryKey,
state
}) => {
const data = state.data;
return [queryKey, data];
});
}
setQueryData(queryKey, updater, options) {
const query = this.queryCache.find(queryKey);
const prevData = query == null ? void 0 : query.state.data;
const data = (0, _utils.functionalUpdate)(updater, prevData);
if (typeof data === 'undefined') {
return undefined;
}
const parsedOptions = (0, _utils.parseQueryArgs)(queryKey);
const defaultedOptions = this.defaultQueryOptions(parsedOptions);
return this.queryCache.build(this, defaultedOptions).setData(data, { ...options,
notifySuccess: false
});
}
setQueriesData(queryKeyOrFilters, updater, options) {
return _notifyManager.notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({
queryKey
}) => [queryKey, this.setQueryData(queryKey, updater, options)]));
}
getQueryState(queryKey, filters) {
var _this$queryCache$find2;
return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
}
removeQueries(arg1, arg2) {
const [filters] = (0, _utils.parseFilterArgs)(arg1, arg2);
const queryCache = this.queryCache;
_notifyManager.notifyManager.batch(() => {
queryCache.findAll(filters).forEach(query => {
queryCache.remove(query);
});
});
}
resetQueries(arg1, arg2, arg3) {
const [filters, options] = (0, _utils.parseFilterArgs)(arg1, arg2, arg3);
const queryCache = this.queryCache;
const refetchFilters = {
type: 'active',
...filters
};
return _notifyManager.notifyManager.batch(() => {
queryCache.findAll(filters).forEach(query => {
query.reset();
});
return this.refetchQueries(refetchFilters, options);
});
}
cancelQueries(arg1, arg2, arg3) {
const [filters, cancelOptions = {}] = (0, _utils.parseFilterArgs)(arg1, arg2, arg3);
if (typeof cancelOptions.revert === 'undefined') {
cancelOptions.revert = true;
}
const promises = _notifyManager.notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
return Promise.all(promises).then(_utils.noop).catch(_utils.noop);
}
invalidateQueries(arg1, arg2, arg3) {
const [filters, options] = (0, _utils.parseFilterArgs)(arg1, arg2, arg3);
return _notifyManager.notifyManager.batch(() => {
var _ref, _filters$refetchType;
this.queryCache.findAll(filters).forEach(query => {
query.invalidate();
});
if (filters.refetchType === 'none') {
return Promise.resolve();
}
const refetchFilters = { ...filters,
type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active'
};
return this.refetchQueries(refetchFilters, options);
});
}
refetchQueries(arg1, arg2, arg3) {
const [filters, options] = (0, _utils.parseFilterArgs)(arg1, arg2, arg3);
const promises = _notifyManager.notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => {
var _options$cancelRefetc;
return query.fetch(undefined, { ...options,
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
meta: {
refetchPage: filters.refetchPage
}
});
}));
let promise = Promise.all(promises).then(_utils.noop);
if (!(options != null && options.throwOnError)) {
promise = promise.catch(_utils.noop);
}
return promise;
}
fetchQuery(arg1, arg2, arg3) {
const parsedOptions = (0, _utils.parseQueryArgs)(arg1, arg2, arg3);
const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
if (typeof defaultedOptions.retry === 'undefined') {
defaultedOptions.retry = false;
}
const query = this.queryCache.build(this, defaultedOptions);
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
}
prefetchQuery(arg1, arg2, arg3) {
return this.fetchQuery(arg1, arg2, arg3).then(_utils.noop).catch(_utils.noop);
}
fetchInfiniteQuery(arg1, arg2, arg3) {
const parsedOptions = (0, _utils.parseQueryArgs)(arg1, arg2, arg3);
parsedOptions.behavior = (0, _infiniteQueryBehavior.infiniteQueryBehavior)();
return this.fetchQuery(parsedOptions);
}
prefetchInfiniteQuery(arg1, arg2, arg3) {
return this.fetchInfiniteQuery(arg1, arg2, arg3).then(_utils.noop).catch(_utils.noop);
}
resumePausedMutations() {
return this.mutationCache.resumePausedMutations();
}
getQueryCache() {
return this.queryCache;
}
getMutationCache() {
return this.mutationCache;
}
getLogger() {
return this.logger;
}
getDefaultOptions() {
return this.defaultOptions;
}
setDefaultOptions(options) {
this.defaultOptions = options;
}
setQueryDefaults(queryKey, options) {
const result = this.queryDefaults.find(x => (0, _utils.hashQueryKey)(queryKey) === (0, _utils.hashQueryKey)(x.queryKey));
if (result) {
result.defaultOptions = options;
} else {
this.queryDefaults.push({
queryKey,
defaultOptions: options
});
}
}
getQueryDefaults(queryKey) {
if (!queryKey) {
return undefined;
} // Get the first matching defaults
const firstMatchingDefaults = this.queryDefaults.find(x => (0, _utils.partialMatchKey)(queryKey, x.queryKey)); // Additional checks and error in dev mode
if (process.env.NODE_ENV !== 'production') {
// Retrieve all matching defaults for the given key
const matchingDefaults = this.queryDefaults.filter(x => (0, _utils.partialMatchKey)(queryKey, x.queryKey)); // It is ok not having defaults, but it is error prone to have more than 1 default for a given key
if (matchingDefaults.length > 1) {
if (process.env.NODE_ENV !== 'production') {
this.logger.error("[QueryClient] Several query defaults match with key '" + JSON.stringify(queryKey) + "'. The first matching query defaults are used. Please check how query defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetquerydefaults.");
}
}
}
return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
}
setMutationDefaults(mutationKey, options) {
const result = this.mutationDefaults.find(x => (0, _utils.hashQueryKey)(mutationKey) === (0, _utils.hashQueryKey)(x.mutationKey));
if (result) {
result.defaultOptions = options;
} else {
this.mutationDefaults.push({
mutationKey,
defaultOptions: options
});
}
}
getMutationDefaults(mutationKey) {
if (!mutationKey) {
return undefined;
} // Get the first matching defaults
const firstMatchingDefaults = this.mutationDefaults.find(x => (0, _utils.partialMatchKey)(mutationKey, x.mutationKey)); // Additional checks and error in dev mode
if (process.env.NODE_ENV !== 'production') {
// Retrieve all matching defaults for the given key
const matchingDefaults = this.mutationDefaults.filter(x => (0, _utils.partialMatchKey)(mutationKey, x.mutationKey)); // It is ok not having defaults, but it is error prone to have more than 1 default for a given key
if (matchingDefaults.length > 1) {
if (process.env.NODE_ENV !== 'production') {
this.logger.error("[QueryClient] Several mutation defaults match with key '" + JSON.stringify(mutationKey) + "'. The first matching mutation defaults are used. Please check how mutation defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetmutationdefaults.");
}
}
}
return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
}
defaultQueryOptions(options) {
if (options != null && options._defaulted) {
return options;
}
const defaultedOptions = { ...this.defaultOptions.queries,
...this.getQueryDefaults(options == null ? void 0 : options.queryKey),
...options,
_defaulted: true
};
if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
defaultedOptions.queryHash = (0, _utils.hashQueryKeyByOptions)(defaultedOptions.queryKey, defaultedOptions);
} // dependent default values
if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
}
if (typeof defaultedOptions.useErrorBoundary === 'undefined') {
defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense;
}
return defaultedOptions;
}
defaultMutationOptions(options) {
if (options != null && options._defaulted) {
return options;
}
return { ...this.defaultOptions.mutations,
...this.getMutationDefaults(options == null ? void 0 : options.mutationKey),
...options,
_defaulted: true
};
}
clear() {
this.queryCache.clear();
this.mutationCache.clear();
}
}
exports.QueryClient = QueryClient;