| 1 | /**
|
|---|
| 2 | * Note: this file should import all other files for type discovery and declaration merging
|
|---|
| 3 | */
|
|---|
| 4 | import type {
|
|---|
| 5 | ActionCreatorWithPayload,
|
|---|
| 6 | Dispatch,
|
|---|
| 7 | Middleware,
|
|---|
| 8 | Reducer,
|
|---|
| 9 | ThunkAction,
|
|---|
| 10 | ThunkDispatch,
|
|---|
| 11 | UnknownAction,
|
|---|
| 12 | } from '@reduxjs/toolkit'
|
|---|
| 13 | import { enablePatches } from '../utils/immerImports'
|
|---|
| 14 | import type { Api, Module } from '../apiTypes'
|
|---|
| 15 | import type { BaseQueryFn } from '../baseQueryTypes'
|
|---|
| 16 | import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
|
|---|
| 17 | import type {
|
|---|
| 18 | AssertTagTypes,
|
|---|
| 19 | EndpointDefinitions,
|
|---|
| 20 | InfiniteQueryDefinition,
|
|---|
| 21 | MutationDefinition,
|
|---|
| 22 | QueryArgFrom,
|
|---|
| 23 | QueryArgFromAnyQuery,
|
|---|
| 24 | QueryDefinition,
|
|---|
| 25 | TagDescription,
|
|---|
| 26 | } from '../endpointDefinitions'
|
|---|
| 27 | import {
|
|---|
| 28 | isInfiniteQueryDefinition,
|
|---|
| 29 | isMutationDefinition,
|
|---|
| 30 | isQueryDefinition,
|
|---|
| 31 | } from '../endpointDefinitions'
|
|---|
| 32 | import { assertCast, safeAssign } from '../tsHelpers'
|
|---|
| 33 | import type {
|
|---|
| 34 | CombinedState,
|
|---|
| 35 | MutationKeys,
|
|---|
| 36 | QueryKeys,
|
|---|
| 37 | RootState,
|
|---|
| 38 | } from './apiState'
|
|---|
| 39 | import type {
|
|---|
| 40 | BuildInitiateApiEndpointMutation,
|
|---|
| 41 | BuildInitiateApiEndpointQuery,
|
|---|
| 42 | MutationActionCreatorResult,
|
|---|
| 43 | QueryActionCreatorResult,
|
|---|
| 44 | InfiniteQueryActionCreatorResult,
|
|---|
| 45 | BuildInitiateApiEndpointInfiniteQuery,
|
|---|
| 46 | } from './buildInitiate'
|
|---|
| 47 | import { buildInitiate } from './buildInitiate'
|
|---|
| 48 | import type {
|
|---|
| 49 | ReferenceCacheCollection,
|
|---|
| 50 | ReferenceCacheLifecycle,
|
|---|
| 51 | ReferenceQueryLifecycle,
|
|---|
| 52 | } from './buildMiddleware'
|
|---|
| 53 | import { buildMiddleware } from './buildMiddleware'
|
|---|
| 54 | import type {
|
|---|
| 55 | BuildSelectorsApiEndpointInfiniteQuery,
|
|---|
| 56 | BuildSelectorsApiEndpointMutation,
|
|---|
| 57 | BuildSelectorsApiEndpointQuery,
|
|---|
| 58 | } from './buildSelectors'
|
|---|
| 59 | import { buildSelectors } from './buildSelectors'
|
|---|
| 60 | import type { SliceActions, UpsertEntries } from './buildSlice'
|
|---|
| 61 | import { buildSlice } from './buildSlice'
|
|---|
| 62 | import type {
|
|---|
| 63 | AllQueryKeys,
|
|---|
| 64 | BuildThunksApiEndpointInfiniteQuery,
|
|---|
| 65 | BuildThunksApiEndpointMutation,
|
|---|
| 66 | BuildThunksApiEndpointQuery,
|
|---|
| 67 | PatchQueryDataThunk,
|
|---|
| 68 | QueryArgFromAnyQueryDefinition,
|
|---|
| 69 | UpdateQueryDataThunk,
|
|---|
| 70 | UpsertQueryDataThunk,
|
|---|
| 71 | } from './buildThunks'
|
|---|
| 72 | import { buildThunks } from './buildThunks'
|
|---|
| 73 | import { createSelector as _createSelector } from './rtkImports'
|
|---|
| 74 | import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
|
|---|
| 75 | import type { InternalMiddlewareState } from './buildMiddleware/types'
|
|---|
| 76 | import { getOrInsertComputed } from '../utils'
|
|---|
| 77 | import type { CreateSelectorFunction } from 'reselect'
|
|---|
| 78 |
|
|---|
| 79 | /**
|
|---|
| 80 | * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
|
|---|
| 81 | * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
|
|---|
| 82 | *
|
|---|
| 83 | * @overloadSummary
|
|---|
| 84 | * `force`
|
|---|
| 85 | * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
|
|---|
| 86 | */
|
|---|
| 87 | export type PrefetchOptions =
|
|---|
| 88 | | {
|
|---|
| 89 | ifOlderThan?: false | number
|
|---|
| 90 | }
|
|---|
| 91 | | { force?: boolean }
|
|---|
| 92 |
|
|---|
| 93 | export const coreModuleName = /* @__PURE__ */ Symbol()
|
|---|
| 94 | export type CoreModule =
|
|---|
| 95 | | typeof coreModuleName
|
|---|
| 96 | | ReferenceCacheLifecycle
|
|---|
| 97 | | ReferenceQueryLifecycle
|
|---|
| 98 | | ReferenceCacheCollection
|
|---|
| 99 |
|
|---|
| 100 | export type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>
|
|---|
| 101 |
|
|---|
| 102 | export interface ApiModules<
|
|---|
| 103 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 104 | BaseQuery extends BaseQueryFn,
|
|---|
| 105 | Definitions extends EndpointDefinitions,
|
|---|
| 106 | ReducerPath extends string,
|
|---|
| 107 | TagTypes extends string,
|
|---|
| 108 | > {
|
|---|
| 109 | [coreModuleName]: {
|
|---|
| 110 | /**
|
|---|
| 111 | * This api's reducer should be mounted at `store[api.reducerPath]`.
|
|---|
| 112 | *
|
|---|
| 113 | * @example
|
|---|
| 114 | * ```ts
|
|---|
| 115 | * configureStore({
|
|---|
| 116 | * reducer: {
|
|---|
| 117 | * [api.reducerPath]: api.reducer,
|
|---|
| 118 | * },
|
|---|
| 119 | * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
|
|---|
| 120 | * })
|
|---|
| 121 | * ```
|
|---|
| 122 | */
|
|---|
| 123 | reducerPath: ReducerPath
|
|---|
| 124 | /**
|
|---|
| 125 | * Internal actions not part of the public API. Note: These are subject to change at any given time.
|
|---|
| 126 | */
|
|---|
| 127 | internalActions: InternalActions
|
|---|
| 128 | /**
|
|---|
| 129 | * A standard redux reducer that enables core functionality. Make sure it's included in your store.
|
|---|
| 130 | *
|
|---|
| 131 | * @example
|
|---|
| 132 | * ```ts
|
|---|
| 133 | * configureStore({
|
|---|
| 134 | * reducer: {
|
|---|
| 135 | * [api.reducerPath]: api.reducer,
|
|---|
| 136 | * },
|
|---|
| 137 | * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
|
|---|
| 138 | * })
|
|---|
| 139 | * ```
|
|---|
| 140 | */
|
|---|
| 141 | reducer: Reducer<
|
|---|
| 142 | CombinedState<Definitions, TagTypes, ReducerPath>,
|
|---|
| 143 | UnknownAction
|
|---|
| 144 | >
|
|---|
| 145 | /**
|
|---|
| 146 | * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.
|
|---|
| 147 | *
|
|---|
| 148 | * @example
|
|---|
| 149 | * ```ts
|
|---|
| 150 | * configureStore({
|
|---|
| 151 | * reducer: {
|
|---|
| 152 | * [api.reducerPath]: api.reducer,
|
|---|
| 153 | * },
|
|---|
| 154 | * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
|
|---|
| 155 | * })
|
|---|
| 156 | * ```
|
|---|
| 157 | */
|
|---|
| 158 | middleware: Middleware<
|
|---|
| 159 | {},
|
|---|
| 160 | RootState<Definitions, string, ReducerPath>,
|
|---|
| 161 | ThunkDispatch<any, any, UnknownAction>
|
|---|
| 162 | >
|
|---|
| 163 | /**
|
|---|
| 164 | * A collection of utility thunks for various situations.
|
|---|
| 165 | */
|
|---|
| 166 | util: {
|
|---|
| 167 | /**
|
|---|
| 168 | * A thunk that (if dispatched) will return a specific running query, identified
|
|---|
| 169 | * by `endpointName` and `arg`.
|
|---|
| 170 | * If that query is not running, dispatching the thunk will result in `undefined`.
|
|---|
| 171 | *
|
|---|
| 172 | * Can be used to await a specific query triggered in any way,
|
|---|
| 173 | * including via hook calls or manually dispatching `initiate` actions.
|
|---|
| 174 | *
|
|---|
| 175 | * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
|
|---|
| 176 | */
|
|---|
| 177 | getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(
|
|---|
| 178 | endpointName: EndpointName,
|
|---|
| 179 | arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
|
|---|
| 180 | ): ThunkWithReturnValue<
|
|---|
| 181 | | QueryActionCreatorResult<
|
|---|
| 182 | Definitions[EndpointName] & { type: 'query' }
|
|---|
| 183 | >
|
|---|
| 184 | | InfiniteQueryActionCreatorResult<
|
|---|
| 185 | Definitions[EndpointName] & { type: 'infinitequery' }
|
|---|
| 186 | >
|
|---|
| 187 | | undefined
|
|---|
| 188 | >
|
|---|
| 189 |
|
|---|
| 190 | /**
|
|---|
| 191 | * A thunk that (if dispatched) will return a specific running mutation, identified
|
|---|
| 192 | * by `endpointName` and `fixedCacheKey` or `requestId`.
|
|---|
| 193 | * If that mutation is not running, dispatching the thunk will result in `undefined`.
|
|---|
| 194 | *
|
|---|
| 195 | * Can be used to await a specific mutation triggered in any way,
|
|---|
| 196 | * including via hook trigger functions or manually dispatching `initiate` actions.
|
|---|
| 197 | *
|
|---|
| 198 | * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
|
|---|
| 199 | */
|
|---|
| 200 | getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
|
|---|
| 201 | endpointName: EndpointName,
|
|---|
| 202 | fixedCacheKeyOrRequestId: string,
|
|---|
| 203 | ): ThunkWithReturnValue<
|
|---|
| 204 | | MutationActionCreatorResult<
|
|---|
| 205 | Definitions[EndpointName] & { type: 'mutation' }
|
|---|
| 206 | >
|
|---|
| 207 | | undefined
|
|---|
| 208 | >
|
|---|
| 209 |
|
|---|
| 210 | /**
|
|---|
| 211 | * A thunk that (if dispatched) will return all running queries.
|
|---|
| 212 | *
|
|---|
| 213 | * Useful for SSR scenarios to await all running queries triggered in any way,
|
|---|
| 214 | * including via hook calls or manually dispatching `initiate` actions.
|
|---|
| 215 | *
|
|---|
| 216 | * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
|
|---|
| 217 | */
|
|---|
| 218 | getRunningQueriesThunk(): ThunkWithReturnValue<
|
|---|
| 219 | Array<
|
|---|
| 220 | QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>
|
|---|
| 221 | >
|
|---|
| 222 | >
|
|---|
| 223 |
|
|---|
| 224 | /**
|
|---|
| 225 | * A thunk that (if dispatched) will return all running mutations.
|
|---|
| 226 | *
|
|---|
| 227 | * Useful for SSR scenarios to await all running mutations triggered in any way,
|
|---|
| 228 | * including via hook calls or manually dispatching `initiate` actions.
|
|---|
| 229 | *
|
|---|
| 230 | * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
|
|---|
| 231 | */
|
|---|
| 232 | getRunningMutationsThunk(): ThunkWithReturnValue<
|
|---|
| 233 | Array<MutationActionCreatorResult<any>>
|
|---|
| 234 | >
|
|---|
| 235 |
|
|---|
| 236 | /**
|
|---|
| 237 | * A Redux thunk that can be used to manually trigger pre-fetching of data.
|
|---|
| 238 | *
|
|---|
| 239 | * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
|
|---|
| 240 | *
|
|---|
| 241 | * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.
|
|---|
| 242 | *
|
|---|
| 243 | * @example
|
|---|
| 244 | *
|
|---|
| 245 | * ```ts no-transpile
|
|---|
| 246 | * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
|
|---|
| 247 | * ```
|
|---|
| 248 | */
|
|---|
| 249 | prefetch<EndpointName extends QueryKeys<Definitions>>(
|
|---|
| 250 | endpointName: EndpointName,
|
|---|
| 251 | arg: QueryArgFrom<Definitions[EndpointName]>,
|
|---|
| 252 | options?: PrefetchOptions,
|
|---|
| 253 | ): ThunkAction<void, any, any, UnknownAction>
|
|---|
| 254 | /**
|
|---|
| 255 | * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.
|
|---|
| 256 | *
|
|---|
| 257 | * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.
|
|---|
| 258 | *
|
|---|
| 259 | * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).
|
|---|
| 260 | *
|
|---|
| 261 | * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
|
|---|
| 262 | *
|
|---|
| 263 | * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
|
|---|
| 264 | *
|
|---|
| 265 | * @example
|
|---|
| 266 | *
|
|---|
| 267 | * ```ts
|
|---|
| 268 | * const patchCollection = dispatch(
|
|---|
| 269 | * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
|
|---|
| 270 | * draftPosts.push({ id: 1, name: 'Teddy' })
|
|---|
| 271 | * })
|
|---|
| 272 | * )
|
|---|
| 273 | * ```
|
|---|
| 274 | */
|
|---|
| 275 | updateQueryData: UpdateQueryDataThunk<
|
|---|
| 276 | Definitions,
|
|---|
| 277 | RootState<Definitions, string, ReducerPath>
|
|---|
| 278 | >
|
|---|
| 279 |
|
|---|
| 280 | /**
|
|---|
| 281 | * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
|
|---|
| 282 | *
|
|---|
| 283 | * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.
|
|---|
| 284 | *
|
|---|
| 285 | * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
|
|---|
| 286 | *
|
|---|
| 287 | * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
|
|---|
| 288 | *
|
|---|
| 289 | * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.
|
|---|
| 290 | *
|
|---|
| 291 | * @example
|
|---|
| 292 | *
|
|---|
| 293 | * ```ts
|
|---|
| 294 | * await dispatch(
|
|---|
| 295 | * api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
|
|---|
| 296 | * )
|
|---|
| 297 | * ```
|
|---|
| 298 | */
|
|---|
| 299 | upsertQueryData: UpsertQueryDataThunk<
|
|---|
| 300 | Definitions,
|
|---|
| 301 | RootState<Definitions, string, ReducerPath>
|
|---|
| 302 | >
|
|---|
| 303 | /**
|
|---|
| 304 | * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
|
|---|
| 305 | *
|
|---|
| 306 | * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
|
|---|
| 307 | *
|
|---|
| 308 | * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.
|
|---|
| 309 | *
|
|---|
| 310 | * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.
|
|---|
| 311 | *
|
|---|
| 312 | * @example
|
|---|
| 313 | * ```ts
|
|---|
| 314 | * const patchCollection = dispatch(
|
|---|
| 315 | * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
|
|---|
| 316 | * draftPosts.push({ id: 1, name: 'Teddy' })
|
|---|
| 317 | * })
|
|---|
| 318 | * )
|
|---|
| 319 | *
|
|---|
| 320 | * // later
|
|---|
| 321 | * dispatch(
|
|---|
| 322 | * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
|
|---|
| 323 | * )
|
|---|
| 324 | *
|
|---|
| 325 | * // or
|
|---|
| 326 | * patchCollection.undo()
|
|---|
| 327 | * ```
|
|---|
| 328 | */
|
|---|
| 329 | patchQueryData: PatchQueryDataThunk<
|
|---|
| 330 | Definitions,
|
|---|
| 331 | RootState<Definitions, string, ReducerPath>
|
|---|
| 332 | >
|
|---|
| 333 |
|
|---|
| 334 | /**
|
|---|
| 335 | * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
|
|---|
| 336 | *
|
|---|
| 337 | * @example
|
|---|
| 338 | *
|
|---|
| 339 | * ```ts
|
|---|
| 340 | * dispatch(api.util.resetApiState())
|
|---|
| 341 | * ```
|
|---|
| 342 | */
|
|---|
| 343 | resetApiState: SliceActions['resetApiState']
|
|---|
| 344 |
|
|---|
| 345 | upsertQueryEntries: UpsertEntries<Definitions>
|
|---|
| 346 |
|
|---|
| 347 | /**
|
|---|
| 348 | * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
|
|---|
| 349 | *
|
|---|
| 350 | * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.
|
|---|
| 351 | *
|
|---|
| 352 | * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.
|
|---|
| 353 | *
|
|---|
| 354 | * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:
|
|---|
| 355 | *
|
|---|
| 356 | * - `[TagType]`
|
|---|
| 357 | * - `[{ type: TagType }]`
|
|---|
| 358 | * - `[{ type: TagType, id: number | string }]`
|
|---|
| 359 | *
|
|---|
| 360 | * @example
|
|---|
| 361 | *
|
|---|
| 362 | * ```ts
|
|---|
| 363 | * dispatch(api.util.invalidateTags(['Post']))
|
|---|
| 364 | * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
|
|---|
| 365 | * dispatch(
|
|---|
| 366 | * api.util.invalidateTags([
|
|---|
| 367 | * { type: 'Post', id: 1 },
|
|---|
| 368 | * { type: 'Post', id: 'LIST' },
|
|---|
| 369 | * ])
|
|---|
| 370 | * )
|
|---|
| 371 | * ```
|
|---|
| 372 | */
|
|---|
| 373 | invalidateTags: ActionCreatorWithPayload<
|
|---|
| 374 | Array<TagDescription<TagTypes> | null | undefined>,
|
|---|
| 375 | string
|
|---|
| 376 | >
|
|---|
| 377 |
|
|---|
| 378 | /**
|
|---|
| 379 | * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
|
|---|
| 380 | *
|
|---|
| 381 | * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
|
|---|
| 382 | */
|
|---|
| 383 | selectInvalidatedBy: (
|
|---|
| 384 | state: RootState<Definitions, string, ReducerPath>,
|
|---|
| 385 | tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>,
|
|---|
| 386 | ) => Array<{
|
|---|
| 387 | endpointName: string
|
|---|
| 388 | originalArgs: any
|
|---|
| 389 | queryCacheKey: string
|
|---|
| 390 | }>
|
|---|
| 391 |
|
|---|
| 392 | /**
|
|---|
| 393 | * A function to select all arguments currently cached for a given endpoint.
|
|---|
| 394 | *
|
|---|
| 395 | * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
|
|---|
| 396 | */
|
|---|
| 397 | selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(
|
|---|
| 398 | state: RootState<Definitions, string, ReducerPath>,
|
|---|
| 399 | queryName: QueryName,
|
|---|
| 400 | ) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>
|
|---|
| 401 | }
|
|---|
| 402 | /**
|
|---|
| 403 | * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
|
|---|
| 404 | */
|
|---|
| 405 | endpoints: {
|
|---|
| 406 | [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
|
|---|
| 407 | any,
|
|---|
| 408 | any,
|
|---|
| 409 | any,
|
|---|
| 410 | any,
|
|---|
| 411 | any
|
|---|
| 412 | >
|
|---|
| 413 | ? ApiEndpointQuery<Definitions[K], Definitions>
|
|---|
| 414 | : Definitions[K] extends MutationDefinition<any, any, any, any, any>
|
|---|
| 415 | ? ApiEndpointMutation<Definitions[K], Definitions>
|
|---|
| 416 | : Definitions[K] extends InfiniteQueryDefinition<
|
|---|
| 417 | any,
|
|---|
| 418 | any,
|
|---|
| 419 | any,
|
|---|
| 420 | any,
|
|---|
| 421 | any
|
|---|
| 422 | >
|
|---|
| 423 | ? ApiEndpointInfiniteQuery<Definitions[K], Definitions>
|
|---|
| 424 | : never
|
|---|
| 425 | }
|
|---|
| 426 | }
|
|---|
| 427 | }
|
|---|
| 428 |
|
|---|
| 429 | export interface ApiEndpointQuery<
|
|---|
| 430 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 431 | Definition extends QueryDefinition<any, any, any, any, any>,
|
|---|
| 432 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 433 | Definitions extends EndpointDefinitions,
|
|---|
| 434 | > extends BuildThunksApiEndpointQuery<Definition>,
|
|---|
| 435 | BuildInitiateApiEndpointQuery<Definition>,
|
|---|
| 436 | BuildSelectorsApiEndpointQuery<Definition, Definitions> {
|
|---|
| 437 | name: string
|
|---|
| 438 | /**
|
|---|
| 439 | * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
|
|---|
| 440 | */
|
|---|
| 441 | Types: NonNullable<Definition['Types']>
|
|---|
| 442 | }
|
|---|
| 443 |
|
|---|
| 444 | export interface ApiEndpointInfiniteQuery<
|
|---|
| 445 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 446 | Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
|
|---|
| 447 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 448 | Definitions extends EndpointDefinitions,
|
|---|
| 449 | > extends BuildThunksApiEndpointInfiniteQuery<Definition>,
|
|---|
| 450 | BuildInitiateApiEndpointInfiniteQuery<Definition>,
|
|---|
| 451 | BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {
|
|---|
| 452 | name: string
|
|---|
| 453 | /**
|
|---|
| 454 | * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
|
|---|
| 455 | */
|
|---|
| 456 | Types: NonNullable<Definition['Types']>
|
|---|
| 457 | }
|
|---|
| 458 |
|
|---|
| 459 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 460 | export interface ApiEndpointMutation<
|
|---|
| 461 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 462 | Definition extends MutationDefinition<any, any, any, any, any>,
|
|---|
| 463 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|---|
| 464 | Definitions extends EndpointDefinitions,
|
|---|
| 465 | > extends BuildThunksApiEndpointMutation<Definition>,
|
|---|
| 466 | BuildInitiateApiEndpointMutation<Definition>,
|
|---|
| 467 | BuildSelectorsApiEndpointMutation<Definition, Definitions> {
|
|---|
| 468 | name: string
|
|---|
| 469 | /**
|
|---|
| 470 | * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
|
|---|
| 471 | */
|
|---|
| 472 | Types: NonNullable<Definition['Types']>
|
|---|
| 473 | }
|
|---|
| 474 |
|
|---|
| 475 | export type ListenerActions = {
|
|---|
| 476 | /**
|
|---|
| 477 | * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
|
|---|
| 478 | * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
|
|---|
| 479 | */
|
|---|
| 480 | onOnline: typeof onOnline
|
|---|
| 481 | onOffline: typeof onOffline
|
|---|
| 482 | /**
|
|---|
| 483 | * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
|
|---|
| 484 | * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
|
|---|
| 485 | */
|
|---|
| 486 | onFocus: typeof onFocus
|
|---|
| 487 | onFocusLost: typeof onFocusLost
|
|---|
| 488 | }
|
|---|
| 489 |
|
|---|
| 490 | export type InternalActions = SliceActions & ListenerActions
|
|---|
| 491 |
|
|---|
| 492 | export interface CoreModuleOptions {
|
|---|
| 493 | /**
|
|---|
| 494 | * A selector creator (usually from `reselect`, or matching the same signature)
|
|---|
| 495 | */
|
|---|
| 496 | createSelector?: CreateSelectorFunction<any, any, any>
|
|---|
| 497 | }
|
|---|
| 498 |
|
|---|
| 499 | /**
|
|---|
| 500 | * Creates a module containing the basic redux logic for use with `buildCreateApi`.
|
|---|
| 501 | *
|
|---|
| 502 | * @example
|
|---|
| 503 | * ```ts
|
|---|
| 504 | * const createBaseApi = buildCreateApi(coreModule());
|
|---|
| 505 | * ```
|
|---|
| 506 | */
|
|---|
| 507 | export const coreModule = ({
|
|---|
| 508 | createSelector = _createSelector,
|
|---|
| 509 | }: CoreModuleOptions = {}): Module<CoreModule> => ({
|
|---|
| 510 | name: coreModuleName,
|
|---|
| 511 | init(
|
|---|
| 512 | api,
|
|---|
| 513 | {
|
|---|
| 514 | baseQuery,
|
|---|
| 515 | tagTypes,
|
|---|
| 516 | reducerPath,
|
|---|
| 517 | serializeQueryArgs,
|
|---|
| 518 | keepUnusedDataFor,
|
|---|
| 519 | refetchOnMountOrArgChange,
|
|---|
| 520 | refetchOnFocus,
|
|---|
| 521 | refetchOnReconnect,
|
|---|
| 522 | invalidationBehavior,
|
|---|
| 523 | onSchemaFailure,
|
|---|
| 524 | catchSchemaFailure,
|
|---|
| 525 | skipSchemaValidation,
|
|---|
| 526 | },
|
|---|
| 527 | context,
|
|---|
| 528 | ) {
|
|---|
| 529 | enablePatches()
|
|---|
| 530 |
|
|---|
| 531 | assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)
|
|---|
| 532 |
|
|---|
| 533 | const assertTagType: AssertTagTypes = (tag) => {
|
|---|
| 534 | if (
|
|---|
| 535 | typeof process !== 'undefined' &&
|
|---|
| 536 | process.env.NODE_ENV === 'development'
|
|---|
| 537 | ) {
|
|---|
| 538 | if (!tagTypes.includes(tag.type as any)) {
|
|---|
| 539 | console.error(
|
|---|
| 540 | `Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`,
|
|---|
| 541 | )
|
|---|
| 542 | }
|
|---|
| 543 | }
|
|---|
| 544 | return tag
|
|---|
| 545 | }
|
|---|
| 546 |
|
|---|
| 547 | Object.assign(api, {
|
|---|
| 548 | reducerPath,
|
|---|
| 549 | endpoints: {},
|
|---|
| 550 | internalActions: {
|
|---|
| 551 | onOnline,
|
|---|
| 552 | onOffline,
|
|---|
| 553 | onFocus,
|
|---|
| 554 | onFocusLost,
|
|---|
| 555 | },
|
|---|
| 556 | util: {},
|
|---|
| 557 | })
|
|---|
| 558 |
|
|---|
| 559 | const selectors = buildSelectors({
|
|---|
| 560 | serializeQueryArgs: serializeQueryArgs as any,
|
|---|
| 561 | reducerPath,
|
|---|
| 562 | createSelector,
|
|---|
| 563 | })
|
|---|
| 564 |
|
|---|
| 565 | const {
|
|---|
| 566 | selectInvalidatedBy,
|
|---|
| 567 | selectCachedArgsForQuery,
|
|---|
| 568 | buildQuerySelector,
|
|---|
| 569 | buildInfiniteQuerySelector,
|
|---|
| 570 | buildMutationSelector,
|
|---|
| 571 | } = selectors
|
|---|
| 572 |
|
|---|
| 573 | safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })
|
|---|
| 574 |
|
|---|
| 575 | const {
|
|---|
| 576 | queryThunk,
|
|---|
| 577 | infiniteQueryThunk,
|
|---|
| 578 | mutationThunk,
|
|---|
| 579 | patchQueryData,
|
|---|
| 580 | updateQueryData,
|
|---|
| 581 | upsertQueryData,
|
|---|
| 582 | prefetch,
|
|---|
| 583 | buildMatchThunkActions,
|
|---|
| 584 | } = buildThunks({
|
|---|
| 585 | baseQuery,
|
|---|
| 586 | reducerPath,
|
|---|
| 587 | context,
|
|---|
| 588 | api,
|
|---|
| 589 | serializeQueryArgs,
|
|---|
| 590 | assertTagType,
|
|---|
| 591 | selectors,
|
|---|
| 592 | onSchemaFailure,
|
|---|
| 593 | catchSchemaFailure,
|
|---|
| 594 | skipSchemaValidation,
|
|---|
| 595 | })
|
|---|
| 596 |
|
|---|
| 597 | const { reducer, actions: sliceActions } = buildSlice({
|
|---|
| 598 | context,
|
|---|
| 599 | queryThunk,
|
|---|
| 600 | infiniteQueryThunk,
|
|---|
| 601 | mutationThunk,
|
|---|
| 602 | serializeQueryArgs,
|
|---|
| 603 | reducerPath,
|
|---|
| 604 | assertTagType,
|
|---|
| 605 | config: {
|
|---|
| 606 | refetchOnFocus,
|
|---|
| 607 | refetchOnReconnect,
|
|---|
| 608 | refetchOnMountOrArgChange,
|
|---|
| 609 | keepUnusedDataFor,
|
|---|
| 610 | reducerPath,
|
|---|
| 611 | invalidationBehavior,
|
|---|
| 612 | },
|
|---|
| 613 | })
|
|---|
| 614 |
|
|---|
| 615 | safeAssign(api.util, {
|
|---|
| 616 | patchQueryData,
|
|---|
| 617 | updateQueryData,
|
|---|
| 618 | upsertQueryData,
|
|---|
| 619 | prefetch,
|
|---|
| 620 | resetApiState: sliceActions.resetApiState,
|
|---|
| 621 | upsertQueryEntries: sliceActions.cacheEntriesUpserted as any,
|
|---|
| 622 | })
|
|---|
| 623 | safeAssign(api.internalActions, sliceActions)
|
|---|
| 624 |
|
|---|
| 625 | const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>()
|
|---|
| 626 |
|
|---|
| 627 | const getInternalState = (dispatch: Dispatch) => {
|
|---|
| 628 | const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
|
|---|
| 629 | currentSubscriptions: new Map(),
|
|---|
| 630 | currentPolls: new Map(),
|
|---|
| 631 | runningQueries: new Map(),
|
|---|
| 632 | runningMutations: new Map(),
|
|---|
| 633 | }))
|
|---|
| 634 |
|
|---|
| 635 | return state
|
|---|
| 636 | }
|
|---|
| 637 |
|
|---|
| 638 | const {
|
|---|
| 639 | buildInitiateQuery,
|
|---|
| 640 | buildInitiateInfiniteQuery,
|
|---|
| 641 | buildInitiateMutation,
|
|---|
| 642 | getRunningMutationThunk,
|
|---|
| 643 | getRunningMutationsThunk,
|
|---|
| 644 | getRunningQueriesThunk,
|
|---|
| 645 | getRunningQueryThunk,
|
|---|
| 646 | } = buildInitiate({
|
|---|
| 647 | queryThunk,
|
|---|
| 648 | mutationThunk,
|
|---|
| 649 | infiniteQueryThunk,
|
|---|
| 650 | api,
|
|---|
| 651 | serializeQueryArgs: serializeQueryArgs as any,
|
|---|
| 652 | context,
|
|---|
| 653 | getInternalState,
|
|---|
| 654 | })
|
|---|
| 655 |
|
|---|
| 656 | safeAssign(api.util, {
|
|---|
| 657 | getRunningMutationThunk,
|
|---|
| 658 | getRunningMutationsThunk,
|
|---|
| 659 | getRunningQueryThunk,
|
|---|
| 660 | getRunningQueriesThunk,
|
|---|
| 661 | })
|
|---|
| 662 |
|
|---|
| 663 | const { middleware, actions: middlewareActions } = buildMiddleware({
|
|---|
| 664 | reducerPath,
|
|---|
| 665 | context,
|
|---|
| 666 | queryThunk,
|
|---|
| 667 | mutationThunk,
|
|---|
| 668 | infiniteQueryThunk,
|
|---|
| 669 | api,
|
|---|
| 670 | assertTagType,
|
|---|
| 671 | selectors,
|
|---|
| 672 | getRunningQueryThunk,
|
|---|
| 673 | getInternalState,
|
|---|
| 674 | })
|
|---|
| 675 | safeAssign(api.util, middlewareActions)
|
|---|
| 676 |
|
|---|
| 677 | safeAssign(api, { reducer: reducer as any, middleware })
|
|---|
| 678 |
|
|---|
| 679 | return {
|
|---|
| 680 | name: coreModuleName,
|
|---|
| 681 | injectEndpoint(endpointName, definition) {
|
|---|
| 682 | const anyApi = api as any as Api<
|
|---|
| 683 | any,
|
|---|
| 684 | Record<string, any>,
|
|---|
| 685 | string,
|
|---|
| 686 | string,
|
|---|
| 687 | CoreModule
|
|---|
| 688 | >
|
|---|
| 689 | const endpoint = (anyApi.endpoints[endpointName] ??= {} as any)
|
|---|
| 690 |
|
|---|
| 691 | if (isQueryDefinition(definition)) {
|
|---|
| 692 | safeAssign(
|
|---|
| 693 | endpoint,
|
|---|
| 694 | {
|
|---|
| 695 | name: endpointName,
|
|---|
| 696 | select: buildQuerySelector(endpointName, definition),
|
|---|
| 697 | initiate: buildInitiateQuery(endpointName, definition),
|
|---|
| 698 | },
|
|---|
| 699 | buildMatchThunkActions(queryThunk, endpointName),
|
|---|
| 700 | )
|
|---|
| 701 | }
|
|---|
| 702 | if (isMutationDefinition(definition)) {
|
|---|
| 703 | safeAssign(
|
|---|
| 704 | endpoint,
|
|---|
| 705 | {
|
|---|
| 706 | name: endpointName,
|
|---|
| 707 | select: buildMutationSelector(),
|
|---|
| 708 | initiate: buildInitiateMutation(endpointName),
|
|---|
| 709 | },
|
|---|
| 710 | buildMatchThunkActions(mutationThunk, endpointName),
|
|---|
| 711 | )
|
|---|
| 712 | }
|
|---|
| 713 | if (isInfiniteQueryDefinition(definition)) {
|
|---|
| 714 | safeAssign(
|
|---|
| 715 | endpoint,
|
|---|
| 716 | {
|
|---|
| 717 | name: endpointName,
|
|---|
| 718 | select: buildInfiniteQuerySelector(endpointName, definition),
|
|---|
| 719 | initiate: buildInitiateInfiniteQuery(endpointName, definition),
|
|---|
| 720 | },
|
|---|
| 721 | buildMatchThunkActions(queryThunk, endpointName),
|
|---|
| 722 | )
|
|---|
| 723 | }
|
|---|
| 724 | },
|
|---|
| 725 | }
|
|---|
| 726 | },
|
|---|
| 727 | })
|
|---|