| 1 |
// src/query/core/apiState.ts |
| 2 |
var QueryStatus = /* @__PURE__ */ ((QueryStatus2) => { |
| 3 |
QueryStatus2["uninitialized"] = "uninitialized"; |
| 4 |
QueryStatus2["pending"] = "pending"; |
| 5 |
QueryStatus2["fulfilled"] = "fulfilled"; |
| 6 |
QueryStatus2["rejected"] = "rejected"; |
| 7 |
return QueryStatus2; |
| 8 |
})(QueryStatus || {}); |
| 9 |
function getRequestStatusFlags(status) { |
| 10 |
return { |
| 11 |
status, |
| 12 |
isUninitialized: status === "uninitialized" /* uninitialized */, |
| 13 |
isLoading: status === "pending" /* pending */, |
| 14 |
isSuccess: status === "fulfilled" /* fulfilled */, |
| 15 |
isError: status === "rejected" /* rejected */ |
| 16 |
}; |
| 17 |
} |
| 18 |
|
| 19 |
// src/query/core/rtkImports.ts |
| 20 |
import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit"; |
| 21 |
|
| 22 |
// src/query/utils/copyWithStructuralSharing.ts |
| 23 |
var isPlainObject2 = isPlainObject; |
| 24 |
function copyWithStructuralSharing(oldObj, newObj) { |
| 25 |
if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) { |
| 26 |
return newObj; |
| 27 |
} |
| 28 |
const newKeys = Object.keys(newObj); |
| 29 |
const oldKeys = Object.keys(oldObj); |
| 30 |
let isSameObject = newKeys.length === oldKeys.length; |
| 31 |
const mergeObj = Array.isArray(newObj) ? [] : {}; |
| 32 |
for (const key of newKeys) { |
| 33 |
mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]); |
| 34 |
if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]; |
| 35 |
} |
| 36 |
return isSameObject ? oldObj : mergeObj; |
| 37 |
} |
| 38 |
|
| 39 |
// src/query/utils/countObjectKeys.ts |
| 40 |
function countObjectKeys(obj) { |
| 41 |
let count = 0; |
| 42 |
for (const _key in obj) { |
| 43 |
count++; |
| 44 |
} |
| 45 |
return count; |
| 46 |
} |
| 47 |
|
| 48 |
// src/query/utils/flatten.ts |
| 49 |
var flatten = (arr) => [].concat(...arr); |
| 50 |
|
| 51 |
// src/query/utils/isAbsoluteUrl.ts |
| 52 |
function isAbsoluteUrl(url) { |
| 53 |
return new RegExp(`(^|:)//`).test(url); |
| 54 |
} |
| 55 |
|
| 56 |
// src/query/utils/isDocumentVisible.ts |
| 57 |
function isDocumentVisible() { |
| 58 |
if (typeof document === "undefined") { |
| 59 |
return true; |
| 60 |
} |
| 61 |
return document.visibilityState !== "hidden"; |
| 62 |
} |
| 63 |
|
| 64 |
// src/query/utils/isNotNullish.ts |
| 65 |
function isNotNullish(v) { |
| 66 |
return v != null; |
| 67 |
} |
| 68 |
|
| 69 |
// src/query/utils/isOnline.ts |
| 70 |
function isOnline() { |
| 71 |
return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine; |
| 72 |
} |
| 73 |
|
| 74 |
// src/query/utils/joinUrls.ts |
| 75 |
var withoutTrailingSlash = (url) => url.replace(/\/$/, ""); |
| 76 |
var withoutLeadingSlash = (url) => url.replace(/^\//, ""); |
| 77 |
function joinUrls(base, url) { |
| 78 |
if (!base) { |
| 79 |
return url; |
| 80 |
} |
| 81 |
if (!url) { |
| 82 |
return base; |
| 83 |
} |
| 84 |
if (isAbsoluteUrl(url)) { |
| 85 |
return url; |
| 86 |
} |
| 87 |
const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : ""; |
| 88 |
base = withoutTrailingSlash(base); |
| 89 |
url = withoutLeadingSlash(url); |
| 90 |
return `${base}${delimiter}${url}`; |
| 91 |
} |
| 92 |
|
| 93 |
// src/query/utils/getOrInsert.ts |
| 94 |
function getOrInsert(map, key, value) { |
| 95 |
if (map.has(key)) return map.get(key); |
| 96 |
return map.set(key, value).get(key); |
| 97 |
} |
| 98 |
|
| 99 |
// src/query/fetchBaseQuery.ts |
| 100 |
var defaultFetchFn = (...args) => fetch(...args); |
| 101 |
var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299; |
| 102 |
var defaultIsJsonContentType = (headers) => ( |
| 103 |
/*applicat*/ |
| 104 |
/ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "") |
| 105 |
); |
| 106 |
function stripUndefined(obj) { |
| 107 |
if (!isPlainObject(obj)) { |
| 108 |
return obj; |
| 109 |
} |
| 110 |
const copy = { |
| 111 |
...obj |
| 112 |
}; |
| 113 |
for (const [k, v] of Object.entries(copy)) { |
| 114 |
if (v === void 0) delete copy[k]; |
| 115 |
} |
| 116 |
return copy; |
| 117 |
} |
| 118 |
function fetchBaseQuery({ |
| 119 |
baseUrl, |
| 120 |
prepareHeaders = (x) => x, |
| 121 |
fetchFn = defaultFetchFn, |
| 122 |
paramsSerializer, |
| 123 |
isJsonContentType = defaultIsJsonContentType, |
| 124 |
jsonContentType = "application/json", |
| 125 |
jsonReplacer, |
| 126 |
timeout: defaultTimeout, |
| 127 |
responseHandler: globalResponseHandler, |
| 128 |
validateStatus: globalValidateStatus, |
| 129 |
...baseFetchOptions |
| 130 |
} = {}) { |
| 131 |
if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) { |
| 132 |
console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."); |
| 133 |
} |
| 134 |
return async (arg, api, extraOptions) => { |
| 135 |
const { |
| 136 |
getState, |
| 137 |
extra, |
| 138 |
endpoint, |
| 139 |
forced, |
| 140 |
type |
| 141 |
} = api; |
| 142 |
let meta; |
| 143 |
let { |
| 144 |
url, |
| 145 |
headers = new Headers(baseFetchOptions.headers), |
| 146 |
params = void 0, |
| 147 |
responseHandler = globalResponseHandler ?? "json", |
| 148 |
validateStatus = globalValidateStatus ?? defaultValidateStatus, |
| 149 |
timeout = defaultTimeout, |
| 150 |
...rest |
| 151 |
} = typeof arg == "string" ? { |
| 152 |
url: arg |
| 153 |
} : arg; |
| 154 |
let abortController, signal = api.signal; |
| 155 |
if (timeout) { |
| 156 |
abortController = new AbortController(); |
| 157 |
api.signal.addEventListener("abort", abortController.abort); |
| 158 |
signal = abortController.signal; |
| 159 |
} |
| 160 |
let config = { |
| 161 |
...baseFetchOptions, |
| 162 |
signal, |
| 163 |
...rest |
| 164 |
}; |
| 165 |
headers = new Headers(stripUndefined(headers)); |
| 166 |
config.headers = await prepareHeaders(headers, { |
| 167 |
getState, |
| 168 |
arg, |
| 169 |
extra, |
| 170 |
endpoint, |
| 171 |
forced, |
| 172 |
type, |
| 173 |
extraOptions |
| 174 |
}) || headers; |
| 175 |
const isJsonifiable = (body) => typeof body === "object" && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === "function"); |
| 176 |
if (!config.headers.has("content-type") && isJsonifiable(config.body)) { |
| 177 |
config.headers.set("content-type", jsonContentType); |
| 178 |
} |
| 179 |
if (isJsonifiable(config.body) && isJsonContentType(config.headers)) { |
| 180 |
config.body = JSON.stringify(config.body, jsonReplacer); |
| 181 |
} |
| 182 |
if (params) { |
| 183 |
const divider = ~url.indexOf("?") ? "&" : "?"; |
| 184 |
const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params)); |
| 185 |
url += divider + query; |
| 186 |
} |
| 187 |
url = joinUrls(baseUrl, url); |
| 188 |
const request = new Request(url, config); |
| 189 |
const requestClone = new Request(url, config); |
| 190 |
meta = { |
| 191 |
request: requestClone |
| 192 |
}; |
| 193 |
let response, timedOut = false, timeoutId = abortController && setTimeout(() => { |
| 194 |
timedOut = true; |
| 195 |
abortController.abort(); |
| 196 |
}, timeout); |
| 197 |
try { |
| 198 |
response = await fetchFn(request); |
| 199 |
} catch (e) { |
| 200 |
return { |
| 201 |
error: { |
| 202 |
status: timedOut ? "TIMEOUT_ERROR" : "FETCH_ERROR", |
| 203 |
error: String(e) |
| 204 |
}, |
| 205 |
meta |
| 206 |
}; |
| 207 |
} finally { |
| 208 |
if (timeoutId) clearTimeout(timeoutId); |
| 209 |
abortController?.signal.removeEventListener("abort", abortController.abort); |
| 210 |
} |
| 211 |
const responseClone = response.clone(); |
| 212 |
meta.response = responseClone; |
| 213 |
let resultData; |
| 214 |
let responseText = ""; |
| 215 |
try { |
| 216 |
let handleResponseError; |
| 217 |
await Promise.all([ |
| 218 |
handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e), |
| 219 |
// see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182 |
| 220 |
// we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios |
| 221 |
responseClone.text().then((r) => responseText = r, () => { |
| 222 |
}) |
| 223 |
]); |
| 224 |
if (handleResponseError) throw handleResponseError; |
| 225 |
} catch (e) { |
| 226 |
return { |
| 227 |
error: { |
| 228 |
status: "PARSING_ERROR", |
| 229 |
originalStatus: response.status, |
| 230 |
data: responseText, |
| 231 |
error: String(e) |
| 232 |
}, |
| 233 |
meta |
| 234 |
}; |
| 235 |
} |
| 236 |
return validateStatus(response, resultData) ? { |
| 237 |
data: resultData, |
| 238 |
meta |
| 239 |
} : { |
| 240 |
error: { |
| 241 |
status: response.status, |
| 242 |
data: resultData |
| 243 |
}, |
| 244 |
meta |
| 245 |
}; |
| 246 |
}; |
| 247 |
async function handleResponse(response, responseHandler) { |
| 248 |
if (typeof responseHandler === "function") { |
| 249 |
return responseHandler(response); |
| 250 |
} |
| 251 |
if (responseHandler === "content-type") { |
| 252 |
responseHandler = isJsonContentType(response.headers) ? "json" : "text"; |
| 253 |
} |
| 254 |
if (responseHandler === "json") { |
| 255 |
const text = await response.text(); |
| 256 |
return text.length ? JSON.parse(text) : null; |
| 257 |
} |
| 258 |
return response.text(); |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
// src/query/HandledError.ts |
| 263 |
var HandledError = class { |
| 264 |
constructor(value, meta = void 0) { |
| 265 |
this.value = value; |
| 266 |
this.meta = meta; |
| 267 |
} |
| 268 |
}; |
| 269 |
|
| 270 |
// src/query/retry.ts |
| 271 |
async function defaultBackoff(attempt = 0, maxRetries = 5) { |
| 272 |
const attempts = Math.min(attempt, maxRetries); |
| 273 |
const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); |
| 274 |
await new Promise((resolve) => setTimeout((res) => resolve(res), timeout)); |
| 275 |
} |
| 276 |
function fail(error, meta) { |
| 277 |
throw Object.assign(new HandledError({ |
| 278 |
error, |
| 279 |
meta |
| 280 |
}), { |
| 281 |
throwImmediately: true |
| 282 |
}); |
| 283 |
} |
| 284 |
var EMPTY_OPTIONS = {}; |
| 285 |
var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => { |
| 286 |
const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0); |
| 287 |
const [maxRetries] = possibleMaxRetries.slice(-1); |
| 288 |
const defaultRetryCondition = (_, __, { |
| 289 |
attempt |
| 290 |
}) => attempt <= maxRetries; |
| 291 |
const options = { |
| 292 |
maxRetries, |
| 293 |
backoff: defaultBackoff, |
| 294 |
retryCondition: defaultRetryCondition, |
| 295 |
...defaultOptions, |
| 296 |
...extraOptions |
| 297 |
}; |
| 298 |
let retry2 = 0; |
| 299 |
while (true) { |
| 300 |
try { |
| 301 |
const result = await baseQuery(args, api, extraOptions); |
| 302 |
if (result.error) { |
| 303 |
throw new HandledError(result); |
| 304 |
} |
| 305 |
return result; |
| 306 |
} catch (e) { |
| 307 |
retry2++; |
| 308 |
if (e.throwImmediately) { |
| 309 |
if (e instanceof HandledError) { |
| 310 |
return e.value; |
| 311 |
} |
| 312 |
throw e; |
| 313 |
} |
| 314 |
if (e instanceof HandledError && !options.retryCondition(e.value.error, args, { |
| 315 |
attempt: retry2, |
| 316 |
baseQueryApi: api, |
| 317 |
extraOptions |
| 318 |
})) { |
| 319 |
return e.value; |
| 320 |
} |
| 321 |
await options.backoff(retry2, options.maxRetries); |
| 322 |
} |
| 323 |
} |
| 324 |
}; |
| 325 |
var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { |
| 326 |
fail |
| 327 |
}); |
| 328 |
|
| 329 |
// src/query/core/setupListeners.ts |
| 330 |
var onFocus = /* @__PURE__ */ createAction("__rtkq/focused"); |
| 331 |
var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused"); |
| 332 |
var onOnline = /* @__PURE__ */ createAction("__rtkq/online"); |
| 333 |
var onOffline = /* @__PURE__ */ createAction("__rtkq/offline"); |
| 334 |
var initialized = false; |
| 335 |
function setupListeners(dispatch, customHandler) { |
| 336 |
function defaultHandler() { |
| 337 |
const handleFocus = () => dispatch(onFocus()); |
| 338 |
const handleFocusLost = () => dispatch(onFocusLost()); |
| 339 |
const handleOnline = () => dispatch(onOnline()); |
| 340 |
const handleOffline = () => dispatch(onOffline()); |
| 341 |
const handleVisibilityChange = () => { |
| 342 |
if (window.document.visibilityState === "visible") { |
| 343 |
handleFocus(); |
| 344 |
} else { |
| 345 |
handleFocusLost(); |
| 346 |
} |
| 347 |
}; |
| 348 |
if (!initialized) { |
| 349 |
if (typeof window !== "undefined" && window.addEventListener) { |
| 350 |
window.addEventListener("visibilitychange", handleVisibilityChange, false); |
| 351 |
window.addEventListener("focus", handleFocus, false); |
| 352 |
window.addEventListener("online", handleOnline, false); |
| 353 |
window.addEventListener("offline", handleOffline, false); |
| 354 |
initialized = true; |
| 355 |
} |
| 356 |
} |
| 357 |
const unsubscribe = () => { |
| 358 |
window.removeEventListener("focus", handleFocus); |
| 359 |
window.removeEventListener("visibilitychange", handleVisibilityChange); |
| 360 |
window.removeEventListener("online", handleOnline); |
| 361 |
window.removeEventListener("offline", handleOffline); |
| 362 |
initialized = false; |
| 363 |
}; |
| 364 |
return unsubscribe; |
| 365 |
} |
| 366 |
return customHandler ? customHandler(dispatch, { |
| 367 |
onFocus, |
| 368 |
onFocusLost, |
| 369 |
onOffline, |
| 370 |
onOnline |
| 371 |
}) : defaultHandler(); |
| 372 |
} |
| 373 |
|
| 374 |
// src/query/endpointDefinitions.ts |
| 375 |
function isQueryDefinition(e) { |
| 376 |
return e.type === "query" /* query */; |
| 377 |
} |
| 378 |
function isMutationDefinition(e) { |
| 379 |
return e.type === "mutation" /* mutation */; |
| 380 |
} |
| 381 |
function isInfiniteQueryDefinition(e) { |
| 382 |
return e.type === "infinitequery" /* infinitequery */; |
| 383 |
} |
| 384 |
function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) { |
| 385 |
if (isFunction(description)) { |
| 386 |
return description(result, error, queryArg, meta).filter(isNotNullish).map(expandTagDescription).map(assertTagTypes); |
| 387 |
} |
| 388 |
if (Array.isArray(description)) { |
| 389 |
return description.map(expandTagDescription).map(assertTagTypes); |
| 390 |
} |
| 391 |
return []; |
| 392 |
} |
| 393 |
function isFunction(t) { |
| 394 |
return typeof t === "function"; |
| 395 |
} |
| 396 |
function expandTagDescription(description) { |
| 397 |
return typeof description === "string" ? { |
| 398 |
type: description |
| 399 |
} : description; |
| 400 |
} |
| 401 |
|
| 402 |
// src/query/core/buildThunks.ts |
| 403 |
import { isDraftable, produceWithPatches } from "immer"; |
| 404 |
|
| 405 |
// src/query/core/buildInitiate.ts |
| 406 |
import { formatProdErrorMessage as _formatProdErrorMessage } from "@reduxjs/toolkit"; |
| 407 |
|
| 408 |
// src/tsHelpers.ts |
| 409 |
function asSafePromise(promise, fallback) { |
| 410 |
return promise.catch(fallback); |
| 411 |
} |
| 412 |
|
| 413 |
// src/query/core/buildInitiate.ts |
| 414 |
var forceQueryFnSymbol = Symbol("forceQueryFn"); |
| 415 |
var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function"; |
| 416 |
function buildInitiate({ |
| 417 |
serializeQueryArgs, |
| 418 |
queryThunk, |
| 419 |
infiniteQueryThunk, |
| 420 |
mutationThunk, |
| 421 |
api, |
| 422 |
context |
| 423 |
}) { |
| 424 |
const runningQueries = /* @__PURE__ */ new Map(); |
| 425 |
const runningMutations = /* @__PURE__ */ new Map(); |
| 426 |
const { |
| 427 |
unsubscribeQueryResult, |
| 428 |
removeMutationResult, |
| 429 |
updateSubscriptionOptions |
| 430 |
} = api.internalActions; |
| 431 |
return { |
| 432 |
buildInitiateQuery, |
| 433 |
buildInitiateInfiniteQuery, |
| 434 |
buildInitiateMutation, |
| 435 |
getRunningQueryThunk, |
| 436 |
getRunningMutationThunk, |
| 437 |
getRunningQueriesThunk, |
| 438 |
getRunningMutationsThunk |
| 439 |
}; |
| 440 |
function getRunningQueryThunk(endpointName, queryArgs) { |
| 441 |
return (dispatch) => { |
| 442 |
const endpointDefinition = context.endpointDefinitions[endpointName]; |
| 443 |
const queryCacheKey = serializeQueryArgs({ |
| 444 |
queryArgs, |
| 445 |
endpointDefinition, |
| 446 |
endpointName |
| 447 |
}); |
| 448 |
return runningQueries.get(dispatch)?.[queryCacheKey]; |
| 449 |
}; |
| 450 |
} |
| 451 |
function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) { |
| 452 |
return (dispatch) => { |
| 453 |
return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId]; |
| 454 |
}; |
| 455 |
} |
| 456 |
function getRunningQueriesThunk() { |
| 457 |
return (dispatch) => Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish); |
| 458 |
} |
| 459 |
function getRunningMutationsThunk() { |
| 460 |
return (dispatch) => Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish); |
| 461 |
} |
| 462 |
function middlewareWarning(dispatch) { |
| 463 |
if (process.env.NODE_ENV !== "production") { |
| 464 |
if (middlewareWarning.triggered) return; |
| 465 |
const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions()); |
| 466 |
middlewareWarning.triggered = true; |
| 467 |
if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") { |
| 468 |
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store. |
| 469 |
You must add the middleware for RTK-Query to function correctly!`); |
| 470 |
} |
| 471 |
} |
| 472 |
} |
| 473 |
function buildInitiateAnyQuery(endpointName, endpointDefinition) { |
| 474 |
const queryAction = (arg, { |
| 475 |
subscribe = true, |
| 476 |
forceRefetch, |
| 477 |
subscriptionOptions, |
| 478 |
[forceQueryFnSymbol]: forceQueryFn, |
| 479 |
...rest |
| 480 |
} = {}) => (dispatch, getState) => { |
| 481 |
const queryCacheKey = serializeQueryArgs({ |
| 482 |
queryArgs: arg, |
| 483 |
endpointDefinition, |
| 484 |
endpointName |
| 485 |
}); |
| 486 |
let thunk; |
| 487 |
const commonThunkArgs = { |
| 488 |
...rest, |
| 489 |
type: "query", |
| 490 |
subscribe, |
| 491 |
forceRefetch, |
| 492 |
subscriptionOptions, |
| 493 |
endpointName, |
| 494 |
originalArgs: arg, |
| 495 |
queryCacheKey, |
| 496 |
[forceQueryFnSymbol]: forceQueryFn |
| 497 |
}; |
| 498 |
if (isQueryDefinition(endpointDefinition)) { |
| 499 |
thunk = queryThunk(commonThunkArgs); |
| 500 |
} else { |
| 501 |
const { |
| 502 |
direction, |
| 503 |
initialPageParam |
| 504 |
} = rest; |
| 505 |
thunk = infiniteQueryThunk({ |
| 506 |
...commonThunkArgs, |
| 507 |
// Supply these even if undefined. This helps with a field existence |
| 508 |
// check over in `buildSlice.ts` |
| 509 |
direction, |
| 510 |
initialPageParam |
| 511 |
}); |
| 512 |
} |
| 513 |
const selector = api.endpoints[endpointName].select(arg); |
| 514 |
const thunkResult = dispatch(thunk); |
| 515 |
const stateAfter = selector(getState()); |
| 516 |
middlewareWarning(dispatch); |
| 517 |
const { |
| 518 |
requestId, |
| 519 |
abort |
| 520 |
} = thunkResult; |
| 521 |
const skippedSynchronously = stateAfter.requestId !== requestId; |
| 522 |
const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey]; |
| 523 |
const selectFromState = () => selector(getState()); |
| 524 |
const statePromise = Object.assign(forceQueryFn ? ( |
| 525 |
// a query has been forced (upsertQueryData) |
| 526 |
// -> we want to resolve it once data has been written with the data that will be written |
| 527 |
thunkResult.then(selectFromState) |
| 528 |
) : skippedSynchronously && !runningQuery ? ( |
| 529 |
// a query has been skipped due to a condition and we do not have any currently running query |
| 530 |
// -> we want to resolve it immediately with the current data |
| 531 |
Promise.resolve(stateAfter) |
| 532 |
) : ( |
| 533 |
// query just started or one is already in flight |
| 534 |
// -> wait for the running query, then resolve with data from after that |
| 535 |
Promise.all([runningQuery, thunkResult]).then(selectFromState) |
| 536 |
), { |
| 537 |
arg, |
| 538 |
requestId, |
| 539 |
subscriptionOptions, |
| 540 |
queryCacheKey, |
| 541 |
abort, |
| 542 |
async unwrap() { |
| 543 |
const result = await statePromise; |
| 544 |
if (result.isError) { |
| 545 |
throw result.error; |
| 546 |
} |
| 547 |
return result.data; |
| 548 |
}, |
| 549 |
refetch: () => dispatch(queryAction(arg, { |
| 550 |
subscribe: false, |
| 551 |
forceRefetch: true |
| 552 |
})), |
| 553 |
unsubscribe() { |
| 554 |
if (subscribe) dispatch(unsubscribeQueryResult({ |
| 555 |
queryCacheKey, |
| 556 |
requestId |
| 557 |
})); |
| 558 |
}, |
| 559 |
updateSubscriptionOptions(options) { |
| 560 |
statePromise.subscriptionOptions = options; |
| 561 |
dispatch(updateSubscriptionOptions({ |
| 562 |
endpointName, |
| 563 |
requestId, |
| 564 |
queryCacheKey, |
| 565 |
options |
| 566 |
})); |
| 567 |
} |
| 568 |
}); |
| 569 |
if (!runningQuery && !skippedSynchronously && !forceQueryFn) { |
| 570 |
const running = getOrInsert(runningQueries, dispatch, {}); |
| 571 |
running[queryCacheKey] = statePromise; |
| 572 |
statePromise.then(() => { |
| 573 |
delete running[queryCacheKey]; |
| 574 |
if (!countObjectKeys(running)) { |
| 575 |
runningQueries.delete(dispatch); |
| 576 |
} |
| 577 |
}); |
| 578 |
} |
| 579 |
return statePromise; |
| 580 |
}; |
| 581 |
return queryAction; |
| 582 |
} |
| 583 |
function buildInitiateQuery(endpointName, endpointDefinition) { |
| 584 |
const queryAction = buildInitiateAnyQuery(endpointName, endpointDefinition); |
| 585 |
return queryAction; |
| 586 |
} |
| 587 |
function buildInitiateInfiniteQuery(endpointName, endpointDefinition) { |
| 588 |
const infiniteQueryAction = buildInitiateAnyQuery(endpointName, endpointDefinition); |
| 589 |
return infiniteQueryAction; |
| 590 |
} |
| 591 |
function buildInitiateMutation(endpointName) { |
| 592 |
return (arg, { |
| 593 |
track = true, |
| 594 |
fixedCacheKey |
| 595 |
} = {}) => (dispatch, getState) => { |
| 596 |
const thunk = mutationThunk({ |
| 597 |
type: "mutation", |
| 598 |
endpointName, |
| 599 |
originalArgs: arg, |
| 600 |
track, |
| 601 |
fixedCacheKey |
| 602 |
}); |
| 603 |
const thunkResult = dispatch(thunk); |
| 604 |
middlewareWarning(dispatch); |
| 605 |
const { |
| 606 |
requestId, |
| 607 |
abort, |
| 608 |
unwrap |
| 609 |
} = thunkResult; |
| 610 |
const returnValuePromise = asSafePromise(thunkResult.unwrap().then((data) => ({ |
| 611 |
data |
| 612 |
})), (error) => ({ |
| 613 |
error |
| 614 |
})); |
| 615 |
const reset = () => { |
| 616 |
dispatch(removeMutationResult({ |
| 617 |
requestId, |
| 618 |
fixedCacheKey |
| 619 |
})); |
| 620 |
}; |
| 621 |
const ret = Object.assign(returnValuePromise, { |
| 622 |
arg: thunkResult.arg, |
| 623 |
requestId, |
| 624 |
abort, |
| 625 |
unwrap, |
| 626 |
reset |
| 627 |
}); |
| 628 |
const running = runningMutations.get(dispatch) || {}; |
| 629 |
runningMutations.set(dispatch, running); |
| 630 |
running[requestId] = ret; |
| 631 |
ret.then(() => { |
| 632 |
delete running[requestId]; |
| 633 |
if (!countObjectKeys(running)) { |
| 634 |
runningMutations.delete(dispatch); |
| 635 |
} |
| 636 |
}); |
| 637 |
if (fixedCacheKey) { |
| 638 |
running[fixedCacheKey] = ret; |
| 639 |
ret.then(() => { |
| 640 |
if (running[fixedCacheKey] === ret) { |
| 641 |
delete running[fixedCacheKey]; |
| 642 |
if (!countObjectKeys(running)) { |
| 643 |
runningMutations.delete(dispatch); |
| 644 |
} |
| 645 |
} |
| 646 |
}); |
| 647 |
} |
| 648 |
return ret; |
| 649 |
}; |
| 650 |
} |
| 651 |
} |
| 652 |
|
| 653 |
// src/query/core/buildThunks.ts |
| 654 |
function defaultTransformResponse(baseQueryReturnValue) { |
| 655 |
return baseQueryReturnValue; |
| 656 |
} |
| 657 |
var addShouldAutoBatch = (arg = {}) => { |
| 658 |
return { |
| 659 |
...arg, |
| 660 |
[SHOULD_AUTOBATCH]: true |
| 661 |
}; |
| 662 |
}; |
| 663 |
function buildThunks({ |
| 664 |
reducerPath, |
| 665 |
baseQuery, |
| 666 |
context: { |
| 667 |
endpointDefinitions |
| 668 |
}, |
| 669 |
serializeQueryArgs, |
| 670 |
api, |
| 671 |
assertTagType, |
| 672 |
selectors |
| 673 |
}) { |
| 674 |
const patchQueryData = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => { |
| 675 |
const endpointDefinition = endpointDefinitions[endpointName]; |
| 676 |
const queryCacheKey = serializeQueryArgs({ |
| 677 |
queryArgs: arg, |
| 678 |
endpointDefinition, |
| 679 |
endpointName |
| 680 |
}); |
| 681 |
dispatch(api.internalActions.queryResultPatched({ |
| 682 |
queryCacheKey, |
| 683 |
patches |
| 684 |
})); |
| 685 |
if (!updateProvided) { |
| 686 |
return; |
| 687 |
} |
| 688 |
const newValue = api.endpoints[endpointName].select(arg)( |
| 689 |
// Work around TS 4.1 mismatch |
| 690 |
getState() |
| 691 |
); |
| 692 |
const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType); |
| 693 |
dispatch(api.internalActions.updateProvidedBy({ |
| 694 |
queryCacheKey, |
| 695 |
providedTags |
| 696 |
})); |
| 697 |
}; |
| 698 |
function addToStart(items, item, max = 0) { |
| 699 |
const newItems = [item, ...items]; |
| 700 |
return max && newItems.length > max ? newItems.slice(0, -1) : newItems; |
| 701 |
} |
| 702 |
function addToEnd(items, item, max = 0) { |
| 703 |
const newItems = [...items, item]; |
| 704 |
return max && newItems.length > max ? newItems.slice(1) : newItems; |
| 705 |
} |
| 706 |
const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => { |
| 707 |
const endpointDefinition = api.endpoints[endpointName]; |
| 708 |
const currentState = endpointDefinition.select(arg)( |
| 709 |
// Work around TS 4.1 mismatch |
| 710 |
getState() |
| 711 |
); |
| 712 |
const ret = { |
| 713 |
patches: [], |
| 714 |
inversePatches: [], |
| 715 |
undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided)) |
| 716 |
}; |
| 717 |
if (currentState.status === "uninitialized" /* uninitialized */) { |
| 718 |
return ret; |
| 719 |
} |
| 720 |
let newValue; |
| 721 |
if ("data" in currentState) { |
| 722 |
if (isDraftable(currentState.data)) { |
| 723 |
const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe); |
| 724 |
ret.patches.push(...patches); |
| 725 |
ret.inversePatches.push(...inversePatches); |
| 726 |
newValue = value; |
| 727 |
} else { |
| 728 |
newValue = updateRecipe(currentState.data); |
| 729 |
ret.patches.push({ |
| 730 |
op: "replace", |
| 731 |
path: [], |
| 732 |
value: newValue |
| 733 |
}); |
| 734 |
ret.inversePatches.push({ |
| 735 |
op: "replace", |
| 736 |
path: [], |
| 737 |
value: currentState.data |
| 738 |
}); |
| 739 |
} |
| 740 |
} |
| 741 |
if (ret.patches.length === 0) { |
| 742 |
return ret; |
| 743 |
} |
| 744 |
dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided)); |
| 745 |
return ret; |
| 746 |
}; |
| 747 |
const upsertQueryData = (endpointName, arg, value) => (dispatch) => { |
| 748 |
const res = dispatch(api.endpoints[endpointName].initiate(arg, { |
| 749 |
subscribe: false, |
| 750 |
forceRefetch: true, |
| 751 |
[forceQueryFnSymbol]: () => ({ |
| 752 |
data: value |
| 753 |
}) |
| 754 |
})); |
| 755 |
return res; |
| 756 |
}; |
| 757 |
const getTransformCallbackForEndpoint = (endpointDefinition, transformFieldName) => { |
| 758 |
return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName] : defaultTransformResponse; |
| 759 |
}; |
| 760 |
const executeEndpoint = async (arg, { |
| 761 |
signal, |
| 762 |
abort, |
| 763 |
rejectWithValue, |
| 764 |
fulfillWithValue, |
| 765 |
dispatch, |
| 766 |
getState, |
| 767 |
extra |
| 768 |
}) => { |
| 769 |
const endpointDefinition = endpointDefinitions[arg.endpointName]; |
| 770 |
try { |
| 771 |
let transformResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformResponse"); |
| 772 |
const baseQueryApi = { |
| 773 |
signal, |
| 774 |
abort, |
| 775 |
dispatch, |
| 776 |
getState, |
| 777 |
extra, |
| 778 |
endpoint: arg.endpointName, |
| 779 |
type: arg.type, |
| 780 |
forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0, |
| 781 |
queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0 |
| 782 |
}; |
| 783 |
const forceQueryFn = arg.type === "query" ? arg[forceQueryFnSymbol] : void 0; |
| 784 |
let finalQueryReturnValue; |
| 785 |
const fetchPage = async (data, param, maxPages, previous) => { |
| 786 |
if (param == null && data.pages.length) { |
| 787 |
return Promise.resolve({ |
| 788 |
data |
| 789 |
}); |
| 790 |
} |
| 791 |
const finalQueryArg = { |
| 792 |
queryArg: arg.originalArgs, |
| 793 |
pageParam: param |
| 794 |
}; |
| 795 |
const pageResponse = await executeRequest(finalQueryArg); |
| 796 |
const addTo = previous ? addToStart : addToEnd; |
| 797 |
return { |
| 798 |
data: { |
| 799 |
pages: addTo(data.pages, pageResponse.data, maxPages), |
| 800 |
pageParams: addTo(data.pageParams, param, maxPages) |
| 801 |
} |
| 802 |
}; |
| 803 |
}; |
| 804 |
async function executeRequest(finalQueryArg) { |
| 805 |
let result; |
| 806 |
const { |
| 807 |
extraOptions |
| 808 |
} = endpointDefinition; |
| 809 |
if (forceQueryFn) { |
| 810 |
result = forceQueryFn(); |
| 811 |
} else if (endpointDefinition.query) { |
| 812 |
result = await baseQuery(endpointDefinition.query(finalQueryArg), baseQueryApi, extraOptions); |
| 813 |
} else { |
| 814 |
result = await endpointDefinition.queryFn(finalQueryArg, baseQueryApi, extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, extraOptions)); |
| 815 |
} |
| 816 |
if (typeof process !== "undefined" && process.env.NODE_ENV === "development") { |
| 817 |
const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`"; |
| 818 |
let err; |
| 819 |
if (!result) { |
| 820 |
err = `${what} did not return anything.`; |
| 821 |
} else if (typeof result !== "object") { |
| 822 |
err = `${what} did not return an object.`; |
| 823 |
} else if (result.error && result.data) { |
| 824 |
err = `${what} returned an object containing both \`error\` and \`result\`.`; |
| 825 |
} else if (result.error === void 0 && result.data === void 0) { |
| 826 |
err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``; |
| 827 |
} else { |
| 828 |
for (const key of Object.keys(result)) { |
| 829 |
if (key !== "error" && key !== "data" && key !== "meta") { |
| 830 |
err = `The object returned by ${what} has the unknown property ${key}.`; |
| 831 |
break; |
| 832 |
} |
| 833 |
} |
| 834 |
} |
| 835 |
if (err) { |
| 836 |
console.error(`Error encountered handling the endpoint ${arg.endpointName}. |
| 837 |
${err} |
| 838 |
It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property. |
| 839 |
Object returned was:`, result); |
| 840 |
} |
| 841 |
} |
| 842 |
if (result.error) throw new HandledError(result.error, result.meta); |
| 843 |
const transformedResponse = await transformResponse(result.data, result.meta, finalQueryArg); |
| 844 |
return { |
| 845 |
...result, |
| 846 |
data: transformedResponse |
| 847 |
}; |
| 848 |
} |
| 849 |
if (arg.type === "query" && "infiniteQueryOptions" in endpointDefinition) { |
| 850 |
const { |
| 851 |
infiniteQueryOptions |
| 852 |
} = endpointDefinition; |
| 853 |
const { |
| 854 |
maxPages = Infinity |
| 855 |
} = infiniteQueryOptions; |
| 856 |
let result; |
| 857 |
const blankData = { |
| 858 |
pages: [], |
| 859 |
pageParams: [] |
| 860 |
}; |
| 861 |
const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data; |
| 862 |
const isForcedQueryNeedingRefetch = ( |
| 863 |
// arg.forceRefetch |
| 864 |
isForcedQuery(arg, getState()) && !arg.direction |
| 865 |
); |
| 866 |
const existingData = isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData; |
| 867 |
if ("direction" in arg && arg.direction && existingData.pages.length) { |
| 868 |
const previous = arg.direction === "backward"; |
| 869 |
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam; |
| 870 |
const param = pageParamFn(infiniteQueryOptions, existingData); |
| 871 |
result = await fetchPage(existingData, param, maxPages, previous); |
| 872 |
} else { |
| 873 |
const { |
| 874 |
initialPageParam = infiniteQueryOptions.initialPageParam |
| 875 |
} = arg; |
| 876 |
const cachedPageParams = cachedData?.pageParams ?? []; |
| 877 |
const firstPageParam = cachedPageParams[0] ?? initialPageParam; |
| 878 |
const totalPages = cachedPageParams.length; |
| 879 |
result = await fetchPage(existingData, firstPageParam, maxPages); |
| 880 |
if (forceQueryFn) { |
| 881 |
result = { |
| 882 |
data: result.data.pages[0] |
| 883 |
}; |
| 884 |
} |
| 885 |
for (let i = 1; i < totalPages; i++) { |
| 886 |
const param = getNextPageParam(infiniteQueryOptions, result.data); |
| 887 |
result = await fetchPage(result.data, param, maxPages); |
| 888 |
} |
| 889 |
} |
| 890 |
finalQueryReturnValue = result; |
| 891 |
} else { |
| 892 |
finalQueryReturnValue = await executeRequest(arg.originalArgs); |
| 893 |
} |
| 894 |
return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({ |
| 895 |
fulfilledTimeStamp: Date.now(), |
| 896 |
baseQueryMeta: finalQueryReturnValue.meta |
| 897 |
})); |
| 898 |
} catch (error) { |
| 899 |
let catchedError = error; |
| 900 |
if (catchedError instanceof HandledError) { |
| 901 |
let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformErrorResponse"); |
| 902 |
try { |
| 903 |
return rejectWithValue(await transformErrorResponse(catchedError.value, catchedError.meta, arg.originalArgs), addShouldAutoBatch({ |
| 904 |
baseQueryMeta: catchedError.meta |
| 905 |
})); |
| 906 |
} catch (e) { |
| 907 |
catchedError = e; |
| 908 |
} |
| 909 |
} |
| 910 |
if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") { |
| 911 |
console.error(`An unhandled error occurred processing a request for the endpoint "${arg.endpointName}". |
| 912 |
In the case of an unhandled error, no tags will be "provided" or "invalidated".`, catchedError); |
| 913 |
} else { |
| 914 |
console.error(catchedError); |
| 915 |
} |
| 916 |
throw catchedError; |
| 917 |
} |
| 918 |
}; |
| 919 |
function isForcedQuery(arg, state) { |
| 920 |
const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey); |
| 921 |
const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange; |
| 922 |
const fulfilledVal = requestState?.fulfilledTimeStamp; |
| 923 |
const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange); |
| 924 |
if (refetchVal) { |
| 925 |
return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal; |
| 926 |
} |
| 927 |
return false; |
| 928 |
} |
| 929 |
const createQueryThunk = () => { |
| 930 |
const generatedQueryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, { |
| 931 |
getPendingMeta({ |
| 932 |
arg |
| 933 |
}) { |
| 934 |
const endpointDefinition = endpointDefinitions[arg.endpointName]; |
| 935 |
return addShouldAutoBatch({ |
| 936 |
startedTimeStamp: Date.now(), |
| 937 |
...isInfiniteQueryDefinition(endpointDefinition) ? { |
| 938 |
direction: arg.direction |
| 939 |
} : {} |
| 940 |
}); |
| 941 |
}, |
| 942 |
condition(queryThunkArg, { |
| 943 |
getState |
| 944 |
}) { |
| 945 |
const state = getState(); |
| 946 |
const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey); |
| 947 |
const fulfilledVal = requestState?.fulfilledTimeStamp; |
| 948 |
const currentArg = queryThunkArg.originalArgs; |
| 949 |
const previousArg = requestState?.originalArgs; |
| 950 |
const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName]; |
| 951 |
const direction = queryThunkArg.direction; |
| 952 |
if (isUpsertQuery(queryThunkArg)) { |
| 953 |
return true; |
| 954 |
} |
| 955 |
if (requestState?.status === "pending") { |
| 956 |
return false; |
| 957 |
} |
| 958 |
if (isForcedQuery(queryThunkArg, state)) { |
| 959 |
return true; |
| 960 |
} |
| 961 |
if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({ |
| 962 |
currentArg, |
| 963 |
previousArg, |
| 964 |
endpointState: requestState, |
| 965 |
state |
| 966 |
})) { |
| 967 |
return true; |
| 968 |
} |
| 969 |
if (fulfilledVal && !direction) { |
| 970 |
return false; |
| 971 |
} |
| 972 |
return true; |
| 973 |
}, |
| 974 |
dispatchConditionRejection: true |
| 975 |
}); |
| 976 |
return generatedQueryThunk; |
| 977 |
}; |
| 978 |
const queryThunk = createQueryThunk(); |
| 979 |
const infiniteQueryThunk = createQueryThunk(); |
| 980 |
const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, { |
| 981 |
getPendingMeta() { |
| 982 |
return addShouldAutoBatch({ |
| 983 |
startedTimeStamp: Date.now() |
| 984 |
}); |
| 985 |
} |
| 986 |
}); |
| 987 |
const hasTheForce = (options) => "force" in options; |
| 988 |
const hasMaxAge = (options) => "ifOlderThan" in options; |
| 989 |
const prefetch = (endpointName, arg, options) => (dispatch, getState) => { |
| 990 |
const force = hasTheForce(options) && options.force; |
| 991 |
const maxAge = hasMaxAge(options) && options.ifOlderThan; |
| 992 |
const queryAction = (force2 = true) => { |
| 993 |
const options2 = { |
| 994 |
forceRefetch: force2, |
| 995 |
isPrefetch: true |
| 996 |
}; |
| 997 |
return api.endpoints[endpointName].initiate(arg, options2); |
| 998 |
}; |
| 999 |
const latestStateValue = api.endpoints[endpointName].select(arg)(getState()); |
| 1000 |
if (force) { |
| 1001 |
dispatch(queryAction()); |
| 1002 |
} else if (maxAge) { |
| 1003 |
const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp; |
| 1004 |
if (!lastFulfilledTs) { |
| 1005 |
dispatch(queryAction()); |
| 1006 |
return; |
| 1007 |
} |
| 1008 |
const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge; |
| 1009 |
if (shouldRetrigger) { |
| 1010 |
dispatch(queryAction()); |
| 1011 |
} |
| 1012 |
} else { |
| 1013 |
dispatch(queryAction(false)); |
| 1014 |
} |
| 1015 |
}; |
| 1016 |
function matchesEndpoint(endpointName) { |
| 1017 |
return (action) => action?.meta?.arg?.endpointName === endpointName; |
| 1018 |
} |
| 1019 |
function buildMatchThunkActions(thunk, endpointName) { |
| 1020 |
return { |
| 1021 |
matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)), |
| 1022 |
matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)), |
| 1023 |
matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)) |
| 1024 |
}; |
| 1025 |
} |
| 1026 |
return { |
| 1027 |
queryThunk, |
| 1028 |
mutationThunk, |
| 1029 |
infiniteQueryThunk, |
| 1030 |
prefetch, |
| 1031 |
updateQueryData, |
| 1032 |
upsertQueryData, |
| 1033 |
patchQueryData, |
| 1034 |
buildMatchThunkActions |
| 1035 |
}; |
| 1036 |
} |
| 1037 |
function getNextPageParam(options, { |
| 1038 |
pages, |
| 1039 |
pageParams |
| 1040 |
}) { |
| 1041 |
const lastIndex = pages.length - 1; |
| 1042 |
return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams); |
| 1043 |
} |
| 1044 |
function getPreviousPageParam(options, { |
| 1045 |
pages, |
| 1046 |
pageParams |
| 1047 |
}) { |
| 1048 |
return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams); |
| 1049 |
} |
| 1050 |
function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) { |
| 1051 |
return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType); |
| 1052 |
} |
| 1053 |
|
| 1054 |
// src/query/core/buildSlice.ts |
| 1055 |
import { isDraft } from "immer"; |
| 1056 |
import { applyPatches, original } from "immer"; |
| 1057 |
function updateQuerySubstateIfExists(state, queryCacheKey, update) { |
| 1058 |
const substate = state[queryCacheKey]; |
| 1059 |
if (substate) { |
| 1060 |
update(substate); |
| 1061 |
} |
| 1062 |
} |
| 1063 |
function getMutationCacheKey(id) { |
| 1064 |
return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId; |
| 1065 |
} |
| 1066 |
function updateMutationSubstateIfExists(state, id, update) { |
| 1067 |
const substate = state[getMutationCacheKey(id)]; |
| 1068 |
if (substate) { |
| 1069 |
update(substate); |
| 1070 |
} |
| 1071 |
} |
| 1072 |
var initialState = {}; |
| 1073 |
function buildSlice({ |
| 1074 |
reducerPath, |
| 1075 |
queryThunk, |
| 1076 |
mutationThunk, |
| 1077 |
serializeQueryArgs, |
| 1078 |
context: { |
| 1079 |
endpointDefinitions: definitions, |
| 1080 |
apiUid, |
| 1081 |
extractRehydrationInfo, |
| 1082 |
hasRehydrationInfo |
| 1083 |
}, |
| 1084 |
assertTagType, |
| 1085 |
config |
| 1086 |
}) { |
| 1087 |
const resetApiState = createAction(`${reducerPath}/resetApiState`); |
| 1088 |
function writePendingCacheEntry(draft, arg, upserting, meta) { |
| 1089 |
draft[arg.queryCacheKey] ??= { |
| 1090 |
status: "uninitialized" /* uninitialized */, |
| 1091 |
endpointName: arg.endpointName |
| 1092 |
}; |
| 1093 |
updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => { |
| 1094 |
substate.status = "pending" /* pending */; |
| 1095 |
substate.requestId = upserting && substate.requestId ? ( |
| 1096 |
// for `upsertQuery` **updates**, keep the current `requestId` |
| 1097 |
substate.requestId |
| 1098 |
) : ( |
| 1099 |
// for normal queries or `upsertQuery` **inserts** always update the `requestId` |
| 1100 |
meta.requestId |
| 1101 |
); |
| 1102 |
if (arg.originalArgs !== void 0) { |
| 1103 |
substate.originalArgs = arg.originalArgs; |
| 1104 |
} |
| 1105 |
substate.startedTimeStamp = meta.startedTimeStamp; |
| 1106 |
const endpointDefinition = definitions[meta.arg.endpointName]; |
| 1107 |
if (isInfiniteQueryDefinition(endpointDefinition) && "direction" in arg) { |
| 1108 |
; |
| 1109 |
substate.direction = arg.direction; |
| 1110 |
} |
| 1111 |
}); |
| 1112 |
} |
| 1113 |
function writeFulfilledCacheEntry(draft, meta, payload, upserting) { |
| 1114 |
updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => { |
| 1115 |
if (substate.requestId !== meta.requestId && !upserting) return; |
| 1116 |
const { |
| 1117 |
merge |
| 1118 |
} = definitions[meta.arg.endpointName]; |
| 1119 |
substate.status = "fulfilled" /* fulfilled */; |
| 1120 |
if (merge) { |
| 1121 |
if (substate.data !== void 0) { |
| 1122 |
const { |
| 1123 |
fulfilledTimeStamp, |
| 1124 |
arg, |
| 1125 |
baseQueryMeta, |
| 1126 |
requestId |
| 1127 |
} = meta; |
| 1128 |
let newData = createNextState(substate.data, (draftSubstateData) => { |
| 1129 |
return merge(draftSubstateData, payload, { |
| 1130 |
arg: arg.originalArgs, |
| 1131 |
baseQueryMeta, |
| 1132 |
fulfilledTimeStamp, |
| 1133 |
requestId |
| 1134 |
}); |
| 1135 |
}); |
| 1136 |
substate.data = newData; |
| 1137 |
} else { |
| 1138 |
substate.data = payload; |
| 1139 |
} |
| 1140 |
} else { |
| 1141 |
substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload; |
| 1142 |
} |
| 1143 |
delete substate.error; |
| 1144 |
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp; |
| 1145 |
}); |
| 1146 |
} |
| 1147 |
const querySlice = createSlice({ |
| 1148 |
name: `${reducerPath}/queries`, |
| 1149 |
initialState, |
| 1150 |
reducers: { |
| 1151 |
removeQueryResult: { |
| 1152 |
reducer(draft, { |
| 1153 |
payload: { |
| 1154 |
queryCacheKey |
| 1155 |
} |
| 1156 |
}) { |
| 1157 |
delete draft[queryCacheKey]; |
| 1158 |
}, |
| 1159 |
prepare: prepareAutoBatched() |
| 1160 |
}, |
| 1161 |
cacheEntriesUpserted: { |
| 1162 |
reducer(draft, action) { |
| 1163 |
for (const entry of action.payload) { |
| 1164 |
const { |
| 1165 |
queryDescription: arg, |
| 1166 |
value |
| 1167 |
} = entry; |
| 1168 |
writePendingCacheEntry(draft, arg, true, { |
| 1169 |
arg, |
| 1170 |
requestId: action.meta.requestId, |
| 1171 |
startedTimeStamp: action.meta.timestamp |
| 1172 |
}); |
| 1173 |
writeFulfilledCacheEntry( |
| 1174 |
draft, |
| 1175 |
{ |
| 1176 |
arg, |
| 1177 |
requestId: action.meta.requestId, |
| 1178 |
fulfilledTimeStamp: action.meta.timestamp, |
| 1179 |
baseQueryMeta: {} |
| 1180 |
}, |
| 1181 |
value, |
| 1182 |
// We know we're upserting here |
| 1183 |
true |
| 1184 |
); |
| 1185 |
} |
| 1186 |
}, |
| 1187 |
prepare: (payload) => { |
| 1188 |
const queryDescriptions = payload.map((entry) => { |
| 1189 |
const { |
| 1190 |
endpointName, |
| 1191 |
arg, |
| 1192 |
value |
| 1193 |
} = entry; |
| 1194 |
const endpointDefinition = definitions[endpointName]; |
| 1195 |
const queryDescription = { |
| 1196 |
type: "query", |
| 1197 |
endpointName, |
| 1198 |
originalArgs: entry.arg, |
| 1199 |
queryCacheKey: serializeQueryArgs({ |
| 1200 |
queryArgs: arg, |
| 1201 |
endpointDefinition, |
| 1202 |
endpointName |
| 1203 |
}) |
| 1204 |
}; |
| 1205 |
return { |
| 1206 |
queryDescription, |
| 1207 |
value |
| 1208 |
}; |
| 1209 |
}); |
| 1210 |
const result = { |
| 1211 |
payload: queryDescriptions, |
| 1212 |
meta: { |
| 1213 |
[SHOULD_AUTOBATCH]: true, |
| 1214 |
requestId: nanoid(), |
| 1215 |
timestamp: Date.now() |
| 1216 |
} |
| 1217 |
}; |
| 1218 |
return result; |
| 1219 |
} |
| 1220 |
}, |
| 1221 |
queryResultPatched: { |
| 1222 |
reducer(draft, { |
| 1223 |
payload: { |
| 1224 |
queryCacheKey, |
| 1225 |
patches |
| 1226 |
} |
| 1227 |
}) { |
| 1228 |
updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => { |
| 1229 |
substate.data = applyPatches(substate.data, patches.concat()); |
| 1230 |
}); |
| 1231 |
}, |
| 1232 |
prepare: prepareAutoBatched() |
| 1233 |
} |
| 1234 |
}, |
| 1235 |
extraReducers(builder) { |
| 1236 |
builder.addCase(queryThunk.pending, (draft, { |
| 1237 |
meta, |
| 1238 |
meta: { |
| 1239 |
arg |
| 1240 |
} |
| 1241 |
}) => { |
| 1242 |
const upserting = isUpsertQuery(arg); |
| 1243 |
writePendingCacheEntry(draft, arg, upserting, meta); |
| 1244 |
}).addCase(queryThunk.fulfilled, (draft, { |
| 1245 |
meta, |
| 1246 |
payload |
| 1247 |
}) => { |
| 1248 |
const upserting = isUpsertQuery(meta.arg); |
| 1249 |
writeFulfilledCacheEntry(draft, meta, payload, upserting); |
| 1250 |
}).addCase(queryThunk.rejected, (draft, { |
| 1251 |
meta: { |
| 1252 |
condition, |
| 1253 |
arg, |
| 1254 |
requestId |
| 1255 |
}, |
| 1256 |
error, |
| 1257 |
payload |
| 1258 |
}) => { |
| 1259 |
updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => { |
| 1260 |
if (condition) { |
| 1261 |
} else { |
| 1262 |
if (substate.requestId !== requestId) return; |
| 1263 |
substate.status = "rejected" /* rejected */; |
| 1264 |
substate.error = payload ?? error; |
| 1265 |
} |
| 1266 |
}); |
| 1267 |
}).addMatcher(hasRehydrationInfo, (draft, action) => { |
| 1268 |
const { |
| 1269 |
queries |
| 1270 |
} = extractRehydrationInfo(action); |
| 1271 |
for (const [key, entry] of Object.entries(queries)) { |
| 1272 |
if ( |
| 1273 |
// do not rehydrate entries that were currently in flight. |
| 1274 |
entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */ |
| 1275 |
) { |
| 1276 |
draft[key] = entry; |
| 1277 |
} |
| 1278 |
} |
| 1279 |
}); |
| 1280 |
} |
| 1281 |
}); |
| 1282 |
const mutationSlice = createSlice({ |
| 1283 |
name: `${reducerPath}/mutations`, |
| 1284 |
initialState, |
| 1285 |
reducers: { |
| 1286 |
removeMutationResult: { |
| 1287 |
reducer(draft, { |
| 1288 |
payload |
| 1289 |
}) { |
| 1290 |
const cacheKey = getMutationCacheKey(payload); |
| 1291 |
if (cacheKey in draft) { |
| 1292 |
delete draft[cacheKey]; |
| 1293 |
} |
| 1294 |
}, |
| 1295 |
prepare: prepareAutoBatched() |
| 1296 |
} |
| 1297 |
}, |
| 1298 |
extraReducers(builder) { |
| 1299 |
builder.addCase(mutationThunk.pending, (draft, { |
| 1300 |
meta, |
| 1301 |
meta: { |
| 1302 |
requestId, |
| 1303 |
arg, |
| 1304 |
startedTimeStamp |
| 1305 |
} |
| 1306 |
}) => { |
| 1307 |
if (!arg.track) return; |
| 1308 |
draft[getMutationCacheKey(meta)] = { |
| 1309 |
requestId, |
| 1310 |
status: "pending" /* pending */, |
| 1311 |
endpointName: arg.endpointName, |
| 1312 |
startedTimeStamp |
| 1313 |
}; |
| 1314 |
}).addCase(mutationThunk.fulfilled, (draft, { |
| 1315 |
payload, |
| 1316 |
meta |
| 1317 |
}) => { |
| 1318 |
if (!meta.arg.track) return; |
| 1319 |
updateMutationSubstateIfExists(draft, meta, (substate) => { |
| 1320 |
if (substate.requestId !== meta.requestId) return; |
| 1321 |
substate.status = "fulfilled" /* fulfilled */; |
| 1322 |
substate.data = payload; |
| 1323 |
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp; |
| 1324 |
}); |
| 1325 |
}).addCase(mutationThunk.rejected, (draft, { |
| 1326 |
payload, |
| 1327 |
error, |
| 1328 |
meta |
| 1329 |
}) => { |
| 1330 |
if (!meta.arg.track) return; |
| 1331 |
updateMutationSubstateIfExists(draft, meta, (substate) => { |
| 1332 |
if (substate.requestId !== meta.requestId) return; |
| 1333 |
substate.status = "rejected" /* rejected */; |
| 1334 |
substate.error = payload ?? error; |
| 1335 |
}); |
| 1336 |
}).addMatcher(hasRehydrationInfo, (draft, action) => { |
| 1337 |
const { |
| 1338 |
mutations |
| 1339 |
} = extractRehydrationInfo(action); |
| 1340 |
for (const [key, entry] of Object.entries(mutations)) { |
| 1341 |
if ( |
| 1342 |
// do not rehydrate entries that were currently in flight. |
| 1343 |
(entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */) && // only rehydrate endpoints that were persisted using a `fixedCacheKey` |
| 1344 |
key !== entry?.requestId |
| 1345 |
) { |
| 1346 |
draft[key] = entry; |
| 1347 |
} |
| 1348 |
} |
| 1349 |
}); |
| 1350 |
} |
| 1351 |
}); |
| 1352 |
const invalidationSlice = createSlice({ |
| 1353 |
name: `${reducerPath}/invalidation`, |
| 1354 |
initialState, |
| 1355 |
reducers: { |
| 1356 |
updateProvidedBy: { |
| 1357 |
reducer(draft, action) { |
| 1358 |
const { |
| 1359 |
queryCacheKey, |
| 1360 |
providedTags |
| 1361 |
} = action.payload; |
| 1362 |
for (const tagTypeSubscriptions of Object.values(draft)) { |
| 1363 |
for (const idSubscriptions of Object.values(tagTypeSubscriptions)) { |
| 1364 |
const foundAt = idSubscriptions.indexOf(queryCacheKey); |
| 1365 |
if (foundAt !== -1) { |
| 1366 |
idSubscriptions.splice(foundAt, 1); |
| 1367 |
} |
| 1368 |
} |
| 1369 |
} |
| 1370 |
for (const { |
| 1371 |
type, |
| 1372 |
id |
| 1373 |
} of providedTags) { |
| 1374 |
const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= []; |
| 1375 |
const alreadySubscribed = subscribedQueries.includes(queryCacheKey); |
| 1376 |
if (!alreadySubscribed) { |
| 1377 |
subscribedQueries.push(queryCacheKey); |
| 1378 |
} |
| 1379 |
} |
| 1380 |
}, |
| 1381 |
prepare: prepareAutoBatched() |
| 1382 |
} |
| 1383 |
}, |
| 1384 |
extraReducers(builder) { |
| 1385 |
builder.addCase(querySlice.actions.removeQueryResult, (draft, { |
| 1386 |
payload: { |
| 1387 |
queryCacheKey |
| 1388 |
} |
| 1389 |
}) => { |
| 1390 |
for (const tagTypeSubscriptions of Object.values(draft)) { |
| 1391 |
for (const idSubscriptions of Object.values(tagTypeSubscriptions)) { |
| 1392 |
const foundAt = idSubscriptions.indexOf(queryCacheKey); |
| 1393 |
if (foundAt !== -1) { |
| 1394 |
idSubscriptions.splice(foundAt, 1); |
| 1395 |
} |
| 1396 |
} |
| 1397 |
} |
| 1398 |
}).addMatcher(hasRehydrationInfo, (draft, action) => { |
| 1399 |
const { |
| 1400 |
provided |
| 1401 |
} = extractRehydrationInfo(action); |
| 1402 |
for (const [type, incomingTags] of Object.entries(provided)) { |
| 1403 |
for (const [id, cacheKeys] of Object.entries(incomingTags)) { |
| 1404 |
const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= []; |
| 1405 |
for (const queryCacheKey of cacheKeys) { |
| 1406 |
const alreadySubscribed = subscribedQueries.includes(queryCacheKey); |
| 1407 |
if (!alreadySubscribed) { |
| 1408 |
subscribedQueries.push(queryCacheKey); |
| 1409 |
} |
| 1410 |
} |
| 1411 |
} |
| 1412 |
} |
| 1413 |
}).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => { |
| 1414 |
writeProvidedTagsForQuery(draft, action); |
| 1415 |
}).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => { |
| 1416 |
for (const { |
| 1417 |
queryDescription: arg, |
| 1418 |
value |
| 1419 |
} of action.payload) { |
| 1420 |
const action2 = { |
| 1421 |
type: "UNKNOWN", |
| 1422 |
payload: value, |
| 1423 |
meta: { |
| 1424 |
requestStatus: "fulfilled", |
| 1425 |
requestId: "UNKNOWN", |
| 1426 |
arg |
| 1427 |
} |
| 1428 |
}; |
| 1429 |
writeProvidedTagsForQuery(draft, action2); |
| 1430 |
} |
| 1431 |
}); |
| 1432 |
} |
| 1433 |
}); |
| 1434 |
function writeProvidedTagsForQuery(draft, action) { |
| 1435 |
const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType); |
| 1436 |
const { |
| 1437 |
queryCacheKey |
| 1438 |
} = action.meta.arg; |
| 1439 |
invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy({ |
| 1440 |
queryCacheKey, |
| 1441 |
providedTags |
| 1442 |
})); |
| 1443 |
} |
| 1444 |
const subscriptionSlice = createSlice({ |
| 1445 |
name: `${reducerPath}/subscriptions`, |
| 1446 |
initialState, |
| 1447 |
reducers: { |
| 1448 |
updateSubscriptionOptions(d, a) { |
| 1449 |
}, |
| 1450 |
unsubscribeQueryResult(d, a) { |
| 1451 |
}, |
| 1452 |
internal_getRTKQSubscriptions() { |
| 1453 |
} |
| 1454 |
} |
| 1455 |
}); |
| 1456 |
const internalSubscriptionsSlice = createSlice({ |
| 1457 |
name: `${reducerPath}/internalSubscriptions`, |
| 1458 |
initialState, |
| 1459 |
reducers: { |
| 1460 |
subscriptionsUpdated: { |
| 1461 |
reducer(state, action) { |
| 1462 |
return applyPatches(state, action.payload); |
| 1463 |
}, |
| 1464 |
prepare: prepareAutoBatched() |
| 1465 |
} |
| 1466 |
} |
| 1467 |
}); |
| 1468 |
const configSlice = createSlice({ |
| 1469 |
name: `${reducerPath}/config`, |
| 1470 |
initialState: { |
| 1471 |
online: isOnline(), |
| 1472 |
focused: isDocumentVisible(), |
| 1473 |
middlewareRegistered: false, |
| 1474 |
...config |
| 1475 |
}, |
| 1476 |
reducers: { |
| 1477 |
middlewareRegistered(state, { |
| 1478 |
payload |
| 1479 |
}) { |
| 1480 |
state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true; |
| 1481 |
} |
| 1482 |
}, |
| 1483 |
extraReducers: (builder) => { |
| 1484 |
builder.addCase(onOnline, (state) => { |
| 1485 |
state.online = true; |
| 1486 |
}).addCase(onOffline, (state) => { |
| 1487 |
state.online = false; |
| 1488 |
}).addCase(onFocus, (state) => { |
| 1489 |
state.focused = true; |
| 1490 |
}).addCase(onFocusLost, (state) => { |
| 1491 |
state.focused = false; |
| 1492 |
}).addMatcher(hasRehydrationInfo, (draft) => ({ |
| 1493 |
...draft |
| 1494 |
})); |
| 1495 |
} |
| 1496 |
}); |
| 1497 |
const combinedReducer = combineReducers({ |
| 1498 |
queries: querySlice.reducer, |
| 1499 |
mutations: mutationSlice.reducer, |
| 1500 |
provided: invalidationSlice.reducer, |
| 1501 |
subscriptions: internalSubscriptionsSlice.reducer, |
| 1502 |
config: configSlice.reducer |
| 1503 |
}); |
| 1504 |
const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action); |
| 1505 |
const actions = { |
| 1506 |
...configSlice.actions, |
| 1507 |
...querySlice.actions, |
| 1508 |
...subscriptionSlice.actions, |
| 1509 |
...internalSubscriptionsSlice.actions, |
| 1510 |
...mutationSlice.actions, |
| 1511 |
...invalidationSlice.actions, |
| 1512 |
resetApiState |
| 1513 |
}; |
| 1514 |
return { |
| 1515 |
reducer, |
| 1516 |
actions |
| 1517 |
}; |
| 1518 |
} |
| 1519 |
|
| 1520 |
// src/query/core/buildSelectors.ts |
| 1521 |
var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken"); |
| 1522 |
var initialSubState = { |
| 1523 |
status: "uninitialized" /* uninitialized */ |
| 1524 |
}; |
| 1525 |
var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => { |
| 1526 |
}); |
| 1527 |
var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, () => { |
| 1528 |
}); |
| 1529 |
function buildSelectors({ |
| 1530 |
serializeQueryArgs, |
| 1531 |
reducerPath, |
| 1532 |
createSelector: createSelector2 |
| 1533 |
}) { |
| 1534 |
const selectSkippedQuery = (state) => defaultQuerySubState; |
| 1535 |
const selectSkippedMutation = (state) => defaultMutationSubState; |
| 1536 |
return { |
| 1537 |
buildQuerySelector, |
| 1538 |
buildInfiniteQuerySelector, |
| 1539 |
buildMutationSelector, |
| 1540 |
selectInvalidatedBy, |
| 1541 |
selectCachedArgsForQuery, |
| 1542 |
selectApiState, |
| 1543 |
selectQueries, |
| 1544 |
selectMutations, |
| 1545 |
selectQueryEntry, |
| 1546 |
selectConfig |
| 1547 |
}; |
| 1548 |
function withRequestFlags(substate) { |
| 1549 |
return { |
| 1550 |
...substate, |
| 1551 |
...getRequestStatusFlags(substate.status) |
| 1552 |
}; |
| 1553 |
} |
| 1554 |
function selectApiState(rootState) { |
| 1555 |
const state = rootState[reducerPath]; |
| 1556 |
if (process.env.NODE_ENV !== "production") { |
| 1557 |
if (!state) { |
| 1558 |
if (selectApiState.triggered) return state; |
| 1559 |
selectApiState.triggered = true; |
| 1560 |
console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`); |
| 1561 |
} |
| 1562 |
} |
| 1563 |
return state; |
| 1564 |
} |
| 1565 |
function selectQueries(rootState) { |
| 1566 |
return selectApiState(rootState)?.queries; |
| 1567 |
} |
| 1568 |
function selectQueryEntry(rootState, cacheKey) { |
| 1569 |
return selectQueries(rootState)?.[cacheKey]; |
| 1570 |
} |
| 1571 |
function selectMutations(rootState) { |
| 1572 |
return selectApiState(rootState)?.mutations; |
| 1573 |
} |
| 1574 |
function selectConfig(rootState) { |
| 1575 |
return selectApiState(rootState)?.config; |
| 1576 |
} |
| 1577 |
function buildAnyQuerySelector(endpointName, endpointDefinition, combiner) { |
| 1578 |
return (queryArgs) => { |
| 1579 |
if (queryArgs === skipToken) { |
| 1580 |
return createSelector2(selectSkippedQuery, combiner); |
| 1581 |
} |
| 1582 |
const serializedArgs = serializeQueryArgs({ |
| 1583 |
queryArgs, |
| 1584 |
endpointDefinition, |
| 1585 |
endpointName |
| 1586 |
}); |
| 1587 |
const selectQuerySubstate = (state) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState; |
| 1588 |
return createSelector2(selectQuerySubstate, combiner); |
| 1589 |
}; |
| 1590 |
} |
| 1591 |
function buildQuerySelector(endpointName, endpointDefinition) { |
| 1592 |
return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags); |
| 1593 |
} |
| 1594 |
function buildInfiniteQuerySelector(endpointName, endpointDefinition) { |
| 1595 |
const { |
| 1596 |
infiniteQueryOptions |
| 1597 |
} = endpointDefinition; |
| 1598 |
function withInfiniteQueryResultFlags(substate) { |
| 1599 |
const stateWithRequestFlags = { |
| 1600 |
...substate, |
| 1601 |
...getRequestStatusFlags(substate.status) |
| 1602 |
}; |
| 1603 |
const { |
| 1604 |
isLoading, |
| 1605 |
isError, |
| 1606 |
direction |
| 1607 |
} = stateWithRequestFlags; |
| 1608 |
const isForward = direction === "forward"; |
| 1609 |
const isBackward = direction === "backward"; |
| 1610 |
return { |
| 1611 |
...stateWithRequestFlags, |
| 1612 |
hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data), |
| 1613 |
hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data), |
| 1614 |
isFetchingNextPage: isLoading && isForward, |
| 1615 |
isFetchingPreviousPage: isLoading && isBackward, |
| 1616 |
isFetchNextPageError: isError && isForward, |
| 1617 |
isFetchPreviousPageError: isError && isBackward |
| 1618 |
}; |
| 1619 |
} |
| 1620 |
return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags); |
| 1621 |
} |
| 1622 |
function buildMutationSelector() { |
| 1623 |
return (id) => { |
| 1624 |
let mutationId; |
| 1625 |
if (typeof id === "object") { |
| 1626 |
mutationId = getMutationCacheKey(id) ?? skipToken; |
| 1627 |
} else { |
| 1628 |
mutationId = id; |
| 1629 |
} |
| 1630 |
const selectMutationSubstate = (state) => selectApiState(state)?.mutations?.[mutationId] ?? defaultMutationSubState; |
| 1631 |
const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate; |
| 1632 |
return createSelector2(finalSelectMutationSubstate, withRequestFlags); |
| 1633 |
}; |
| 1634 |
} |
| 1635 |
function selectInvalidatedBy(state, tags) { |
| 1636 |
const apiState = state[reducerPath]; |
| 1637 |
const toInvalidate = /* @__PURE__ */ new Set(); |
| 1638 |
for (const tag of tags.filter(isNotNullish).map(expandTagDescription)) { |
| 1639 |
const provided = apiState.provided[tag.type]; |
| 1640 |
if (!provided) { |
| 1641 |
continue; |
| 1642 |
} |
| 1643 |
let invalidateSubscriptions = (tag.id !== void 0 ? ( |
| 1644 |
// id given: invalidate all queries that provide this type & id |
| 1645 |
provided[tag.id] |
| 1646 |
) : ( |
| 1647 |
// no id: invalidate all queries that provide this type |
| 1648 |
flatten(Object.values(provided)) |
| 1649 |
)) ?? []; |
| 1650 |
for (const invalidate of invalidateSubscriptions) { |
| 1651 |
toInvalidate.add(invalidate); |
| 1652 |
} |
| 1653 |
} |
| 1654 |
return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => { |
| 1655 |
const querySubState = apiState.queries[queryCacheKey]; |
| 1656 |
return querySubState ? [{ |
| 1657 |
queryCacheKey, |
| 1658 |
endpointName: querySubState.endpointName, |
| 1659 |
originalArgs: querySubState.originalArgs |
| 1660 |
}] : []; |
| 1661 |
})); |
| 1662 |
} |
| 1663 |
function selectCachedArgsForQuery(state, queryName) { |
| 1664 |
return Object.values(selectQueries(state)).filter((entry) => entry?.endpointName === queryName && entry.status !== "uninitialized" /* uninitialized */).map((entry) => entry.originalArgs); |
| 1665 |
} |
| 1666 |
function getHasNextPage(options, data) { |
| 1667 |
if (!data) return false; |
| 1668 |
return getNextPageParam(options, data) != null; |
| 1669 |
} |
| 1670 |
function getHasPreviousPage(options, data) { |
| 1671 |
if (!data || !options.getPreviousPageParam) return false; |
| 1672 |
return getPreviousPageParam(options, data) != null; |
| 1673 |
} |
| 1674 |
} |
| 1675 |
|
| 1676 |
// src/query/createApi.ts |
| 1677 |
import { formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage22, formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit"; |
| 1678 |
|
| 1679 |
// src/query/defaultSerializeQueryArgs.ts |
| 1680 |
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0; |
| 1681 |
var defaultSerializeQueryArgs = ({ |
| 1682 |
endpointName, |
| 1683 |
queryArgs |
| 1684 |
}) => { |
| 1685 |
let serialized = ""; |
| 1686 |
const cached = cache?.get(queryArgs); |
| 1687 |
if (typeof cached === "string") { |
| 1688 |
serialized = cached; |
| 1689 |
} else { |
| 1690 |
const stringified = JSON.stringify(queryArgs, (key, value) => { |
| 1691 |
value = typeof value === "bigint" ? { |
| 1692 |
$bigint: value.toString() |
| 1693 |
} : value; |
| 1694 |
value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => { |
| 1695 |
acc[key2] = value[key2]; |
| 1696 |
return acc; |
| 1697 |
}, {}) : value; |
| 1698 |
return value; |
| 1699 |
}); |
| 1700 |
if (isPlainObject(queryArgs)) { |
| 1701 |
cache?.set(queryArgs, stringified); |
| 1702 |
} |
| 1703 |
serialized = stringified; |
| 1704 |
} |
| 1705 |
return `${endpointName}(${serialized})`; |
| 1706 |
}; |
| 1707 |
|
| 1708 |
// src/query/createApi.ts |
| 1709 |
import { weakMapMemoize } from "reselect"; |
| 1710 |
function buildCreateApi(...modules) { |
| 1711 |
return function baseCreateApi(options) { |
| 1712 |
const extractRehydrationInfo = weakMapMemoize((action) => options.extractRehydrationInfo?.(action, { |
| 1713 |
reducerPath: options.reducerPath ?? "api" |
| 1714 |
})); |
| 1715 |
const optionsWithDefaults = { |
| 1716 |
reducerPath: "api", |
| 1717 |
keepUnusedDataFor: 60, |
| 1718 |
refetchOnMountOrArgChange: false, |
| 1719 |
refetchOnFocus: false, |
| 1720 |
refetchOnReconnect: false, |
| 1721 |
invalidationBehavior: "delayed", |
| 1722 |
...options, |
| 1723 |
extractRehydrationInfo, |
| 1724 |
serializeQueryArgs(queryArgsApi) { |
| 1725 |
let finalSerializeQueryArgs = defaultSerializeQueryArgs; |
| 1726 |
if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) { |
| 1727 |
const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs; |
| 1728 |
finalSerializeQueryArgs = (queryArgsApi2) => { |
| 1729 |
const initialResult = endpointSQA(queryArgsApi2); |
| 1730 |
if (typeof initialResult === "string") { |
| 1731 |
return initialResult; |
| 1732 |
} else { |
| 1733 |
return defaultSerializeQueryArgs({ |
| 1734 |
...queryArgsApi2, |
| 1735 |
queryArgs: initialResult |
| 1736 |
}); |
| 1737 |
} |
| 1738 |
}; |
| 1739 |
} else if (options.serializeQueryArgs) { |
| 1740 |
finalSerializeQueryArgs = options.serializeQueryArgs; |
| 1741 |
} |
| 1742 |
return finalSerializeQueryArgs(queryArgsApi); |
| 1743 |
}, |
| 1744 |
tagTypes: [...options.tagTypes || []] |
| 1745 |
}; |
| 1746 |
const context = { |
| 1747 |
endpointDefinitions: {}, |
| 1748 |
batch(fn) { |
| 1749 |
fn(); |
| 1750 |
}, |
| 1751 |
apiUid: nanoid(), |
| 1752 |
extractRehydrationInfo, |
| 1753 |
hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null) |
| 1754 |
}; |
| 1755 |
const api = { |
| 1756 |
injectEndpoints, |
| 1757 |
enhanceEndpoints({ |
| 1758 |
addTagTypes, |
| 1759 |
endpoints |
| 1760 |
}) { |
| 1761 |
if (addTagTypes) { |
| 1762 |
for (const eT of addTagTypes) { |
| 1763 |
if (!optionsWithDefaults.tagTypes.includes(eT)) { |
| 1764 |
; |
| 1765 |
optionsWithDefaults.tagTypes.push(eT); |
| 1766 |
} |
| 1767 |
} |
| 1768 |
} |
| 1769 |
if (endpoints) { |
| 1770 |
for (const [endpointName, partialDefinition] of Object.entries(endpoints)) { |
| 1771 |
if (typeof partialDefinition === "function") { |
| 1772 |
partialDefinition(context.endpointDefinitions[endpointName]); |
| 1773 |
} else { |
| 1774 |
Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition); |
| 1775 |
} |
| 1776 |
} |
| 1777 |
} |
| 1778 |
return api; |
| 1779 |
} |
| 1780 |
}; |
| 1781 |
const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context)); |
| 1782 |
function injectEndpoints(inject) { |
| 1783 |
const evaluatedEndpoints = inject.endpoints({ |
| 1784 |
query: (x) => ({ |
| 1785 |
...x, |
| 1786 |
type: "query" /* query */ |
| 1787 |
}), |
| 1788 |
mutation: (x) => ({ |
| 1789 |
...x, |
| 1790 |
type: "mutation" /* mutation */ |
| 1791 |
}), |
| 1792 |
infiniteQuery: (x) => ({ |
| 1793 |
...x, |
| 1794 |
type: "infinitequery" /* infinitequery */ |
| 1795 |
}) |
| 1796 |
}); |
| 1797 |
for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) { |
| 1798 |
if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) { |
| 1799 |
if (inject.overrideExisting === "throw") { |
| 1800 |
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(39) : `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``); |
| 1801 |
} else if (typeof process !== "undefined" && process.env.NODE_ENV === "development") { |
| 1802 |
console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``); |
| 1803 |
} |
| 1804 |
continue; |
| 1805 |
} |
| 1806 |
if (typeof process !== "undefined" && process.env.NODE_ENV === "development") { |
| 1807 |
if (isInfiniteQueryDefinition(definition)) { |
| 1808 |
const { |
| 1809 |
infiniteQueryOptions |
| 1810 |
} = definition; |
| 1811 |
const { |
| 1812 |
maxPages, |
| 1813 |
getPreviousPageParam: getPreviousPageParam2 |
| 1814 |
} = infiniteQueryOptions; |
| 1815 |
if (typeof maxPages === "number") { |
| 1816 |
if (maxPages < 1) { |
| 1817 |
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage22(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`); |
| 1818 |
} |
| 1819 |
if (typeof getPreviousPageParam2 !== "function") { |
| 1820 |
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`); |
| 1821 |
} |
| 1822 |
} |
| 1823 |
} |
| 1824 |
} |
| 1825 |
context.endpointDefinitions[endpointName] = definition; |
| 1826 |
for (const m of initializedModules) { |
| 1827 |
m.injectEndpoint(endpointName, definition); |
| 1828 |
} |
| 1829 |
} |
| 1830 |
return api; |
| 1831 |
} |
| 1832 |
return api.injectEndpoints({ |
| 1833 |
endpoints: options.endpoints |
| 1834 |
}); |
| 1835 |
}; |
| 1836 |
} |
| 1837 |
|
| 1838 |
// src/query/fakeBaseQuery.ts |
| 1839 |
import { formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit"; |
| 1840 |
var _NEVER = /* @__PURE__ */ Symbol(); |
| 1841 |
function fakeBaseQuery() { |
| 1842 |
return function() { |
| 1843 |
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax."); |
| 1844 |
}; |
| 1845 |
} |
| 1846 |
|
| 1847 |
// src/query/core/module.ts |
| 1848 |
import { enablePatches } from "immer"; |
| 1849 |
|
| 1850 |
// src/query/tsHelpers.ts |
| 1851 |
function assertCast(v) { |
| 1852 |
} |
| 1853 |
function safeAssign(target, ...args) { |
| 1854 |
return Object.assign(target, ...args); |
| 1855 |
} |
| 1856 |
|
| 1857 |
// src/query/core/buildMiddleware/batchActions.ts |
| 1858 |
import { produceWithPatches as produceWithPatches2 } from "immer"; |
| 1859 |
var buildBatchedActionsHandler = ({ |
| 1860 |
api, |
| 1861 |
queryThunk, |
| 1862 |
internalState |
| 1863 |
}) => { |
| 1864 |
const subscriptionsPrefix = `${api.reducerPath}/subscriptions`; |
| 1865 |
let previousSubscriptions = null; |
| 1866 |
let updateSyncTimer = null; |
| 1867 |
const { |
| 1868 |
updateSubscriptionOptions, |
| 1869 |
unsubscribeQueryResult |
| 1870 |
} = api.internalActions; |
| 1871 |
const actuallyMutateSubscriptions = (mutableState, action) => { |
| 1872 |
if (updateSubscriptionOptions.match(action)) { |
| 1873 |
const { |
| 1874 |
queryCacheKey, |
| 1875 |
requestId, |
| 1876 |
options |
| 1877 |
} = action.payload; |
| 1878 |
if (mutableState?.[queryCacheKey]?.[requestId]) { |
| 1879 |
mutableState[queryCacheKey][requestId] = options; |
| 1880 |
} |
| 1881 |
return true; |
| 1882 |
} |
| 1883 |
if (unsubscribeQueryResult.match(action)) { |
| 1884 |
const { |
| 1885 |
queryCacheKey, |
| 1886 |
requestId |
| 1887 |
} = action.payload; |
| 1888 |
if (mutableState[queryCacheKey]) { |
| 1889 |
delete mutableState[queryCacheKey][requestId]; |
| 1890 |
} |
| 1891 |
return true; |
| 1892 |
} |
| 1893 |
if (api.internalActions.removeQueryResult.match(action)) { |
| 1894 |
delete mutableState[action.payload.queryCacheKey]; |
| 1895 |
return true; |
| 1896 |
} |
| 1897 |
if (queryThunk.pending.match(action)) { |
| 1898 |
const { |
| 1899 |
meta: { |
| 1900 |
arg, |
| 1901 |
requestId |
| 1902 |
} |
| 1903 |
} = action; |
| 1904 |
const substate = mutableState[arg.queryCacheKey] ??= {}; |
| 1905 |
substate[`${requestId}_running`] = {}; |
| 1906 |
if (arg.subscribe) { |
| 1907 |
substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {}; |
| 1908 |
} |
| 1909 |
return true; |
| 1910 |
} |
| 1911 |
let mutated = false; |
| 1912 |
if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action)) { |
| 1913 |
const state = mutableState[action.meta.arg.queryCacheKey] || {}; |
| 1914 |
const key = `${action.meta.requestId}_running`; |
| 1915 |
mutated ||= !!state[key]; |
| 1916 |
delete state[key]; |
| 1917 |
} |
| 1918 |
if (queryThunk.rejected.match(action)) { |
| 1919 |
const { |
| 1920 |
meta: { |
| 1921 |
condition, |
| 1922 |
arg, |
| 1923 |
requestId |
| 1924 |
} |
| 1925 |
} = action; |
| 1926 |
if (condition && arg.subscribe) { |
| 1927 |
const substate = mutableState[arg.queryCacheKey] ??= {}; |
| 1928 |
substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {}; |
| 1929 |
mutated = true; |
| 1930 |
} |
| 1931 |
} |
| 1932 |
return mutated; |
| 1933 |
}; |
| 1934 |
const getSubscriptions = () => internalState.currentSubscriptions; |
| 1935 |
const getSubscriptionCount = (queryCacheKey) => { |
| 1936 |
const subscriptions = getSubscriptions(); |
| 1937 |
const subscriptionsForQueryArg = subscriptions[queryCacheKey] ?? {}; |
| 1938 |
return countObjectKeys(subscriptionsForQueryArg); |
| 1939 |
}; |
| 1940 |
const isRequestSubscribed = (queryCacheKey, requestId) => { |
| 1941 |
const subscriptions = getSubscriptions(); |
| 1942 |
return !!subscriptions?.[queryCacheKey]?.[requestId]; |
| 1943 |
}; |
| 1944 |
const subscriptionSelectors = { |
| 1945 |
getSubscriptions, |
| 1946 |
getSubscriptionCount, |
| 1947 |
isRequestSubscribed |
| 1948 |
}; |
| 1949 |
return (action, mwApi) => { |
| 1950 |
if (!previousSubscriptions) { |
| 1951 |
previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions)); |
| 1952 |
} |
| 1953 |
if (api.util.resetApiState.match(action)) { |
| 1954 |
previousSubscriptions = internalState.currentSubscriptions = {}; |
| 1955 |
updateSyncTimer = null; |
| 1956 |
return [true, false]; |
| 1957 |
} |
| 1958 |
if (api.internalActions.internal_getRTKQSubscriptions.match(action)) { |
| 1959 |
return [false, subscriptionSelectors]; |
| 1960 |
} |
| 1961 |
const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action); |
| 1962 |
let actionShouldContinue = true; |
| 1963 |
if (didMutate) { |
| 1964 |
if (!updateSyncTimer) { |
| 1965 |
updateSyncTimer = setTimeout(() => { |
| 1966 |
const newSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions)); |
| 1967 |
const [, patches] = produceWithPatches2(previousSubscriptions, () => newSubscriptions); |
| 1968 |
mwApi.next(api.internalActions.subscriptionsUpdated(patches)); |
| 1969 |
previousSubscriptions = newSubscriptions; |
| 1970 |
updateSyncTimer = null; |
| 1971 |
}, 500); |
| 1972 |
} |
| 1973 |
const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix); |
| 1974 |
const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe; |
| 1975 |
actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction; |
| 1976 |
} |
| 1977 |
return [actionShouldContinue, false]; |
| 1978 |
}; |
| 1979 |
}; |
| 1980 |
|
| 1981 |
// src/query/core/buildMiddleware/cacheCollection.ts |
| 1982 |
function isObjectEmpty(obj) { |
| 1983 |
for (const k in obj) { |
| 1984 |
return false; |
| 1985 |
} |
| 1986 |
return true; |
| 1987 |
} |
| 1988 |
var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1; |
| 1989 |
var buildCacheCollectionHandler = ({ |
| 1990 |
reducerPath, |
| 1991 |
api, |
| 1992 |
queryThunk, |
| 1993 |
context, |
| 1994 |
internalState, |
| 1995 |
selectors: { |
| 1996 |
selectQueryEntry, |
| 1997 |
selectConfig |
| 1998 |
} |
| 1999 |
}) => { |
| 2000 |
const { |
| 2001 |
removeQueryResult, |
| 2002 |
unsubscribeQueryResult, |
| 2003 |
cacheEntriesUpserted |
| 2004 |
} = api.internalActions; |
| 2005 |
const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match); |
| 2006 |
function anySubscriptionsRemainingForKey(queryCacheKey) { |
| 2007 |
const subscriptions = internalState.currentSubscriptions[queryCacheKey]; |
| 2008 |
return !!subscriptions && !isObjectEmpty(subscriptions); |
| 2009 |
} |
| 2010 |
const currentRemovalTimeouts = {}; |
| 2011 |
const handler = (action, mwApi, internalState2) => { |
| 2012 |
const state = mwApi.getState(); |
| 2013 |
const config = selectConfig(state); |
| 2014 |
if (canTriggerUnsubscribe(action)) { |
| 2015 |
let queryCacheKeys; |
| 2016 |
if (cacheEntriesUpserted.match(action)) { |
| 2017 |
queryCacheKeys = action.payload.map((entry) => entry.queryDescription.queryCacheKey); |
| 2018 |
} else { |
| 2019 |
const { |
| 2020 |
queryCacheKey |
| 2021 |
} = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg; |
| 2022 |
queryCacheKeys = [queryCacheKey]; |
| 2023 |
} |
| 2024 |
handleUnsubscribeMany(queryCacheKeys, mwApi, config); |
| 2025 |
} |
| 2026 |
if (api.util.resetApiState.match(action)) { |
| 2027 |
for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) { |
| 2028 |
if (timeout) clearTimeout(timeout); |
| 2029 |
delete currentRemovalTimeouts[key]; |
| 2030 |
} |
| 2031 |
} |
| 2032 |
if (context.hasRehydrationInfo(action)) { |
| 2033 |
const { |
| 2034 |
queries |
| 2035 |
} = context.extractRehydrationInfo(action); |
| 2036 |
handleUnsubscribeMany(Object.keys(queries), mwApi, config); |
| 2037 |
} |
| 2038 |
}; |
| 2039 |
function handleUnsubscribeMany(cacheKeys, api2, config) { |
| 2040 |
const state = api2.getState(); |
| 2041 |
for (const queryCacheKey of cacheKeys) { |
| 2042 |
const entry = selectQueryEntry(state, queryCacheKey); |
| 2043 |
handleUnsubscribe(queryCacheKey, entry?.endpointName, api2, config); |
| 2044 |
} |
| 2045 |
} |
| 2046 |
function handleUnsubscribe(queryCacheKey, endpointName, api2, config) { |
| 2047 |
const endpointDefinition = context.endpointDefinitions[endpointName]; |
| 2048 |
const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor; |
| 2049 |
if (keepUnusedDataFor === Infinity) { |
| 2050 |
return; |
| 2051 |
} |
| 2052 |
const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS)); |
| 2053 |
if (!anySubscriptionsRemainingForKey(queryCacheKey)) { |
| 2054 |
const currentTimeout = currentRemovalTimeouts[queryCacheKey]; |
| 2055 |
if (currentTimeout) { |
| 2056 |
clearTimeout(currentTimeout); |
| 2057 |
} |
| 2058 |
currentRemovalTimeouts[queryCacheKey] = setTimeout(() => { |
| 2059 |
if (!anySubscriptionsRemainingForKey(queryCacheKey)) { |
| 2060 |
api2.dispatch(removeQueryResult({ |
| 2061 |
queryCacheKey |
| 2062 |
})); |
| 2063 |
} |
| 2064 |
delete currentRemovalTimeouts[queryCacheKey]; |
| 2065 |
}, finalKeepUnusedDataFor * 1e3); |
| 2066 |
} |
| 2067 |
} |
| 2068 |
return handler; |
| 2069 |
}; |
| 2070 |
|
| 2071 |
// src/query/core/buildMiddleware/cacheLifecycle.ts |
| 2072 |
var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved."); |
| 2073 |
var buildCacheLifecycleHandler = ({ |
| 2074 |
api, |
| 2075 |
reducerPath, |
| 2076 |
context, |
| 2077 |
queryThunk, |
| 2078 |
mutationThunk, |
| 2079 |
internalState, |
| 2080 |
selectors: { |
| 2081 |
selectQueryEntry, |
| 2082 |
selectApiState |
| 2083 |
} |
| 2084 |
}) => { |
| 2085 |
const isQueryThunk = isAsyncThunkAction(queryThunk); |
| 2086 |
const isMutationThunk = isAsyncThunkAction(mutationThunk); |
| 2087 |
const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk); |
| 2088 |
const lifecycleMap = {}; |
| 2089 |
function resolveLifecycleEntry(cacheKey, data, meta) { |
| 2090 |
const lifecycle = lifecycleMap[cacheKey]; |
| 2091 |
if (lifecycle?.valueResolved) { |
| 2092 |
lifecycle.valueResolved({ |
| 2093 |
data, |
| 2094 |
meta |
| 2095 |
}); |
| 2096 |
delete lifecycle.valueResolved; |
| 2097 |
} |
| 2098 |
} |
| 2099 |
function removeLifecycleEntry(cacheKey) { |
| 2100 |
const lifecycle = lifecycleMap[cacheKey]; |
| 2101 |
if (lifecycle) { |
| 2102 |
delete lifecycleMap[cacheKey]; |
| 2103 |
lifecycle.cacheEntryRemoved(); |
| 2104 |
} |
| 2105 |
} |
| 2106 |
const handler = (action, mwApi, stateBefore) => { |
| 2107 |
const cacheKey = getCacheKey(action); |
| 2108 |
function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) { |
| 2109 |
const oldEntry = selectQueryEntry(stateBefore, cacheKey2); |
| 2110 |
const newEntry = selectQueryEntry(mwApi.getState(), cacheKey2); |
| 2111 |
if (!oldEntry && newEntry) { |
| 2112 |
handleNewKey(endpointName, originalArgs, cacheKey2, mwApi, requestId); |
| 2113 |
} |
| 2114 |
} |
| 2115 |
if (queryThunk.pending.match(action)) { |
| 2116 |
checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs); |
| 2117 |
} else if (api.internalActions.cacheEntriesUpserted.match(action)) { |
| 2118 |
for (const { |
| 2119 |
queryDescription, |
| 2120 |
value |
| 2121 |
} of action.payload) { |
| 2122 |
const { |
| 2123 |
endpointName, |
| 2124 |
originalArgs, |
| 2125 |
queryCacheKey |
| 2126 |
} = queryDescription; |
| 2127 |
checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs); |
| 2128 |
resolveLifecycleEntry(queryCacheKey, value, {}); |
| 2129 |
} |
| 2130 |
} else if (mutationThunk.pending.match(action)) { |
| 2131 |
const state = mwApi.getState()[reducerPath].mutations[cacheKey]; |
| 2132 |
if (state) { |
| 2133 |
handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId); |
| 2134 |
} |
| 2135 |
} else if (isFulfilledThunk(action)) { |
| 2136 |
resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta); |
| 2137 |
} else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) { |
| 2138 |
removeLifecycleEntry(cacheKey); |
| 2139 |
} else if (api.util.resetApiState.match(action)) { |
| 2140 |
for (const cacheKey2 of Object.keys(lifecycleMap)) { |
| 2141 |
removeLifecycleEntry(cacheKey2); |
| 2142 |
} |
| 2143 |
} |
| 2144 |
}; |
| 2145 |
function getCacheKey(action) { |
| 2146 |
if (isQueryThunk(action)) return action.meta.arg.queryCacheKey; |
| 2147 |
if (isMutationThunk(action)) { |
| 2148 |
return action.meta.arg.fixedCacheKey ?? action.meta.requestId; |
| 2149 |
} |
| 2150 |
if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey; |
| 2151 |
if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload); |
| 2152 |
return ""; |
| 2153 |
} |
| 2154 |
function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) { |
| 2155 |
const endpointDefinition = context.endpointDefinitions[endpointName]; |
| 2156 |
const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded; |
| 2157 |
if (!onCacheEntryAdded) return; |
| 2158 |
const lifecycle = {}; |
| 2159 |
const cacheEntryRemoved = new Promise((resolve) => { |
| 2160 |
lifecycle.cacheEntryRemoved = resolve; |
| 2161 |
}); |
| 2162 |
const cacheDataLoaded = Promise.race([new Promise((resolve) => { |
| 2163 |
lifecycle.valueResolved = resolve; |
| 2164 |
}), cacheEntryRemoved.then(() => { |
| 2165 |
throw neverResolvedError; |
| 2166 |
})]); |
| 2167 |
cacheDataLoaded.catch(() => { |
| 2168 |
}); |
| 2169 |
lifecycleMap[queryCacheKey] = lifecycle; |
| 2170 |
const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : queryCacheKey); |
| 2171 |
const extra = mwApi.dispatch((_, __, extra2) => extra2); |
| 2172 |
const lifecycleApi = { |
| 2173 |
...mwApi, |
| 2174 |
getCacheEntry: () => selector(mwApi.getState()), |
| 2175 |
requestId, |
| 2176 |
extra, |
| 2177 |
updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0, |
| 2178 |
cacheDataLoaded, |
| 2179 |
cacheEntryRemoved |
| 2180 |
}; |
| 2181 |
const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi); |
| 2182 |
Promise.resolve(runningHandler).catch((e) => { |
| 2183 |
if (e === neverResolvedError) return; |
| 2184 |
throw e; |
| 2185 |
}); |
| 2186 |
} |
| 2187 |
return handler; |
| 2188 |
}; |
| 2189 |
|
| 2190 |
// src/query/core/buildMiddleware/devMiddleware.ts |
| 2191 |
var buildDevCheckHandler = ({ |
| 2192 |
api, |
| 2193 |
context: { |
| 2194 |
apiUid |
| 2195 |
}, |
| 2196 |
reducerPath |
| 2197 |
}) => { |
| 2198 |
return (action, mwApi) => { |
| 2199 |
if (api.util.resetApiState.match(action)) { |
| 2200 |
mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid)); |
| 2201 |
} |
| 2202 |
if (typeof process !== "undefined" && process.env.NODE_ENV === "development") { |
| 2203 |
if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") { |
| 2204 |
console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}". |
| 2205 |
You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? ` |
| 2206 |
If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`); |
| 2207 |
} |
| 2208 |
} |
| 2209 |
}; |
| 2210 |
}; |
| 2211 |
|
| 2212 |
// src/query/core/buildMiddleware/invalidationByTags.ts |
| 2213 |
var buildInvalidationByTagsHandler = ({ |
| 2214 |
reducerPath, |
| 2215 |
context, |
| 2216 |
context: { |
| 2217 |
endpointDefinitions |
| 2218 |
}, |
| 2219 |
mutationThunk, |
| 2220 |
queryThunk, |
| 2221 |
api, |
| 2222 |
assertTagType, |
| 2223 |
refetchQuery, |
| 2224 |
internalState |
| 2225 |
}) => { |
| 2226 |
const { |
| 2227 |
removeQueryResult |
| 2228 |
} = api.internalActions; |
| 2229 |
const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk)); |
| 2230 |
const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk)); |
| 2231 |
let pendingTagInvalidations = []; |
| 2232 |
const handler = (action, mwApi) => { |
| 2233 |
if (isThunkActionWithTags(action)) { |
| 2234 |
invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi); |
| 2235 |
} else if (isQueryEnd(action)) { |
| 2236 |
invalidateTags([], mwApi); |
| 2237 |
} else if (api.util.invalidateTags.match(action)) { |
| 2238 |
invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi); |
| 2239 |
} |
| 2240 |
}; |
| 2241 |
function hasPendingRequests(state) { |
| 2242 |
const { |
| 2243 |
queries, |
| 2244 |
mutations |
| 2245 |
} = state; |
| 2246 |
for (const cacheRecord of [queries, mutations]) { |
| 2247 |
for (const key in cacheRecord) { |
| 2248 |
if (cacheRecord[key]?.status === "pending" /* pending */) return true; |
| 2249 |
} |
| 2250 |
} |
| 2251 |
return false; |
| 2252 |
} |
| 2253 |
function invalidateTags(newTags, mwApi) { |
| 2254 |
const rootState = mwApi.getState(); |
| 2255 |
const state = rootState[reducerPath]; |
| 2256 |
pendingTagInvalidations.push(...newTags); |
| 2257 |
if (state.config.invalidationBehavior === "delayed" && hasPendingRequests(state)) { |
| 2258 |
return; |
| 2259 |
} |
| 2260 |
const tags = pendingTagInvalidations; |
| 2261 |
pendingTagInvalidations = []; |
| 2262 |
if (tags.length === 0) return; |
| 2263 |
const toInvalidate = api.util.selectInvalidatedBy(rootState, tags); |
| 2264 |
context.batch(() => { |
| 2265 |
const valuesArray = Array.from(toInvalidate.values()); |
| 2266 |
for (const { |
| 2267 |
queryCacheKey |
| 2268 |
} of valuesArray) { |
| 2269 |
const querySubState = state.queries[queryCacheKey]; |
| 2270 |
const subscriptionSubState = internalState.currentSubscriptions[queryCacheKey] ?? {}; |
| 2271 |
if (querySubState) { |
| 2272 |
if (countObjectKeys(subscriptionSubState) === 0) { |
| 2273 |
mwApi.dispatch(removeQueryResult({ |
| 2274 |
queryCacheKey |
| 2275 |
})); |
| 2276 |
} else if (querySubState.status !== "uninitialized" /* uninitialized */) { |
| 2277 |
mwApi.dispatch(refetchQuery(querySubState)); |
| 2278 |
} |
| 2279 |
} |
| 2280 |
} |
| 2281 |
}); |
| 2282 |
} |
| 2283 |
return handler; |
| 2284 |
}; |
| 2285 |
|
| 2286 |
// src/query/core/buildMiddleware/polling.ts |
| 2287 |
var buildPollingHandler = ({ |
| 2288 |
reducerPath, |
| 2289 |
queryThunk, |
| 2290 |
api, |
| 2291 |
refetchQuery, |
| 2292 |
internalState |
| 2293 |
}) => { |
| 2294 |
const currentPolls = {}; |
| 2295 |
const handler = (action, mwApi) => { |
| 2296 |
if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) { |
| 2297 |
updatePollingInterval(action.payload, mwApi); |
| 2298 |
} |
| 2299 |
if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) { |
| 2300 |
updatePollingInterval(action.meta.arg, mwApi); |
| 2301 |
} |
| 2302 |
if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) { |
| 2303 |
startNextPoll(action.meta.arg, mwApi); |
| 2304 |
} |
| 2305 |
if (api.util.resetApiState.match(action)) { |
| 2306 |
clearPolls(); |
| 2307 |
} |
| 2308 |
}; |
| 2309 |
function getCacheEntrySubscriptions(queryCacheKey, api2) { |
| 2310 |
const state = api2.getState()[reducerPath]; |
| 2311 |
const querySubState = state.queries[queryCacheKey]; |
| 2312 |
const subscriptions = internalState.currentSubscriptions[queryCacheKey]; |
| 2313 |
if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) return; |
| 2314 |
return subscriptions; |
| 2315 |
} |
| 2316 |
function startNextPoll({ |
| 2317 |
queryCacheKey |
| 2318 |
}, api2) { |
| 2319 |
const state = api2.getState()[reducerPath]; |
| 2320 |
const querySubState = state.queries[queryCacheKey]; |
| 2321 |
const subscriptions = internalState.currentSubscriptions[queryCacheKey]; |
| 2322 |
if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) return; |
| 2323 |
const { |
| 2324 |
lowestPollingInterval, |
| 2325 |
skipPollingIfUnfocused |
| 2326 |
} = findLowestPollingInterval(subscriptions); |
| 2327 |
if (!Number.isFinite(lowestPollingInterval)) return; |
| 2328 |
const currentPoll = currentPolls[queryCacheKey]; |
| 2329 |
if (currentPoll?.timeout) { |
| 2330 |
clearTimeout(currentPoll.timeout); |
| 2331 |
currentPoll.timeout = void 0; |
| 2332 |
} |
| 2333 |
const nextPollTimestamp = Date.now() + lowestPollingInterval; |
| 2334 |
currentPolls[queryCacheKey] = { |
| 2335 |
nextPollTimestamp, |
| 2336 |
pollingInterval: lowestPollingInterval, |
| 2337 |
timeout: setTimeout(() => { |
| 2338 |
if (state.config.focused || !skipPollingIfUnfocused) { |
| 2339 |
api2.dispatch(refetchQuery(querySubState)); |
| 2340 |
} |
| 2341 |
startNextPoll({ |
| 2342 |
queryCacheKey |
| 2343 |
}, api2); |
| 2344 |
}, lowestPollingInterval) |
| 2345 |
}; |
| 2346 |
} |
| 2347 |
function updatePollingInterval({ |
| 2348 |
queryCacheKey |
| 2349 |
}, api2) { |
| 2350 |
const state = api2.getState()[reducerPath]; |
| 2351 |
const querySubState = state.queries[queryCacheKey]; |
| 2352 |
const subscriptions = internalState.currentSubscriptions[queryCacheKey]; |
| 2353 |
if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) { |
| 2354 |
return; |
| 2355 |
} |
| 2356 |
const { |
| 2357 |
lowestPollingInterval |
| 2358 |
} = findLowestPollingInterval(subscriptions); |
| 2359 |
if (!Number.isFinite(lowestPollingInterval)) { |
| 2360 |
cleanupPollForKey(queryCacheKey); |
| 2361 |
return; |
| 2362 |
} |
| 2363 |
const currentPoll = currentPolls[queryCacheKey]; |
| 2364 |
const nextPollTimestamp = Date.now() + lowestPollingInterval; |
| 2365 |
if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) { |
| 2366 |
startNextPoll({ |
| 2367 |
queryCacheKey |
| 2368 |
}, api2); |
| 2369 |
} |
| 2370 |
} |
| 2371 |
function cleanupPollForKey(key) { |
| 2372 |
const existingPoll = currentPolls[key]; |
| 2373 |
if (existingPoll?.timeout) { |
| 2374 |
clearTimeout(existingPoll.timeout); |
| 2375 |
} |
| 2376 |
delete currentPolls[key]; |
| 2377 |
} |
| 2378 |
function clearPolls() { |
| 2379 |
for (const key of Object.keys(currentPolls)) { |
| 2380 |
cleanupPollForKey(key); |
| 2381 |
} |
| 2382 |
} |
| 2383 |
function findLowestPollingInterval(subscribers = {}) { |
| 2384 |
let skipPollingIfUnfocused = false; |
| 2385 |
let lowestPollingInterval = Number.POSITIVE_INFINITY; |
| 2386 |
for (let key in subscribers) { |
| 2387 |
if (!!subscribers[key].pollingInterval) { |
| 2388 |
lowestPollingInterval = Math.min(subscribers[key].pollingInterval, lowestPollingInterval); |
| 2389 |
skipPollingIfUnfocused = subscribers[key].skipPollingIfUnfocused || skipPollingIfUnfocused; |
| 2390 |
} |
| 2391 |
} |
| 2392 |
return { |
| 2393 |
lowestPollingInterval, |
| 2394 |
skipPollingIfUnfocused |
| 2395 |
}; |
| 2396 |
} |
| 2397 |
return handler; |
| 2398 |
}; |
| 2399 |
|
| 2400 |
// src/query/core/buildMiddleware/queryLifecycle.ts |
| 2401 |
var buildQueryLifecycleHandler = ({ |
| 2402 |
api, |
| 2403 |
context, |
| 2404 |
queryThunk, |
| 2405 |
mutationThunk |
| 2406 |
}) => { |
| 2407 |
const isPendingThunk = isPending(queryThunk, mutationThunk); |
| 2408 |
const isRejectedThunk = isRejected(queryThunk, mutationThunk); |
| 2409 |
const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk); |
| 2410 |
const lifecycleMap = {}; |
| 2411 |
const handler = (action, mwApi) => { |
| 2412 |
if (isPendingThunk(action)) { |
| 2413 |
const { |
| 2414 |
requestId, |
| 2415 |
arg: { |
| 2416 |
endpointName, |
| 2417 |
originalArgs |
| 2418 |
} |
| 2419 |
} = action.meta; |
| 2420 |
const endpointDefinition = context.endpointDefinitions[endpointName]; |
| 2421 |
const onQueryStarted = endpointDefinition?.onQueryStarted; |
| 2422 |
if (onQueryStarted) { |
| 2423 |
const lifecycle = {}; |
| 2424 |
const queryFulfilled = new Promise((resolve, reject) => { |
| 2425 |
lifecycle.resolve = resolve; |
| 2426 |
lifecycle.reject = reject; |
| 2427 |
}); |
| 2428 |
queryFulfilled.catch(() => { |
| 2429 |
}); |
| 2430 |
lifecycleMap[requestId] = lifecycle; |
| 2431 |
const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : requestId); |
| 2432 |
const extra = mwApi.dispatch((_, __, extra2) => extra2); |
| 2433 |
const lifecycleApi = { |
| 2434 |
...mwApi, |
| 2435 |
getCacheEntry: () => selector(mwApi.getState()), |
| 2436 |
requestId, |
| 2437 |
extra, |
| 2438 |
updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0, |
| 2439 |
queryFulfilled |
| 2440 |
}; |
| 2441 |
onQueryStarted(originalArgs, lifecycleApi); |
| 2442 |
} |
| 2443 |
} else if (isFullfilledThunk(action)) { |
| 2444 |
const { |
| 2445 |
requestId, |
| 2446 |
baseQueryMeta |
| 2447 |
} = action.meta; |
| 2448 |
lifecycleMap[requestId]?.resolve({ |
| 2449 |
data: action.payload, |
| 2450 |
meta: baseQueryMeta |
| 2451 |
}); |
| 2452 |
delete lifecycleMap[requestId]; |
| 2453 |
} else if (isRejectedThunk(action)) { |
| 2454 |
const { |
| 2455 |
requestId, |
| 2456 |
rejectedWithValue, |
| 2457 |
baseQueryMeta |
| 2458 |
} = action.meta; |
| 2459 |
lifecycleMap[requestId]?.reject({ |
| 2460 |
error: action.payload ?? action.error, |
| 2461 |
isUnhandledError: !rejectedWithValue, |
| 2462 |
meta: baseQueryMeta |
| 2463 |
}); |
| 2464 |
delete lifecycleMap[requestId]; |
| 2465 |
} |
| 2466 |
}; |
| 2467 |
return handler; |
| 2468 |
}; |
| 2469 |
|
| 2470 |
// src/query/core/buildMiddleware/windowEventHandling.ts |
| 2471 |
var buildWindowEventHandler = ({ |
| 2472 |
reducerPath, |
| 2473 |
context, |
| 2474 |
api, |
| 2475 |
refetchQuery, |
| 2476 |
internalState |
| 2477 |
}) => { |
| 2478 |
const { |
| 2479 |
removeQueryResult |
| 2480 |
} = api.internalActions; |
| 2481 |
const handler = (action, mwApi) => { |
| 2482 |
if (onFocus.match(action)) { |
| 2483 |
refetchValidQueries(mwApi, "refetchOnFocus"); |
| 2484 |
} |
| 2485 |
if (onOnline.match(action)) { |
| 2486 |
refetchValidQueries(mwApi, "refetchOnReconnect"); |
| 2487 |
} |
| 2488 |
}; |
| 2489 |
function refetchValidQueries(api2, type) { |
| 2490 |
const state = api2.getState()[reducerPath]; |
| 2491 |
const queries = state.queries; |
| 2492 |
const subscriptions = internalState.currentSubscriptions; |
| 2493 |
context.batch(() => { |
| 2494 |
for (const queryCacheKey of Object.keys(subscriptions)) { |
| 2495 |
const querySubState = queries[queryCacheKey]; |
| 2496 |
const subscriptionSubState = subscriptions[queryCacheKey]; |
| 2497 |
if (!subscriptionSubState || !querySubState) continue; |
| 2498 |
const shouldRefetch = Object.values(subscriptionSubState).some((sub) => sub[type] === true) || Object.values(subscriptionSubState).every((sub) => sub[type] === void 0) && state.config[type]; |
| 2499 |
if (shouldRefetch) { |
| 2500 |
if (countObjectKeys(subscriptionSubState) === 0) { |
| 2501 |
api2.dispatch(removeQueryResult({ |
| 2502 |
queryCacheKey |
| 2503 |
})); |
| 2504 |
} else if (querySubState.status !== "uninitialized" /* uninitialized */) { |
| 2505 |
api2.dispatch(refetchQuery(querySubState)); |
| 2506 |
} |
| 2507 |
} |
| 2508 |
} |
| 2509 |
}); |
| 2510 |
} |
| 2511 |
return handler; |
| 2512 |
}; |
| 2513 |
|
| 2514 |
// src/query/core/buildMiddleware/index.ts |
| 2515 |
function buildMiddleware(input) { |
| 2516 |
const { |
| 2517 |
reducerPath, |
| 2518 |
queryThunk, |
| 2519 |
api, |
| 2520 |
context |
| 2521 |
} = input; |
| 2522 |
const { |
| 2523 |
apiUid |
| 2524 |
} = context; |
| 2525 |
const actions = { |
| 2526 |
invalidateTags: createAction(`${reducerPath}/invalidateTags`) |
| 2527 |
}; |
| 2528 |
const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`); |
| 2529 |
const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler]; |
| 2530 |
const middleware = (mwApi) => { |
| 2531 |
let initialized2 = false; |
| 2532 |
const internalState = { |
| 2533 |
currentSubscriptions: {} |
| 2534 |
}; |
| 2535 |
const builderArgs = { |
| 2536 |
...input, |
| 2537 |
internalState, |
| 2538 |
refetchQuery, |
| 2539 |
isThisApiSliceAction |
| 2540 |
}; |
| 2541 |
const handlers = handlerBuilders.map((build) => build(builderArgs)); |
| 2542 |
const batchedActionsHandler = buildBatchedActionsHandler(builderArgs); |
| 2543 |
const windowEventsHandler = buildWindowEventHandler(builderArgs); |
| 2544 |
return (next) => { |
| 2545 |
return (action) => { |
| 2546 |
if (!isAction(action)) { |
| 2547 |
return next(action); |
| 2548 |
} |
| 2549 |
if (!initialized2) { |
| 2550 |
initialized2 = true; |
| 2551 |
mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid)); |
| 2552 |
} |
| 2553 |
const mwApiWithNext = { |
| 2554 |
...mwApi, |
| 2555 |
next |
| 2556 |
}; |
| 2557 |
const stateBefore = mwApi.getState(); |
| 2558 |
const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore); |
| 2559 |
let res; |
| 2560 |
if (actionShouldContinue) { |
| 2561 |
res = next(action); |
| 2562 |
} else { |
| 2563 |
res = internalProbeResult; |
| 2564 |
} |
| 2565 |
if (!!mwApi.getState()[reducerPath]) { |
| 2566 |
windowEventsHandler(action, mwApiWithNext, stateBefore); |
| 2567 |
if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) { |
| 2568 |
for (const handler of handlers) { |
| 2569 |
handler(action, mwApiWithNext, stateBefore); |
| 2570 |
} |
| 2571 |
} |
| 2572 |
} |
| 2573 |
return res; |
| 2574 |
}; |
| 2575 |
}; |
| 2576 |
}; |
| 2577 |
return { |
| 2578 |
middleware, |
| 2579 |
actions |
| 2580 |
}; |
| 2581 |
function refetchQuery(querySubState) { |
| 2582 |
return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, { |
| 2583 |
subscribe: false, |
| 2584 |
forceRefetch: true |
| 2585 |
}); |
| 2586 |
} |
| 2587 |
} |
| 2588 |
|
| 2589 |
// src/query/core/module.ts |
| 2590 |
var coreModuleName = /* @__PURE__ */ Symbol(); |
| 2591 |
var coreModule = ({ |
| 2592 |
createSelector: createSelector2 = createSelector |
| 2593 |
} = {}) => ({ |
| 2594 |
name: coreModuleName, |
| 2595 |
init(api, { |
| 2596 |
baseQuery, |
| 2597 |
tagTypes, |
| 2598 |
reducerPath, |
| 2599 |
serializeQueryArgs, |
| 2600 |
keepUnusedDataFor, |
| 2601 |
refetchOnMountOrArgChange, |
| 2602 |
refetchOnFocus, |
| 2603 |
refetchOnReconnect, |
| 2604 |
invalidationBehavior |
| 2605 |
}, context) { |
| 2606 |
enablePatches(); |
| 2607 |
assertCast(serializeQueryArgs); |
| 2608 |
const assertTagType = (tag) => { |
| 2609 |
if (typeof process !== "undefined" && process.env.NODE_ENV === "development") { |
| 2610 |
if (!tagTypes.includes(tag.type)) { |
| 2611 |
console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`); |
| 2612 |
} |
| 2613 |
} |
| 2614 |
return tag; |
| 2615 |
}; |
| 2616 |
Object.assign(api, { |
| 2617 |
reducerPath, |
| 2618 |
endpoints: {}, |
| 2619 |
internalActions: { |
| 2620 |
onOnline, |
| 2621 |
onOffline, |
| 2622 |
onFocus, |
| 2623 |
onFocusLost |
| 2624 |
}, |
| 2625 |
util: {} |
| 2626 |
}); |
| 2627 |
const selectors = buildSelectors({ |
| 2628 |
serializeQueryArgs, |
| 2629 |
reducerPath, |
| 2630 |
createSelector: createSelector2 |
| 2631 |
}); |
| 2632 |
const { |
| 2633 |
selectInvalidatedBy, |
| 2634 |
selectCachedArgsForQuery, |
| 2635 |
buildQuerySelector, |
| 2636 |
buildInfiniteQuerySelector, |
| 2637 |
buildMutationSelector |
| 2638 |
} = selectors; |
| 2639 |
safeAssign(api.util, { |
| 2640 |
selectInvalidatedBy, |
| 2641 |
selectCachedArgsForQuery |
| 2642 |
}); |
| 2643 |
const { |
| 2644 |
queryThunk, |
| 2645 |
infiniteQueryThunk, |
| 2646 |
mutationThunk, |
| 2647 |
patchQueryData, |
| 2648 |
updateQueryData, |
| 2649 |
upsertQueryData, |
| 2650 |
prefetch, |
| 2651 |
buildMatchThunkActions |
| 2652 |
} = buildThunks({ |
| 2653 |
baseQuery, |
| 2654 |
reducerPath, |
| 2655 |
context, |
| 2656 |
api, |
| 2657 |
serializeQueryArgs, |
| 2658 |
assertTagType, |
| 2659 |
selectors |
| 2660 |
}); |
| 2661 |
const { |
| 2662 |
reducer, |
| 2663 |
actions: sliceActions |
| 2664 |
} = buildSlice({ |
| 2665 |
context, |
| 2666 |
queryThunk, |
| 2667 |
infiniteQueryThunk, |
| 2668 |
mutationThunk, |
| 2669 |
serializeQueryArgs, |
| 2670 |
reducerPath, |
| 2671 |
assertTagType, |
| 2672 |
config: { |
| 2673 |
refetchOnFocus, |
| 2674 |
refetchOnReconnect, |
| 2675 |
refetchOnMountOrArgChange, |
| 2676 |
keepUnusedDataFor, |
| 2677 |
reducerPath, |
| 2678 |
invalidationBehavior |
| 2679 |
} |
| 2680 |
}); |
| 2681 |
safeAssign(api.util, { |
| 2682 |
patchQueryData, |
| 2683 |
updateQueryData, |
| 2684 |
upsertQueryData, |
| 2685 |
prefetch, |
| 2686 |
resetApiState: sliceActions.resetApiState, |
| 2687 |
upsertQueryEntries: sliceActions.cacheEntriesUpserted |
| 2688 |
}); |
| 2689 |
safeAssign(api.internalActions, sliceActions); |
| 2690 |
const { |
| 2691 |
middleware, |
| 2692 |
actions: middlewareActions |
| 2693 |
} = buildMiddleware({ |
| 2694 |
reducerPath, |
| 2695 |
context, |
| 2696 |
queryThunk, |
| 2697 |
mutationThunk, |
| 2698 |
infiniteQueryThunk, |
| 2699 |
api, |
| 2700 |
assertTagType, |
| 2701 |
selectors |
| 2702 |
}); |
| 2703 |
safeAssign(api.util, middlewareActions); |
| 2704 |
safeAssign(api, { |
| 2705 |
reducer, |
| 2706 |
middleware |
| 2707 |
}); |
| 2708 |
const { |
| 2709 |
buildInitiateQuery, |
| 2710 |
buildInitiateInfiniteQuery, |
| 2711 |
buildInitiateMutation, |
| 2712 |
getRunningMutationThunk, |
| 2713 |
getRunningMutationsThunk, |
| 2714 |
getRunningQueriesThunk, |
| 2715 |
getRunningQueryThunk |
| 2716 |
} = buildInitiate({ |
| 2717 |
queryThunk, |
| 2718 |
mutationThunk, |
| 2719 |
infiniteQueryThunk, |
| 2720 |
api, |
| 2721 |
serializeQueryArgs, |
| 2722 |
context |
| 2723 |
}); |
| 2724 |
safeAssign(api.util, { |
| 2725 |
getRunningMutationThunk, |
| 2726 |
getRunningMutationsThunk, |
| 2727 |
getRunningQueryThunk, |
| 2728 |
getRunningQueriesThunk |
| 2729 |
}); |
| 2730 |
return { |
| 2731 |
name: coreModuleName, |
| 2732 |
injectEndpoint(endpointName, definition) { |
| 2733 |
const anyApi = api; |
| 2734 |
const endpoint = anyApi.endpoints[endpointName] ??= {}; |
| 2735 |
if (isQueryDefinition(definition)) { |
| 2736 |
safeAssign(endpoint, { |
| 2737 |
name: endpointName, |
| 2738 |
select: buildQuerySelector(endpointName, definition), |
| 2739 |
initiate: buildInitiateQuery(endpointName, definition) |
| 2740 |
}, buildMatchThunkActions(queryThunk, endpointName)); |
| 2741 |
} |
| 2742 |
if (isMutationDefinition(definition)) { |
| 2743 |
safeAssign(endpoint, { |
| 2744 |
name: endpointName, |
| 2745 |
select: buildMutationSelector(), |
| 2746 |
initiate: buildInitiateMutation(endpointName) |
| 2747 |
}, buildMatchThunkActions(mutationThunk, endpointName)); |
| 2748 |
} |
| 2749 |
if (isInfiniteQueryDefinition(definition)) { |
| 2750 |
safeAssign(endpoint, { |
| 2751 |
name: endpointName, |
| 2752 |
select: buildInfiniteQuerySelector(endpointName, definition), |
| 2753 |
initiate: buildInitiateInfiniteQuery(endpointName, definition) |
| 2754 |
}, buildMatchThunkActions(queryThunk, endpointName)); |
| 2755 |
} |
| 2756 |
} |
| 2757 |
}; |
| 2758 |
} |
| 2759 |
}); |
| 2760 |
|
| 2761 |
// src/query/core/index.ts |
| 2762 |
var createApi = /* @__PURE__ */ buildCreateApi(coreModule()); |
| 2763 |
export { |
| 2764 |
QueryStatus, |
| 2765 |
_NEVER, |
| 2766 |
buildCreateApi, |
| 2767 |
copyWithStructuralSharing, |
| 2768 |
coreModule, |
| 2769 |
coreModuleName, |
| 2770 |
createApi, |
| 2771 |
defaultSerializeQueryArgs, |
| 2772 |
fakeBaseQuery, |
| 2773 |
fetchBaseQuery, |
| 2774 |
retry, |
| 2775 |
setupListeners, |
| 2776 |
skipToken |
| 2777 |
}; |
| 2778 |
//# sourceMappingURL=rtk-query.modern.mjs.map |