Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts

raw
1 import type { Api } from '@reduxjs/toolkit/query'
2 import type {
3 BaseQueryApi,
4 BaseQueryArg,
5 BaseQueryError,
6 BaseQueryExtraOptions,
7 BaseQueryFn,
8 BaseQueryMeta,
9 BaseQueryResult,
10 QueryReturnValue,
11 } from './baseQueryTypes'
12 import type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection'
13 import type {
14 CacheLifecycleInfiniteQueryExtraOptions,
15 CacheLifecycleMutationExtraOptions,
16 CacheLifecycleQueryExtraOptions,
17 } from './core/buildMiddleware/cacheLifecycle'
18 import type {
19 QueryLifecycleInfiniteQueryExtraOptions,
20 QueryLifecycleMutationExtraOptions,
21 QueryLifecycleQueryExtraOptions,
22 } from './core/buildMiddleware/queryLifecycle'
23 import type {
24 InfiniteData,
25 InfiniteQueryConfigOptions,
26 QuerySubState,
27 RootState,
28 } from './core/index'
29 import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
30 import type { NEVER } from './fakeBaseQuery'
31 import type {
32 CastAny,
33 HasRequiredProps,
34 MaybePromise,
35 NonUndefined,
36 OmitFromUnion,
37 UnwrapPromise,
38 } from './tsHelpers'
39 import { isNotNullish } from './utils'
40
41 const resultType = /* @__PURE__ */ Symbol()
42 const baseQuery = /* @__PURE__ */ Symbol()
43
44 type EndpointDefinitionWithQuery<
45 QueryArg,
46 BaseQuery extends BaseQueryFn,
47 ResultType,
48 > = {
49 /**
50 * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.
51 *
52 * @example
53 *
54 * ```ts
55 * // codeblock-meta title="query example"
56 *
57 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
58 * interface Post {
59 * id: number
60 * name: string
61 * }
62 * type PostsResponse = Post[]
63 *
64 * const api = createApi({
65 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
66 * tagTypes: ['Post'],
67 * endpoints: (build) => ({
68 * getPosts: build.query<PostsResponse, void>({
69 * // highlight-start
70 * query: () => 'posts',
71 * // highlight-end
72 * }),
73 * addPost: build.mutation<Post, Partial<Post>>({
74 * // highlight-start
75 * query: (body) => ({
76 * url: `posts`,
77 * method: 'POST',
78 * body,
79 * }),
80 * // highlight-end
81 * invalidatesTags: [{ type: 'Post', id: 'LIST' }],
82 * }),
83 * })
84 * })
85 * ```
86 */
87 query(arg: QueryArg): BaseQueryArg<BaseQuery>
88 queryFn?: never
89 /**
90 * A function to manipulate the data returned by a query or mutation.
91 */
92 transformResponse?(
93 baseQueryReturnValue: BaseQueryResult<BaseQuery>,
94 meta: BaseQueryMeta<BaseQuery>,
95 arg: QueryArg,
96 ): ResultType | Promise<ResultType>
97 /**
98 * A function to manipulate the data returned by a failed query or mutation.
99 */
100 transformErrorResponse?(
101 baseQueryReturnValue: BaseQueryError<BaseQuery>,
102 meta: BaseQueryMeta<BaseQuery>,
103 arg: QueryArg,
104 ): unknown
105 /**
106 * Defaults to `true`.
107 *
108 * Most apps should leave this setting on. The only time it can be a performance issue
109 * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
110 * you're unable to paginate it.
111 *
112 * For details of how this works, please see the below. When it is set to `false`,
113 * every request will cause subscribed components to rerender, even when the data has not changed.
114 *
115 * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
116 */
117 structuralSharing?: boolean
118 }
119
120 type EndpointDefinitionWithQueryFn<
121 QueryArg,
122 BaseQuery extends BaseQueryFn,
123 ResultType,
124 > = {
125 /**
126 * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.
127 *
128 * @example
129 * ```ts
130 * // codeblock-meta title="Basic queryFn example"
131 *
132 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
133 * interface Post {
134 * id: number
135 * name: string
136 * }
137 * type PostsResponse = Post[]
138 *
139 * const api = createApi({
140 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
141 * endpoints: (build) => ({
142 * getPosts: build.query<PostsResponse, void>({
143 * query: () => 'posts',
144 * }),
145 * flipCoin: build.query<'heads' | 'tails', void>({
146 * // highlight-start
147 * queryFn(arg, queryApi, extraOptions, baseQuery) {
148 * const randomVal = Math.random()
149 * if (randomVal < 0.45) {
150 * return { data: 'heads' }
151 * }
152 * if (randomVal < 0.9) {
153 * return { data: 'tails' }
154 * }
155 * return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on its edge!" } }
156 * }
157 * // highlight-end
158 * })
159 * })
160 * })
161 * ```
162 */
163 queryFn(
164 arg: QueryArg,
165 api: BaseQueryApi,
166 extraOptions: BaseQueryExtraOptions<BaseQuery>,
167 baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>,
168 ): MaybePromise<
169 QueryReturnValue<
170 ResultType,
171 BaseQueryError<BaseQuery>,
172 BaseQueryMeta<BaseQuery>
173 >
174 >
175 query?: never
176 transformResponse?: never
177 transformErrorResponse?: never
178 /**
179 * Defaults to `true`.
180 *
181 * Most apps should leave this setting on. The only time it can be a performance issue
182 * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
183 * you're unable to paginate it.
184 *
185 * For details of how this works, please see the below. When it is set to `false`,
186 * every request will cause subscribed components to rerender, even when the data has not changed.
187 *
188 * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
189 */
190 structuralSharing?: boolean
191 }
192
193 type BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {
194 QueryArg: QueryArg
195 BaseQuery: BaseQuery
196 ResultType: ResultType
197 }
198
199 export type BaseEndpointDefinition<
200 QueryArg,
201 BaseQuery extends BaseQueryFn,
202 ResultType,
203 > = (
204 | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
205 ? never
206 : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>)
207 | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>
208 ) & {
209 /* phantom type */
210 [resultType]?: ResultType
211 /* phantom type */
212 [baseQuery]?: BaseQuery
213 } & HasRequiredProps<
214 BaseQueryExtraOptions<BaseQuery>,
215 { extraOptions: BaseQueryExtraOptions<BaseQuery> },
216 { extraOptions?: BaseQueryExtraOptions<BaseQuery> }
217 >
218
219 export enum DefinitionType {
220 query = 'query',
221 mutation = 'mutation',
222 infinitequery = 'infinitequery',
223 }
224
225 export type GetResultDescriptionFn<
226 TagTypes extends string,
227 ResultType,
228 QueryArg,
229 ErrorType,
230 MetaType,
231 > = (
232 result: ResultType | undefined,
233 error: ErrorType | undefined,
234 arg: QueryArg,
235 meta: MetaType,
236 ) => ReadonlyArray<TagDescription<TagTypes> | undefined | null>
237
238 export type FullTagDescription<TagType> = {
239 type: TagType
240 id?: number | string
241 }
242 export type TagDescription<TagType> = TagType | FullTagDescription<TagType>
243
244 /**
245 * @public
246 */
247 export type ResultDescription<
248 TagTypes extends string,
249 ResultType,
250 QueryArg,
251 ErrorType,
252 MetaType,
253 > =
254 | ReadonlyArray<TagDescription<TagTypes> | undefined | null>
255 | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>
256
257 type QueryTypes<
258 QueryArg,
259 BaseQuery extends BaseQueryFn,
260 TagTypes extends string,
261 ResultType,
262 ReducerPath extends string = string,
263 > = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {
264 /**
265 * The endpoint definition type. To be used with some internal generic types.
266 * @example
267 * ```ts
268 * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
269 * ```
270 */
271 QueryDefinition: QueryDefinition<
272 QueryArg,
273 BaseQuery,
274 TagTypes,
275 ResultType,
276 ReducerPath
277 >
278 TagTypes: TagTypes
279 ReducerPath: ReducerPath
280 }
281
282 /**
283 * @public
284 */
285 export interface QueryExtraOptions<
286 TagTypes extends string,
287 ResultType,
288 QueryArg,
289 BaseQuery extends BaseQueryFn,
290 ReducerPath extends string = string,
291 > extends CacheLifecycleQueryExtraOptions<
292 ResultType,
293 QueryArg,
294 BaseQuery,
295 ReducerPath
296 >,
297 QueryLifecycleQueryExtraOptions<
298 ResultType,
299 QueryArg,
300 BaseQuery,
301 ReducerPath
302 >,
303 CacheCollectionQueryExtraOptions {
304 type: DefinitionType.query
305
306 /**
307 * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.
308 * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.
309 * 1. `['Post']` - equivalent to `2`
310 * 2. `[{ type: 'Post' }]` - equivalent to `1`
311 * 3. `[{ type: 'Post', id: 1 }]`
312 * 4. `(result, error, arg) => ['Post']` - equivalent to `5`
313 * 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`
314 * 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`
315 *
316 * @example
317 *
318 * ```ts
319 * // codeblock-meta title="providesTags example"
320 *
321 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
322 * interface Post {
323 * id: number
324 * name: string
325 * }
326 * type PostsResponse = Post[]
327 *
328 * const api = createApi({
329 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
330 * tagTypes: ['Posts'],
331 * endpoints: (build) => ({
332 * getPosts: build.query<PostsResponse, void>({
333 * query: () => 'posts',
334 * // highlight-start
335 * providesTags: (result) =>
336 * result
337 * ? [
338 * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
339 * { type: 'Posts', id: 'LIST' },
340 * ]
341 * : [{ type: 'Posts', id: 'LIST' }],
342 * // highlight-end
343 * })
344 * })
345 * })
346 * ```
347 */
348 providesTags?: ResultDescription<
349 TagTypes,
350 ResultType,
351 QueryArg,
352 BaseQueryError<BaseQuery>,
353 BaseQueryMeta<BaseQuery>
354 >
355 /**
356 * Not to be used. A query should not invalidate tags in the cache.
357 */
358 invalidatesTags?: never
359
360 /**
361 * Can be provided to return a custom cache key value based on the query arguments.
362 *
363 * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
364 *
365 * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.
366 *
367 *
368 * @example
369 *
370 * ```ts
371 * // codeblock-meta title="serializeQueryArgs : exclude value"
372 *
373 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
374 * interface Post {
375 * id: number
376 * name: string
377 * }
378 *
379 * interface MyApiClient {
380 * fetchPost: (id: string) => Promise<Post>
381 * }
382 *
383 * createApi({
384 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
385 * endpoints: (build) => ({
386 * // Example: an endpoint with an API client passed in as an argument,
387 * // but only the item ID should be used as the cache key
388 * getPost: build.query<Post, { id: string; client: MyApiClient }>({
389 * queryFn: async ({ id, client }) => {
390 * const post = await client.fetchPost(id)
391 * return { data: post }
392 * },
393 * // highlight-start
394 * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
395 * const { id } = queryArgs
396 * // This can return a string, an object, a number, or a boolean.
397 * // If it returns an object, number or boolean, that value
398 * // will be serialized automatically via `defaultSerializeQueryArgs`
399 * return { id } // omit `client` from the cache key
400 *
401 * // Alternately, you can use `defaultSerializeQueryArgs` yourself:
402 * // return defaultSerializeQueryArgs({
403 * // endpointName,
404 * // queryArgs: { id },
405 * // endpointDefinition
406 * // })
407 * // Or create and return a string yourself:
408 * // return `getPost(${id})`
409 * },
410 * // highlight-end
411 * }),
412 * }),
413 *})
414 * ```
415 */
416 serializeQueryArgs?: SerializeQueryArgs<
417 QueryArg,
418 string | number | boolean | Record<any, any>
419 >
420
421 /**
422 * Can be provided to merge an incoming response value into the current cache data.
423 * If supplied, no automatic structural sharing will be applied - it's up to
424 * you to update the cache appropriately.
425 *
426 * Since RTKQ normally replaces cache entries with the new response, you will usually
427 * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep
428 * an existing cache entry so that it can be updated.
429 *
430 * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,
431 * or return a new value, but _not_ both at once.
432 *
433 * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,
434 * the cache entry will just save the response data directly.
435 *
436 * Useful if you don't want a new request to completely override the current cache value,
437 * maybe because you have manually updated it from another source and don't want those
438 * updates to get lost.
439 *
440 *
441 * @example
442 *
443 * ```ts
444 * // codeblock-meta title="merge: pagination"
445 *
446 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
447 * interface Post {
448 * id: number
449 * name: string
450 * }
451 *
452 * createApi({
453 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
454 * endpoints: (build) => ({
455 * listItems: build.query<string[], number>({
456 * query: (pageNumber) => `/listItems?page=${pageNumber}`,
457 * // Only have one cache entry because the arg always maps to one string
458 * serializeQueryArgs: ({ endpointName }) => {
459 * return endpointName
460 * },
461 * // Always merge incoming data to the cache entry
462 * merge: (currentCache, newItems) => {
463 * currentCache.push(...newItems)
464 * },
465 * // Refetch when the page arg changes
466 * forceRefetch({ currentArg, previousArg }) {
467 * return currentArg !== previousArg
468 * },
469 * }),
470 * }),
471 *})
472 * ```
473 */
474 merge?(
475 currentCacheData: ResultType,
476 responseData: ResultType,
477 otherArgs: {
478 arg: QueryArg
479 baseQueryMeta: BaseQueryMeta<BaseQuery>
480 requestId: string
481 fulfilledTimeStamp: number
482 },
483 ): ResultType | void
484
485 /**
486 * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.
487 * This is primarily useful for "infinite scroll" / pagination use cases where
488 * RTKQ is keeping a single cache entry that is added to over time, in combination
489 * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback
490 * set to add incoming data to the cache entry each time.
491 *
492 * @example
493 *
494 * ```ts
495 * // codeblock-meta title="forceRefresh: pagination"
496 *
497 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
498 * interface Post {
499 * id: number
500 * name: string
501 * }
502 *
503 * createApi({
504 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
505 * endpoints: (build) => ({
506 * listItems: build.query<string[], number>({
507 * query: (pageNumber) => `/listItems?page=${pageNumber}`,
508 * // Only have one cache entry because the arg always maps to one string
509 * serializeQueryArgs: ({ endpointName }) => {
510 * return endpointName
511 * },
512 * // Always merge incoming data to the cache entry
513 * merge: (currentCache, newItems) => {
514 * currentCache.push(...newItems)
515 * },
516 * // Refetch when the page arg changes
517 * forceRefetch({ currentArg, previousArg }) {
518 * return currentArg !== previousArg
519 * },
520 * }),
521 * }),
522 *})
523 * ```
524 */
525 forceRefetch?(params: {
526 currentArg: QueryArg | undefined
527 previousArg: QueryArg | undefined
528 state: RootState<any, any, string>
529 endpointState?: QuerySubState<any>
530 }): boolean
531
532 /**
533 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
534 */
535 Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>
536 }
537
538 export type QueryDefinition<
539 QueryArg,
540 BaseQuery extends BaseQueryFn,
541 TagTypes extends string,
542 ResultType,
543 ReducerPath extends string = string,
544 > = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &
545 QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>
546
547 export type InfiniteQueryTypes<
548 QueryArg,
549 PageParam,
550 BaseQuery extends BaseQueryFn,
551 TagTypes extends string,
552 ResultType,
553 ReducerPath extends string = string,
554 > = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {
555 /**
556 * The endpoint definition type. To be used with some internal generic types.
557 * @example
558 * ```ts
559 * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
560 * ```
561 */
562 InfiniteQueryDefinition: InfiniteQueryDefinition<
563 QueryArg,
564 PageParam,
565 BaseQuery,
566 TagTypes,
567 ResultType,
568 ReducerPath
569 >
570 TagTypes: TagTypes
571 ReducerPath: ReducerPath
572 }
573
574 export interface InfiniteQueryExtraOptions<
575 TagTypes extends string,
576 ResultType,
577 QueryArg,
578 PageParam,
579 BaseQuery extends BaseQueryFn,
580 ReducerPath extends string = string,
581 > extends CacheLifecycleInfiniteQueryExtraOptions<
582 InfiniteData<ResultType, PageParam>,
583 QueryArg,
584 BaseQuery,
585 ReducerPath
586 >,
587 QueryLifecycleInfiniteQueryExtraOptions<
588 InfiniteData<ResultType, PageParam>,
589 QueryArg,
590 BaseQuery,
591 ReducerPath
592 >,
593 CacheCollectionQueryExtraOptions {
594 type: DefinitionType.infinitequery
595
596 providesTags?: ResultDescription<
597 TagTypes,
598 InfiniteData<ResultType, PageParam>,
599 QueryArg,
600 BaseQueryError<BaseQuery>,
601 BaseQueryMeta<BaseQuery>
602 >
603 /**
604 * Not to be used. A query should not invalidate tags in the cache.
605 */
606 invalidatesTags?: never
607
608 /**
609 * Required options to configure the infinite query behavior.
610 * `initialPageParam` and `getNextPageParam` are required, to
611 * ensure the infinite query can properly fetch the next page of data.
612 * `initialPageParam` may be specified when using the
613 * endpoint, to override the default value.
614 * `maxPages` and `getPreviousPageParam` are both optional.
615 *
616 * @example
617 *
618 * ```ts
619 * // codeblock-meta title="infiniteQueryOptions example"
620 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
621 *
622 * type Pokemon = {
623 * id: string
624 * name: string
625 * }
626 *
627 * const pokemonApi = createApi({
628 * baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
629 * endpoints: (build) => ({
630 * getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({
631 * infiniteQueryOptions: {
632 * initialPageParam: 0,
633 * maxPages: 3,
634 * getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
635 * lastPageParam + 1,
636 * getPreviousPageParam: (
637 * firstPage,
638 * allPages,
639 * firstPageParam,
640 * allPageParams,
641 * ) => {
642 * return firstPageParam > 0 ? firstPageParam - 1 : undefined
643 * },
644 * },
645 * query({pageParam}) {
646 * return `https://example.com/listItems?page=${pageParam}`
647 * },
648 * }),
649 * }),
650 * })
651
652 * ```
653 */
654 infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam>
655
656 /**
657 * Can be provided to return a custom cache key value based on the query arguments.
658 *
659 * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
660 *
661 * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.
662 *
663 *
664 * @example
665 *
666 * ```ts
667 * // codeblock-meta title="serializeQueryArgs : exclude value"
668 *
669 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
670 * interface Post {
671 * id: number
672 * name: string
673 * }
674 *
675 * interface MyApiClient {
676 * fetchPost: (id: string) => Promise<Post>
677 * }
678 *
679 * createApi({
680 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
681 * endpoints: (build) => ({
682 * // Example: an endpoint with an API client passed in as an argument,
683 * // but only the item ID should be used as the cache key
684 * getPost: build.query<Post, { id: string; client: MyApiClient }>({
685 * queryFn: async ({ id, client }) => {
686 * const post = await client.fetchPost(id)
687 * return { data: post }
688 * },
689 * // highlight-start
690 * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
691 * const { id } = queryArgs
692 * // This can return a string, an object, a number, or a boolean.
693 * // If it returns an object, number or boolean, that value
694 * // will be serialized automatically via `defaultSerializeQueryArgs`
695 * return { id } // omit `client` from the cache key
696 *
697 * // Alternately, you can use `defaultSerializeQueryArgs` yourself:
698 * // return defaultSerializeQueryArgs({
699 * // endpointName,
700 * // queryArgs: { id },
701 * // endpointDefinition
702 * // })
703 * // Or create and return a string yourself:
704 * // return `getPost(${id})`
705 * },
706 * // highlight-end
707 * }),
708 * }),
709 *})
710 * ```
711 */
712 serializeQueryArgs?: SerializeQueryArgs<
713 QueryArg,
714 string | number | boolean | Record<any, any>
715 >
716
717 /**
718 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
719 */
720 Types?: InfiniteQueryTypes<
721 QueryArg,
722 PageParam,
723 BaseQuery,
724 TagTypes,
725 ResultType,
726 ReducerPath
727 >
728 }
729
730 export type InfiniteQueryDefinition<
731 QueryArg,
732 PageParam,
733 BaseQuery extends BaseQueryFn,
734 TagTypes extends string,
735 ResultType,
736 ReducerPath extends string = string,
737 > =
738 // Infinite query endpoints receive `{queryArg, pageParam}`
739 BaseEndpointDefinition<
740 InfiniteQueryCombinedArg<QueryArg, PageParam>,
741 BaseQuery,
742 ResultType
743 > &
744 InfiniteQueryExtraOptions<
745 TagTypes,
746 ResultType,
747 QueryArg,
748 PageParam,
749 BaseQuery,
750 ReducerPath
751 >
752
753 type MutationTypes<
754 QueryArg,
755 BaseQuery extends BaseQueryFn,
756 TagTypes extends string,
757 ResultType,
758 ReducerPath extends string = string,
759 > = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {
760 /**
761 * The endpoint definition type. To be used with some internal generic types.
762 * @example
763 * ```ts
764 * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...
765 * ```
766 */
767 MutationDefinition: MutationDefinition<
768 QueryArg,
769 BaseQuery,
770 TagTypes,
771 ResultType,
772 ReducerPath
773 >
774 TagTypes: TagTypes
775 ReducerPath: ReducerPath
776 }
777
778 /**
779 * @public
780 */
781 export interface MutationExtraOptions<
782 TagTypes extends string,
783 ResultType,
784 QueryArg,
785 BaseQuery extends BaseQueryFn,
786 ReducerPath extends string = string,
787 > extends CacheLifecycleMutationExtraOptions<
788 ResultType,
789 QueryArg,
790 BaseQuery,
791 ReducerPath
792 >,
793 QueryLifecycleMutationExtraOptions<
794 ResultType,
795 QueryArg,
796 BaseQuery,
797 ReducerPath
798 > {
799 type: DefinitionType.mutation
800
801 /**
802 * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.
803 * Expects the same shapes as `providesTags`.
804 *
805 * @example
806 *
807 * ```ts
808 * // codeblock-meta title="invalidatesTags example"
809 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
810 * interface Post {
811 * id: number
812 * name: string
813 * }
814 * type PostsResponse = Post[]
815 *
816 * const api = createApi({
817 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
818 * tagTypes: ['Posts'],
819 * endpoints: (build) => ({
820 * getPosts: build.query<PostsResponse, void>({
821 * query: () => 'posts',
822 * providesTags: (result) =>
823 * result
824 * ? [
825 * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
826 * { type: 'Posts', id: 'LIST' },
827 * ]
828 * : [{ type: 'Posts', id: 'LIST' }],
829 * }),
830 * addPost: build.mutation<Post, Partial<Post>>({
831 * query(body) {
832 * return {
833 * url: `posts`,
834 * method: 'POST',
835 * body,
836 * }
837 * },
838 * // highlight-start
839 * invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
840 * // highlight-end
841 * }),
842 * })
843 * })
844 * ```
845 */
846 invalidatesTags?: ResultDescription<
847 TagTypes,
848 ResultType,
849 QueryArg,
850 BaseQueryError<BaseQuery>,
851 BaseQueryMeta<BaseQuery>
852 >
853 /**
854 * Not to be used. A mutation should not provide tags to the cache.
855 */
856 providesTags?: never
857
858 /**
859 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
860 */
861 Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>
862 }
863
864 export type MutationDefinition<
865 QueryArg,
866 BaseQuery extends BaseQueryFn,
867 TagTypes extends string,
868 ResultType,
869 ReducerPath extends string = string,
870 > = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &
871 MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>
872
873 export type EndpointDefinition<
874 QueryArg,
875 BaseQuery extends BaseQueryFn,
876 TagTypes extends string,
877 ResultType,
878 ReducerPath extends string = string,
879 PageParam = any,
880 > =
881 | QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>
882 | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>
883 | InfiniteQueryDefinition<
884 QueryArg,
885 PageParam,
886 BaseQuery,
887 TagTypes,
888 ResultType,
889 ReducerPath
890 >
891
892 export type EndpointDefinitions = Record<
893 string,
894 EndpointDefinition<any, any, any, any>
895 >
896
897 export function isQueryDefinition(
898 e: EndpointDefinition<any, any, any, any>,
899 ): e is QueryDefinition<any, any, any, any> {
900 return e.type === DefinitionType.query
901 }
902
903 export function isMutationDefinition(
904 e: EndpointDefinition<any, any, any, any>,
905 ): e is MutationDefinition<any, any, any, any> {
906 return e.type === DefinitionType.mutation
907 }
908
909 export function isInfiniteQueryDefinition(
910 e: EndpointDefinition<any, any, any, any>,
911 ): e is InfiniteQueryDefinition<any, any, any, any, any> {
912 return e.type === DefinitionType.infinitequery
913 }
914
915 export type EndpointBuilder<
916 BaseQuery extends BaseQueryFn,
917 TagTypes extends string,
918 ReducerPath extends string,
919 > = {
920 /**
921 * An endpoint definition that retrieves data, and may provide tags to the cache.
922 *
923 * @example
924 * ```js
925 * // codeblock-meta title="Example of all query endpoint options"
926 * const api = createApi({
927 * baseQuery,
928 * endpoints: (build) => ({
929 * getPost: build.query({
930 * query: (id) => ({ url: `post/${id}` }),
931 * // Pick out data and prevent nested properties in a hook or selector
932 * transformResponse: (response) => response.data,
933 * // Pick out error and prevent nested properties in a hook or selector
934 * transformErrorResponse: (response) => response.error,
935 * // `result` is the server response
936 * providesTags: (result, error, id) => [{ type: 'Post', id }],
937 * // trigger side effects or optimistic updates
938 * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},
939 * // handle subscriptions etc
940 * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},
941 * }),
942 * }),
943 *});
944 *```
945 */
946 query<ResultType, QueryArg>(
947 definition: OmitFromUnion<
948 QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>,
949 'type'
950 >,
951 ): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>
952 /**
953 * An endpoint definition that alters data on the server or will possibly invalidate the cache.
954 *
955 * @example
956 * ```js
957 * // codeblock-meta title="Example of all mutation endpoint options"
958 * const api = createApi({
959 * baseQuery,
960 * endpoints: (build) => ({
961 * updatePost: build.mutation({
962 * query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),
963 * // Pick out data and prevent nested properties in a hook or selector
964 * transformResponse: (response) => response.data,
965 * // Pick out error and prevent nested properties in a hook or selector
966 * transformErrorResponse: (response) => response.error,
967 * // `result` is the server response
968 * invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
969 * // trigger side effects or optimistic updates
970 * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},
971 * // handle subscriptions etc
972 * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},
973 * }),
974 * }),
975 * });
976 * ```
977 */
978 mutation<ResultType, QueryArg>(
979 definition: OmitFromUnion<
980 MutationDefinition<
981 QueryArg,
982 BaseQuery,
983 TagTypes,
984 ResultType,
985 ReducerPath
986 >,
987 'type'
988 >,
989 ): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>
990
991 infiniteQuery<ResultType, QueryArg, PageParam>(
992 definition: OmitFromUnion<
993 InfiniteQueryDefinition<
994 QueryArg,
995 PageParam,
996 BaseQuery,
997 TagTypes,
998 ResultType,
999 ReducerPath
1000 >,
1001 'type'
1002 >,
1003 ): InfiniteQueryDefinition<
1004 QueryArg,
1005 PageParam,
1006 BaseQuery,
1007 TagTypes,
1008 ResultType,
1009 ReducerPath
1010 >
1011 }
1012
1013 export type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T
1014
1015 export function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(
1016 description:
1017 | ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType>
1018 | undefined,
1019 result: ResultType | undefined,
1020 error: ErrorType | undefined,
1021 queryArg: QueryArg,
1022 meta: MetaType | undefined,
1023 assertTagTypes: AssertTagTypes,
1024 ): readonly FullTagDescription<string>[] {
1025 if (isFunction(description)) {
1026 return description(
1027 result as ResultType,
1028 error as undefined,
1029 queryArg,
1030 meta as MetaType,
1031 )
1032 .filter(isNotNullish)
1033 .map(expandTagDescription)
1034 .map(assertTagTypes)
1035 }
1036 if (Array.isArray(description)) {
1037 return description.map(expandTagDescription).map(assertTagTypes)
1038 }
1039 return []
1040 }
1041
1042 function isFunction<T>(t: T): t is Extract<T, Function> {
1043 return typeof t === 'function'
1044 }
1045
1046 export function expandTagDescription(
1047 description: TagDescription<string>,
1048 ): FullTagDescription<string> {
1049 return typeof description === 'string' ? { type: description } : description
1050 }
1051
1052 export type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> =
1053 D extends BaseEndpointDefinition<infer QA, any, any> ? QA : never
1054
1055 // Just extracting `QueryArg` from `BaseEndpointDefinition`
1056 // doesn't sufficiently match here.
1057 // We need to explicitly match against `InfiniteQueryDefinition`
1058 export type InfiniteQueryArgFrom<
1059 D extends BaseEndpointDefinition<any, any, any>,
1060 > = D extends InfiniteQueryDefinition<infer QA, any, any, any, any> ? QA : never
1061
1062 export type QueryArgFromAnyQuery<
1063 D extends BaseEndpointDefinition<any, any, any>,
1064 > =
1065 D extends InfiniteQueryDefinition<any, any, any, any, any>
1066 ? InfiniteQueryArgFrom<D>
1067 : D extends QueryDefinition<any, any, any, any>
1068 ? QueryArgFrom<D>
1069 : never
1070
1071 export type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> =
1072 D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown
1073
1074 export type ReducerPathFrom<
1075 D extends EndpointDefinition<any, any, any, any, any>,
1076 > = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown
1077
1078 export type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> =
1079 D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown
1080
1081 export type PageParamFrom<
1082 D extends InfiniteQueryDefinition<any, any, any, any, any>,
1083 > =
1084 D extends InfiniteQueryDefinition<any, infer PP, any, any, any> ? PP : unknown
1085
1086 export type InfiniteQueryCombinedArg<QueryArg, PageParam> = {
1087 queryArg: QueryArg
1088 pageParam: PageParam
1089 }
1090
1091 export type TagTypesFromApi<T> =
1092 T extends Api<any, any, any, infer TagTypes> ? TagTypes : never
1093
1094 export type DefinitionsFromApi<T> =
1095 T extends Api<any, infer Definitions, any, any> ? Definitions : never
1096
1097 export type TransformedResponse<
1098 NewDefinitions extends EndpointDefinitions,
1099 K,
1100 ResultType,
1101 > = K extends keyof NewDefinitions
1102 ? NewDefinitions[K]['transformResponse'] extends undefined
1103 ? ResultType
1104 : UnwrapPromise<
1105 ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>
1106 >
1107 : ResultType
1108
1109 export type OverrideResultType<Definition, NewResultType> =
1110 Definition extends QueryDefinition<
1111 infer QueryArg,
1112 infer BaseQuery,
1113 infer TagTypes,
1114 any,
1115 infer ReducerPath
1116 >
1117 ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath>
1118 : Definition extends MutationDefinition<
1119 infer QueryArg,
1120 infer BaseQuery,
1121 infer TagTypes,
1122 any,
1123 infer ReducerPath
1124 >
1125 ? MutationDefinition<
1126 QueryArg,
1127 BaseQuery,
1128 TagTypes,
1129 NewResultType,
1130 ReducerPath
1131 >
1132 : Definition extends InfiniteQueryDefinition<
1133 infer QueryArg,
1134 infer PageParam,
1135 infer BaseQuery,
1136 infer TagTypes,
1137 any,
1138 infer ReducerPath
1139 >
1140 ? InfiniteQueryDefinition<
1141 QueryArg,
1142 PageParam,
1143 BaseQuery,
1144 TagTypes,
1145 NewResultType,
1146 ReducerPath
1147 >
1148 : never
1149
1150 export type UpdateDefinitions<
1151 Definitions extends EndpointDefinitions,
1152 NewTagTypes extends string,
1153 NewDefinitions extends EndpointDefinitions,
1154 > = {
1155 [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
1156 infer QueryArg,
1157 infer BaseQuery,
1158 any,
1159 infer ResultType,
1160 infer ReducerPath
1161 >
1162 ? QueryDefinition<
1163 QueryArg,
1164 BaseQuery,
1165 NewTagTypes,
1166 TransformedResponse<NewDefinitions, K, ResultType>,
1167 ReducerPath
1168 >
1169 : Definitions[K] extends MutationDefinition<
1170 infer QueryArg,
1171 infer BaseQuery,
1172 any,
1173 infer ResultType,
1174 infer ReducerPath
1175 >
1176 ? MutationDefinition<
1177 QueryArg,
1178 BaseQuery,
1179 NewTagTypes,
1180 TransformedResponse<NewDefinitions, K, ResultType>,
1181 ReducerPath
1182 >
1183 : Definitions[K] extends InfiniteQueryDefinition<
1184 infer QueryArg,
1185 infer PageParam,
1186 infer BaseQuery,
1187 any,
1188 infer ResultType,
1189 infer ReducerPath
1190 >
1191 ? InfiniteQueryDefinition<
1192 QueryArg,
1193 PageParam,
1194 BaseQuery,
1195 NewTagTypes,
1196 TransformedResponse<NewDefinitions, K, ResultType>,
1197 ReducerPath
1198 >
1199 : never
1200 }