Skip to content

Commit fc9b3b8

Browse files
committed
Move ApiModules interface to module.ts
1 parent fac9818 commit fc9b3b8

File tree

3 files changed

+338
-344
lines changed

3 files changed

+338
-344
lines changed

packages/toolkit/src/query/apiTypes.ts

Lines changed: 3 additions & 342 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,12 @@
1-
import type {
2-
ActionCreatorWithPayload,
3-
Middleware,
4-
Reducer,
5-
ThunkAction,
6-
ThunkDispatch,
7-
UnknownAction,
8-
} from '@reduxjs/toolkit'
1+
import type { UnknownAction } from '@reduxjs/toolkit'
92
import type { BaseQueryFn } from './baseQueryTypes'
10-
import type {
11-
ApiEndpointMutation,
12-
ApiEndpointQuery,
13-
CombinedState,
14-
CoreModule,
15-
coreModuleName,
16-
InternalActions,
17-
MutationActionCreatorResult,
18-
MutationKeys,
19-
PatchQueryDataThunk,
20-
PrefetchOptions,
21-
QueryActionCreatorResult,
22-
QueryKeys,
23-
RootState,
24-
SliceActions,
25-
ThunkWithReturnValue,
26-
UpdateQueryDataThunk,
27-
UpsertQueryDataThunk,
28-
} from './core'
3+
import type { CombinedState, CoreModule } from './core'
4+
import type { ApiModules } from './core/module'
295
import type { CreateApiOptions } from './createApi'
306
import type {
317
EndpointBuilder,
328
EndpointDefinition,
339
EndpointDefinitions,
34-
MutationDefinition,
35-
QueryArgFrom,
36-
QueryDefinition,
37-
TagDescription,
3810
UpdateDefinitions,
3911
} from './endpointDefinitions'
4012
import type {
@@ -43,317 +15,6 @@ import type {
4315
WithRequiredProp,
4416
} from './tsHelpers'
4517

46-
export interface ApiModules<
47-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
48-
BaseQuery extends BaseQueryFn,
49-
Definitions extends EndpointDefinitions,
50-
ReducerPath extends string,
51-
TagTypes extends string,
52-
> {
53-
[coreModuleName]: {
54-
/**
55-
* This api's reducer should be mounted at `store[api.reducerPath]`.
56-
*
57-
* @example
58-
* ```ts
59-
* configureStore({
60-
* reducer: {
61-
* [api.reducerPath]: api.reducer,
62-
* },
63-
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
64-
* })
65-
* ```
66-
*/
67-
reducerPath: ReducerPath
68-
/**
69-
* Internal actions not part of the public API. Note: These are subject to change at any given time.
70-
*/
71-
internalActions: InternalActions
72-
/**
73-
* A standard redux reducer that enables core functionality. Make sure it's included in your store.
74-
*
75-
* @example
76-
* ```ts
77-
* configureStore({
78-
* reducer: {
79-
* [api.reducerPath]: api.reducer,
80-
* },
81-
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
82-
* })
83-
* ```
84-
*/
85-
reducer: Reducer<
86-
CombinedState<Definitions, TagTypes, ReducerPath>,
87-
UnknownAction
88-
>
89-
/**
90-
* 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.
91-
*
92-
* @example
93-
* ```ts
94-
* configureStore({
95-
* reducer: {
96-
* [api.reducerPath]: api.reducer,
97-
* },
98-
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
99-
* })
100-
* ```
101-
*/
102-
middleware: Middleware<
103-
{},
104-
RootState<Definitions, string, ReducerPath>,
105-
ThunkDispatch<any, any, UnknownAction>
106-
>
107-
/**
108-
* A collection of utility thunks for various situations.
109-
*/
110-
util: {
111-
/**
112-
* A thunk that (if dispatched) will return a specific running query, identified
113-
* by `endpointName` and `args`.
114-
* If that query is not running, dispatching the thunk will result in `undefined`.
115-
*
116-
* Can be used to await a specific query triggered in any way,
117-
* including via hook calls or manually dispatching `initiate` actions.
118-
*
119-
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
120-
*/
121-
getRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(
122-
endpointName: EndpointName,
123-
args: QueryArgFrom<Definitions[EndpointName]>,
124-
): ThunkWithReturnValue<
125-
| QueryActionCreatorResult<
126-
Definitions[EndpointName] & { type: 'query' }
127-
>
128-
| undefined
129-
>
130-
131-
/**
132-
* A thunk that (if dispatched) will return a specific running mutation, identified
133-
* by `endpointName` and `fixedCacheKey` or `requestId`.
134-
* If that mutation is not running, dispatching the thunk will result in `undefined`.
135-
*
136-
* Can be used to await a specific mutation triggered in any way,
137-
* including via hook trigger functions or manually dispatching `initiate` actions.
138-
*
139-
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
140-
*/
141-
getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
142-
endpointName: EndpointName,
143-
fixedCacheKeyOrRequestId: string,
144-
): ThunkWithReturnValue<
145-
| MutationActionCreatorResult<
146-
Definitions[EndpointName] & { type: 'mutation' }
147-
>
148-
| undefined
149-
>
150-
151-
/**
152-
* A thunk that (if dispatched) will return all running queries.
153-
*
154-
* Useful for SSR scenarios to await all running queries triggered in any way,
155-
* including via hook calls or manually dispatching `initiate` actions.
156-
*
157-
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
158-
*/
159-
getRunningQueriesThunk(): ThunkWithReturnValue<
160-
Array<QueryActionCreatorResult<any>>
161-
>
162-
163-
/**
164-
* A thunk that (if dispatched) will return all running mutations.
165-
*
166-
* Useful for SSR scenarios to await all running mutations triggered in any way,
167-
* including via hook calls or manually dispatching `initiate` actions.
168-
*
169-
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
170-
*/
171-
getRunningMutationsThunk(): ThunkWithReturnValue<
172-
Array<MutationActionCreatorResult<any>>
173-
>
174-
175-
/**
176-
* A Redux thunk that can be used to manually trigger pre-fetching of data.
177-
*
178-
* 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.
179-
*
180-
* 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.
181-
*
182-
* @example
183-
*
184-
* ```ts no-transpile
185-
* dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
186-
* ```
187-
*/
188-
prefetch<EndpointName extends QueryKeys<Definitions>>(
189-
endpointName: EndpointName,
190-
arg: QueryArgFrom<Definitions[EndpointName]>,
191-
options: PrefetchOptions,
192-
): ThunkAction<void, any, any, UnknownAction>
193-
/**
194-
* 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.
195-
*
196-
* 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.
197-
*
198-
* 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).
199-
*
200-
* 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, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
201-
*
202-
* Note that the first two arguments (`endpointName` and `args`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
203-
*
204-
* @example
205-
*
206-
* ```ts
207-
* const patchCollection = dispatch(
208-
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
209-
* draftPosts.push({ id: 1, name: 'Teddy' })
210-
* })
211-
* )
212-
* ```
213-
*/
214-
updateQueryData: UpdateQueryDataThunk<
215-
Definitions,
216-
RootState<Definitions, string, ReducerPath>
217-
>
218-
219-
/**
220-
* A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
221-
*
222-
* 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.
223-
*
224-
* 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.
225-
*
226-
* The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
227-
*
228-
* 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.
229-
*
230-
* @example
231-
*
232-
* ```ts
233-
* await dispatch(
234-
* api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
235-
* )
236-
* ```
237-
*/
238-
upsertQueryData: UpsertQueryDataThunk<
239-
Definitions,
240-
RootState<Definitions, string, ReducerPath>
241-
>
242-
/**
243-
* 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.
244-
*
245-
* 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`.
246-
*
247-
* 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.
248-
*
249-
* 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.
250-
*
251-
* @example
252-
* ```ts
253-
* const patchCollection = dispatch(
254-
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
255-
* draftPosts.push({ id: 1, name: 'Teddy' })
256-
* })
257-
* )
258-
*
259-
* // later
260-
* dispatch(
261-
* api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
262-
* )
263-
*
264-
* // or
265-
* patchCollection.undo()
266-
* ```
267-
*/
268-
patchQueryData: PatchQueryDataThunk<
269-
Definitions,
270-
RootState<Definitions, string, ReducerPath>
271-
>
272-
273-
/**
274-
* 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'.
275-
*
276-
* @example
277-
*
278-
* ```ts
279-
* dispatch(api.util.resetApiState())
280-
* ```
281-
*/
282-
resetApiState: SliceActions['resetApiState']
283-
/**
284-
* A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
285-
*
286-
* 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.
287-
*
288-
* 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.
289-
*
290-
* 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:
291-
*
292-
* - `[TagType]`
293-
* - `[{ type: TagType }]`
294-
* - `[{ type: TagType, id: number | string }]`
295-
*
296-
* @example
297-
*
298-
* ```ts
299-
* dispatch(api.util.invalidateTags(['Post']))
300-
* dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
301-
* dispatch(
302-
* api.util.invalidateTags([
303-
* { type: 'Post', id: 1 },
304-
* { type: 'Post', id: 'LIST' },
305-
* ])
306-
* )
307-
* ```
308-
*/
309-
invalidateTags: ActionCreatorWithPayload<
310-
Array<TagDescription<TagTypes>>,
311-
string
312-
>
313-
314-
/**
315-
* A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
316-
*
317-
* 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.
318-
*/
319-
selectInvalidatedBy: (
320-
state: RootState<Definitions, string, ReducerPath>,
321-
tags: ReadonlyArray<TagDescription<TagTypes>>,
322-
) => Array<{
323-
endpointName: string
324-
originalArgs: any
325-
queryCacheKey: string
326-
}>
327-
328-
/**
329-
* A function to select all arguments currently cached for a given endpoint.
330-
*
331-
* 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.
332-
*/
333-
selectCachedArgsForQuery: <QueryName extends QueryKeys<Definitions>>(
334-
state: RootState<Definitions, string, ReducerPath>,
335-
queryName: QueryName,
336-
) => Array<QueryArgFrom<Definitions[QueryName]>>
337-
}
338-
/**
339-
* Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
340-
*/
341-
endpoints: {
342-
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<
343-
any,
344-
any,
345-
any,
346-
any,
347-
any
348-
>
349-
? ApiEndpointQuery<Definitions[K], Definitions>
350-
: Definitions[K] extends MutationDefinition<any, any, any, any, any>
351-
? ApiEndpointMutation<Definitions[K], Definitions>
352-
: never
353-
}
354-
}
355-
}
356-
35718
export type ModuleName = keyof ApiModules<any, any, any, any>
35819

35920
export type Module<Name extends ModuleName> = {

0 commit comments

Comments
 (0)