Debian Codegraph @

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

raw
1 import type { Api, ApiContext, Module, ModuleName } from './apiTypes'
2 import type { CombinedState } from './core/apiState'
3 import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'
4 import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
5 import { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
6 import type {
7 EndpointBuilder,
8 EndpointDefinitions,
9 } from './endpointDefinitions'
10 import {
11 DefinitionType,
12 isInfiniteQueryDefinition,
13 isQueryDefinition,
14 } from './endpointDefinitions'
15 import { nanoid } from './core/rtkImports'
16 import type { UnknownAction } from '@reduxjs/toolkit'
17 import type { NoInfer } from './tsHelpers'
18 import { weakMapMemoize } from 'reselect'
19
20 export interface CreateApiOptions<
21 BaseQuery extends BaseQueryFn,
22 Definitions extends EndpointDefinitions,
23 ReducerPath extends string = 'api',
24 TagTypes extends string = never,
25 > {
26 /**
27 * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.
28 *
29 * @example
30 *
31 * ```ts
32 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
33 *
34 * const api = createApi({
35 * // highlight-start
36 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
37 * // highlight-end
38 * endpoints: (build) => ({
39 * // ...endpoints
40 * }),
41 * })
42 * ```
43 */
44 baseQuery: BaseQuery
45 /**
46 * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).
47 *
48 * @example
49 *
50 * ```ts
51 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
52 *
53 * const api = createApi({
54 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
55 * // highlight-start
56 * tagTypes: ['Post', 'User'],
57 * // highlight-end
58 * endpoints: (build) => ({
59 * // ...endpoints
60 * }),
61 * })
62 * ```
63 */
64 tagTypes?: readonly TagTypes[]
65 /**
66 * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.
67 *
68 * @example
69 *
70 * ```ts
71 * // codeblock-meta title="apis.js"
72 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
73 *
74 * const apiOne = createApi({
75 * // highlight-start
76 * reducerPath: 'apiOne',
77 * // highlight-end
78 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
79 * endpoints: (builder) => ({
80 * // ...endpoints
81 * }),
82 * });
83 *
84 * const apiTwo = createApi({
85 * // highlight-start
86 * reducerPath: 'apiTwo',
87 * // highlight-end
88 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
89 * endpoints: (builder) => ({
90 * // ...endpoints
91 * }),
92 * });
93 * ```
94 */
95 reducerPath?: ReducerPath
96 /**
97 * Accepts a custom function if you have a need to change the creation of cache keys for any reason.
98 */
99 serializeQueryArgs?: SerializeQueryArgs<unknown>
100 /**
101 * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).
102 */
103 endpoints(
104 build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
105 ): Definitions
106 /**
107 * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
108 *
109 * ```ts
110 * // codeblock-meta title="keepUnusedDataFor example"
111 *
112 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
113 * interface Post {
114 * id: number
115 * name: string
116 * }
117 * type PostsResponse = Post[]
118 *
119 * const api = createApi({
120 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
121 * endpoints: (build) => ({
122 * getPosts: build.query<PostsResponse, void>({
123 * query: () => 'posts',
124 * // highlight-start
125 * keepUnusedDataFor: 5
126 * // highlight-end
127 * })
128 * })
129 * })
130 * ```
131 */
132 keepUnusedDataFor?: number
133 /**
134 * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
135 * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
136 * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
137 * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
138 *
139 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
140 */
141 refetchOnMountOrArgChange?: boolean | number
142 /**
143 * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
144 *
145 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
146 *
147 * Note: requires [`setupListeners`](./setupListeners) to have been called.
148 */
149 refetchOnFocus?: boolean
150 /**
151 * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
152 *
153 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
154 *
155 * Note: requires [`setupListeners`](./setupListeners) to have been called.
156 */
157 refetchOnReconnect?: boolean
158 /**
159 * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.
160 *
161 * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.
162 * If the query provides tags that were invalidated while it ran, it won't be re-fetched.
163 * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.
164 * This ensures that queries are always invalidated correctly and automatically "batches" invalidations of concurrent mutations.
165 * Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.
166 */
167 invalidationBehavior?: 'delayed' | 'immediately'
168 /**
169 * A function that is passed every dispatched action. If this returns something other than `undefined`,
170 * that return value will be used to rehydrate fulfilled & errored queries.
171 *
172 * @example
173 *
174 * ```ts
175 * // codeblock-meta title="next-redux-wrapper rehydration example"
176 * import type { Action, PayloadAction } from '@reduxjs/toolkit'
177 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
178 * import { HYDRATE } from 'next-redux-wrapper'
179 *
180 * type RootState = any; // normally inferred from state
181 *
182 * function isHydrateAction(action: Action): action is PayloadAction<RootState> {
183 * return action.type === HYDRATE
184 * }
185 *
186 * export const api = createApi({
187 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
188 * // highlight-start
189 * extractRehydrationInfo(action, { reducerPath }): any {
190 * if (isHydrateAction(action)) {
191 * return action.payload[reducerPath]
192 * }
193 * },
194 * // highlight-end
195 * endpoints: (build) => ({
196 * // omitted
197 * }),
198 * })
199 * ```
200 */
201 extractRehydrationInfo?: (
202 action: UnknownAction,
203 {
204 reducerPath,
205 }: {
206 reducerPath: ReducerPath
207 },
208 ) =>
209 | undefined
210 | CombinedState<
211 NoInfer<Definitions>,
212 NoInfer<TagTypes>,
213 NoInfer<ReducerPath>
214 >
215 }
216
217 export type CreateApi<Modules extends ModuleName> = {
218 /**
219 * Creates a service to use in your application. Contains only the basic redux logic (the core module).
220 *
221 * @link https://rtk-query-docs.netlify.app/api/createApi
222 */
223 <
224 BaseQuery extends BaseQueryFn,
225 Definitions extends EndpointDefinitions,
226 ReducerPath extends string = 'api',
227 TagTypes extends string = never,
228 >(
229 options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
230 ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>
231 }
232
233 /**
234 * Builds a `createApi` method based on the provided `modules`.
235 *
236 * @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api
237 *
238 * @example
239 * ```ts
240 * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
241 * const customCreateApi = buildCreateApi(
242 * coreModule(),
243 * reactHooksModule({
244 * hooks: {
245 * useDispatch: createDispatchHook(MyContext),
246 * useSelector: createSelectorHook(MyContext),
247 * useStore: createStoreHook(MyContext)
248 * }
249 * })
250 * );
251 * ```
252 *
253 * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
254 * @returns A `createApi` method using the provided `modules`.
255 */
256 export function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(
257 ...modules: Modules
258 ): CreateApi<Modules[number]['name']> {
259 return function baseCreateApi(options) {
260 const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) =>
261 options.extractRehydrationInfo?.(action, {
262 reducerPath: (options.reducerPath ?? 'api') as any,
263 }),
264 )
265
266 const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {
267 reducerPath: 'api',
268 keepUnusedDataFor: 60,
269 refetchOnMountOrArgChange: false,
270 refetchOnFocus: false,
271 refetchOnReconnect: false,
272 invalidationBehavior: 'delayed',
273 ...options,
274 extractRehydrationInfo,
275 serializeQueryArgs(queryArgsApi) {
276 let finalSerializeQueryArgs = defaultSerializeQueryArgs
277 if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {
278 const endpointSQA =
279 queryArgsApi.endpointDefinition.serializeQueryArgs!
280 finalSerializeQueryArgs = (queryArgsApi) => {
281 const initialResult = endpointSQA(queryArgsApi)
282 if (typeof initialResult === 'string') {
283 // If the user function returned a string, use it as-is
284 return initialResult
285 } else {
286 // Assume they returned an object (such as a subset of the original
287 // query args) or a primitive, and serialize it ourselves
288 return defaultSerializeQueryArgs({
289 ...queryArgsApi,
290 queryArgs: initialResult,
291 })
292 }
293 }
294 } else if (options.serializeQueryArgs) {
295 finalSerializeQueryArgs = options.serializeQueryArgs
296 }
297
298 return finalSerializeQueryArgs(queryArgsApi)
299 },
300 tagTypes: [...(options.tagTypes || [])],
301 }
302
303 const context: ApiContext<EndpointDefinitions> = {
304 endpointDefinitions: {},
305 batch(fn) {
306 // placeholder "batch" method to be overridden by plugins, for example with React.unstable_batchedUpdate
307 fn()
308 },
309 apiUid: nanoid(),
310 extractRehydrationInfo,
311 hasRehydrationInfo: weakMapMemoize(
312 (action) => extractRehydrationInfo(action) != null,
313 ),
314 }
315
316 const api = {
317 injectEndpoints,
318 enhanceEndpoints({ addTagTypes, endpoints }) {
319 if (addTagTypes) {
320 for (const eT of addTagTypes) {
321 if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {
322 ;(optionsWithDefaults.tagTypes as any[]).push(eT)
323 }
324 }
325 }
326 if (endpoints) {
327 for (const [endpointName, partialDefinition] of Object.entries(
328 endpoints,
329 )) {
330 if (typeof partialDefinition === 'function') {
331 partialDefinition(context.endpointDefinitions[endpointName])
332 } else {
333 Object.assign(
334 context.endpointDefinitions[endpointName] || {},
335 partialDefinition,
336 )
337 }
338 }
339 }
340 return api
341 },
342 } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>
343
344 const initializedModules = modules.map((m) =>
345 m.init(api as any, optionsWithDefaults as any, context),
346 )
347
348 function injectEndpoints(
349 inject: Parameters<typeof api.injectEndpoints>[0],
350 ) {
351 const evaluatedEndpoints = inject.endpoints({
352 query: (x) => ({ ...x, type: DefinitionType.query }) as any,
353 mutation: (x) => ({ ...x, type: DefinitionType.mutation }) as any,
354 infiniteQuery: (x) =>
355 ({ ...x, type: DefinitionType.infinitequery }) as any,
356 })
357
358 for (const [endpointName, definition] of Object.entries(
359 evaluatedEndpoints,
360 )) {
361 if (
362 inject.overrideExisting !== true &&
363 endpointName in context.endpointDefinitions
364 ) {
365 if (inject.overrideExisting === 'throw') {
366 throw new Error(
367 `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
368 )
369 } else if (
370 typeof process !== 'undefined' &&
371 process.env.NODE_ENV === 'development'
372 ) {
373 console.error(
374 `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
375 )
376 }
377
378 continue
379 }
380
381 if (
382 typeof process !== 'undefined' &&
383 process.env.NODE_ENV === 'development'
384 ) {
385 if (isInfiniteQueryDefinition(definition)) {
386 const { infiniteQueryOptions } = definition
387 const { maxPages, getPreviousPageParam } = infiniteQueryOptions
388
389 if (typeof maxPages === 'number') {
390 if (maxPages < 1) {
391 throw new Error(
392 `maxPages for endpoint '${endpointName}' must be a number greater than 0`,
393 )
394 }
395
396 if (typeof getPreviousPageParam !== 'function') {
397 throw new Error(
398 `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`,
399 )
400 }
401 }
402 }
403 }
404
405 context.endpointDefinitions[endpointName] = definition
406 for (const m of initializedModules) {
407 m.injectEndpoint(endpointName, definition)
408 }
409 }
410
411 return api as any
412 }
413
414 return api.injectEndpoints({ endpoints: options.endpoints as any })
415 }
416 }