queryClient.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var utils = require('./utils.js');
  4. var queryCache = require('./queryCache.js');
  5. var mutationCache = require('./mutationCache.js');
  6. var focusManager = require('./focusManager.js');
  7. var onlineManager = require('./onlineManager.js');
  8. var notifyManager = require('./notifyManager.js');
  9. var infiniteQueryBehavior = require('./infiniteQueryBehavior.js');
  10. var logger = require('./logger');
  11. // CLASS
  12. class QueryClient {
  13. constructor(config = {}) {
  14. this.queryCache = config.queryCache || new queryCache.QueryCache();
  15. this.mutationCache = config.mutationCache || new mutationCache.MutationCache();
  16. this.logger = config.logger || logger.defaultLogger;
  17. this.defaultOptions = config.defaultOptions || {};
  18. this.queryDefaults = [];
  19. this.mutationDefaults = [];
  20. this.mountCount = 0;
  21. if (process.env.NODE_ENV !== 'production' && config.logger) {
  22. this.logger.error("Passing a custom logger has been deprecated and will be removed in the next major version.");
  23. }
  24. }
  25. mount() {
  26. this.mountCount++;
  27. if (this.mountCount !== 1) return;
  28. this.unsubscribeFocus = focusManager.focusManager.subscribe(() => {
  29. if (focusManager.focusManager.isFocused()) {
  30. this.resumePausedMutations();
  31. this.queryCache.onFocus();
  32. }
  33. });
  34. this.unsubscribeOnline = onlineManager.onlineManager.subscribe(() => {
  35. if (onlineManager.onlineManager.isOnline()) {
  36. this.resumePausedMutations();
  37. this.queryCache.onOnline();
  38. }
  39. });
  40. }
  41. unmount() {
  42. var _this$unsubscribeFocu, _this$unsubscribeOnli;
  43. this.mountCount--;
  44. if (this.mountCount !== 0) return;
  45. (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
  46. this.unsubscribeFocus = undefined;
  47. (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
  48. this.unsubscribeOnline = undefined;
  49. }
  50. isFetching(arg1, arg2) {
  51. const [filters] = utils.parseFilterArgs(arg1, arg2);
  52. filters.fetchStatus = 'fetching';
  53. return this.queryCache.findAll(filters).length;
  54. }
  55. isMutating(filters) {
  56. return this.mutationCache.findAll({ ...filters,
  57. fetching: true
  58. }).length;
  59. }
  60. getQueryData(queryKey, filters) {
  61. var _this$queryCache$find;
  62. return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
  63. }
  64. ensureQueryData(arg1, arg2, arg3) {
  65. const parsedOptions = utils.parseQueryArgs(arg1, arg2, arg3);
  66. const cachedData = this.getQueryData(parsedOptions.queryKey);
  67. return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(parsedOptions);
  68. }
  69. getQueriesData(queryKeyOrFilters) {
  70. return this.getQueryCache().findAll(queryKeyOrFilters).map(({
  71. queryKey,
  72. state
  73. }) => {
  74. const data = state.data;
  75. return [queryKey, data];
  76. });
  77. }
  78. setQueryData(queryKey, updater, options) {
  79. const query = this.queryCache.find(queryKey);
  80. const prevData = query == null ? void 0 : query.state.data;
  81. const data = utils.functionalUpdate(updater, prevData);
  82. if (typeof data === 'undefined') {
  83. return undefined;
  84. }
  85. const parsedOptions = utils.parseQueryArgs(queryKey);
  86. const defaultedOptions = this.defaultQueryOptions(parsedOptions);
  87. return this.queryCache.build(this, defaultedOptions).setData(data, { ...options,
  88. manual: true
  89. });
  90. }
  91. setQueriesData(queryKeyOrFilters, updater, options) {
  92. return notifyManager.notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({
  93. queryKey
  94. }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
  95. }
  96. getQueryState(queryKey, filters) {
  97. var _this$queryCache$find2;
  98. return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
  99. }
  100. removeQueries(arg1, arg2) {
  101. const [filters] = utils.parseFilterArgs(arg1, arg2);
  102. const queryCache = this.queryCache;
  103. notifyManager.notifyManager.batch(() => {
  104. queryCache.findAll(filters).forEach(query => {
  105. queryCache.remove(query);
  106. });
  107. });
  108. }
  109. resetQueries(arg1, arg2, arg3) {
  110. const [filters, options] = utils.parseFilterArgs(arg1, arg2, arg3);
  111. const queryCache = this.queryCache;
  112. const refetchFilters = {
  113. type: 'active',
  114. ...filters
  115. };
  116. return notifyManager.notifyManager.batch(() => {
  117. queryCache.findAll(filters).forEach(query => {
  118. query.reset();
  119. });
  120. return this.refetchQueries(refetchFilters, options);
  121. });
  122. }
  123. cancelQueries(arg1, arg2, arg3) {
  124. const [filters, cancelOptions = {}] = utils.parseFilterArgs(arg1, arg2, arg3);
  125. if (typeof cancelOptions.revert === 'undefined') {
  126. cancelOptions.revert = true;
  127. }
  128. const promises = notifyManager.notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
  129. return Promise.all(promises).then(utils.noop).catch(utils.noop);
  130. }
  131. invalidateQueries(arg1, arg2, arg3) {
  132. const [filters, options] = utils.parseFilterArgs(arg1, arg2, arg3);
  133. return notifyManager.notifyManager.batch(() => {
  134. var _ref, _filters$refetchType;
  135. this.queryCache.findAll(filters).forEach(query => {
  136. query.invalidate();
  137. });
  138. if (filters.refetchType === 'none') {
  139. return Promise.resolve();
  140. }
  141. const refetchFilters = { ...filters,
  142. type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active'
  143. };
  144. return this.refetchQueries(refetchFilters, options);
  145. });
  146. }
  147. refetchQueries(arg1, arg2, arg3) {
  148. const [filters, options] = utils.parseFilterArgs(arg1, arg2, arg3);
  149. const promises = notifyManager.notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => {
  150. var _options$cancelRefetc;
  151. return query.fetch(undefined, { ...options,
  152. cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
  153. meta: {
  154. refetchPage: filters.refetchPage
  155. }
  156. });
  157. }));
  158. let promise = Promise.all(promises).then(utils.noop);
  159. if (!(options != null && options.throwOnError)) {
  160. promise = promise.catch(utils.noop);
  161. }
  162. return promise;
  163. }
  164. fetchQuery(arg1, arg2, arg3) {
  165. const parsedOptions = utils.parseQueryArgs(arg1, arg2, arg3);
  166. const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
  167. if (typeof defaultedOptions.retry === 'undefined') {
  168. defaultedOptions.retry = false;
  169. }
  170. const query = this.queryCache.build(this, defaultedOptions);
  171. return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
  172. }
  173. prefetchQuery(arg1, arg2, arg3) {
  174. return this.fetchQuery(arg1, arg2, arg3).then(utils.noop).catch(utils.noop);
  175. }
  176. fetchInfiniteQuery(arg1, arg2, arg3) {
  177. const parsedOptions = utils.parseQueryArgs(arg1, arg2, arg3);
  178. parsedOptions.behavior = infiniteQueryBehavior.infiniteQueryBehavior();
  179. return this.fetchQuery(parsedOptions);
  180. }
  181. prefetchInfiniteQuery(arg1, arg2, arg3) {
  182. return this.fetchInfiniteQuery(arg1, arg2, arg3).then(utils.noop).catch(utils.noop);
  183. }
  184. resumePausedMutations() {
  185. return this.mutationCache.resumePausedMutations();
  186. }
  187. getQueryCache() {
  188. return this.queryCache;
  189. }
  190. getMutationCache() {
  191. return this.mutationCache;
  192. }
  193. getLogger() {
  194. return this.logger;
  195. }
  196. getDefaultOptions() {
  197. return this.defaultOptions;
  198. }
  199. setDefaultOptions(options) {
  200. this.defaultOptions = options;
  201. }
  202. setQueryDefaults(queryKey, options) {
  203. const result = this.queryDefaults.find(x => utils.hashQueryKey(queryKey) === utils.hashQueryKey(x.queryKey));
  204. if (result) {
  205. result.defaultOptions = options;
  206. } else {
  207. this.queryDefaults.push({
  208. queryKey,
  209. defaultOptions: options
  210. });
  211. }
  212. }
  213. getQueryDefaults(queryKey) {
  214. if (!queryKey) {
  215. return undefined;
  216. } // Get the first matching defaults
  217. const firstMatchingDefaults = this.queryDefaults.find(x => utils.partialMatchKey(queryKey, x.queryKey)); // Additional checks and error in dev mode
  218. if (process.env.NODE_ENV !== 'production') {
  219. // Retrieve all matching defaults for the given key
  220. const matchingDefaults = this.queryDefaults.filter(x => 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
  221. if (matchingDefaults.length > 1) {
  222. 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.");
  223. }
  224. }
  225. return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
  226. }
  227. setMutationDefaults(mutationKey, options) {
  228. const result = this.mutationDefaults.find(x => utils.hashQueryKey(mutationKey) === utils.hashQueryKey(x.mutationKey));
  229. if (result) {
  230. result.defaultOptions = options;
  231. } else {
  232. this.mutationDefaults.push({
  233. mutationKey,
  234. defaultOptions: options
  235. });
  236. }
  237. }
  238. getMutationDefaults(mutationKey) {
  239. if (!mutationKey) {
  240. return undefined;
  241. } // Get the first matching defaults
  242. const firstMatchingDefaults = this.mutationDefaults.find(x => utils.partialMatchKey(mutationKey, x.mutationKey)); // Additional checks and error in dev mode
  243. if (process.env.NODE_ENV !== 'production') {
  244. // Retrieve all matching defaults for the given key
  245. const matchingDefaults = this.mutationDefaults.filter(x => 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
  246. if (matchingDefaults.length > 1) {
  247. 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.");
  248. }
  249. }
  250. return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
  251. }
  252. defaultQueryOptions(options) {
  253. if (options != null && options._defaulted) {
  254. return options;
  255. }
  256. const defaultedOptions = { ...this.defaultOptions.queries,
  257. ...this.getQueryDefaults(options == null ? void 0 : options.queryKey),
  258. ...options,
  259. _defaulted: true
  260. };
  261. if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
  262. defaultedOptions.queryHash = utils.hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
  263. } // dependent default values
  264. if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
  265. defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
  266. }
  267. if (typeof defaultedOptions.useErrorBoundary === 'undefined') {
  268. defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense;
  269. }
  270. return defaultedOptions;
  271. }
  272. defaultMutationOptions(options) {
  273. if (options != null && options._defaulted) {
  274. return options;
  275. }
  276. return { ...this.defaultOptions.mutations,
  277. ...this.getMutationDefaults(options == null ? void 0 : options.mutationKey),
  278. ...options,
  279. _defaulted: true
  280. };
  281. }
  282. clear() {
  283. this.queryCache.clear();
  284. this.mutationCache.clear();
  285. }
  286. }
  287. exports.QueryClient = QueryClient;
  288. //# sourceMappingURL=queryClient.js.map