-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
buildInitiate.ts
465 lines (429 loc) · 13.8 KB
/
buildInitiate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import type {
EndpointDefinitions,
QueryDefinition,
MutationDefinition,
QueryArgFrom,
ResultTypeFrom,
} from '../endpointDefinitions'
import { DefinitionType, isQueryDefinition } from '../endpointDefinitions'
import type { QueryThunk, MutationThunk, QueryThunkArg } from './buildThunks'
import type {
UnknownAction,
ThunkAction,
SerializedError,
} from '@reduxjs/toolkit'
import type { SubscriptionOptions, RootState } from './apiState'
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import type { Api, ApiContext } from '../apiTypes'
import type { ApiEndpointQuery } from './module'
import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'
import type { QueryResultSelectorResult } from './buildSelectors'
import type { Dispatch } from 'redux'
import { isNotNullish } from '../utils/isNotNullish'
import { countObjectKeys } from '../utils/countObjectKeys'
declare module './module' {
export interface ApiEndpointQuery<
Definition extends QueryDefinition<any, any, any, any, any>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definitions extends EndpointDefinitions
> {
initiate: StartQueryActionCreator<Definition>
}
export interface ApiEndpointMutation<
Definition extends MutationDefinition<any, any, any, any, any>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definitions extends EndpointDefinitions
> {
initiate: StartMutationActionCreator<Definition>
}
}
export const forceQueryFnSymbol = Symbol('forceQueryFn')
export const isUpsertQuery = (arg: QueryThunkArg) =>
typeof arg[forceQueryFnSymbol] === 'function'
export interface StartQueryActionCreatorOptions {
subscribe?: boolean
forceRefetch?: boolean | number
subscriptionOptions?: SubscriptionOptions
[forceQueryFnSymbol]?: () => QueryReturnValue
}
type StartQueryActionCreator<
D extends QueryDefinition<any, any, any, any, any>
> = (
arg: QueryArgFrom<D>,
options?: StartQueryActionCreatorOptions
) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>
export type QueryActionCreatorResult<
D extends QueryDefinition<any, any, any, any>
> = Promise<QueryResultSelectorResult<D>> & {
arg: QueryArgFrom<D>
requestId: string
subscriptionOptions: SubscriptionOptions | undefined
abort(): void
unwrap(): Promise<ResultTypeFrom<D>>
unsubscribe(): void
refetch(): QueryActionCreatorResult<D>
updateSubscriptionOptions(options: SubscriptionOptions): void
queryCacheKey: string
}
type StartMutationActionCreator<
D extends MutationDefinition<any, any, any, any>
> = (
arg: QueryArgFrom<D>,
options?: {
/**
* If this mutation should be tracked in the store.
* If you just want to manually trigger this mutation using `dispatch` and don't care about the
* result, state & potential errors being held in store, you can set this to false.
* (defaults to `true`)
*/
track?: boolean
fixedCacheKey?: string
}
) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>
export type MutationActionCreatorResult<
D extends MutationDefinition<any, any, any, any>
> = Promise<
| { data: ResultTypeFrom<D> }
| {
error:
| Exclude<
BaseQueryError<
D extends MutationDefinition<any, infer BaseQuery, any, any>
? BaseQuery
: never
>,
undefined
>
| SerializedError
}
> & {
/** @internal */
arg: {
/**
* The name of the given endpoint for the mutation
*/
endpointName: string
/**
* The original arguments supplied to the mutation call
*/
originalArgs: QueryArgFrom<D>
/**
* Whether the mutation is being tracked in the store.
*/
track?: boolean
fixedCacheKey?: string
}
/**
* A unique string generated for the request sequence
*/
requestId: string
/**
* A method to cancel the mutation promise. Note that this is not intended to prevent the mutation
* that was fired off from reaching the server, but only to assist in handling the response.
*
* Calling `abort()` prior to the promise resolving will force it to reach the error state with
* the serialized error:
* `{ name: 'AbortError', message: 'Aborted' }`
*
* @example
* ```ts
* const [updateUser] = useUpdateUserMutation();
*
* useEffect(() => {
* const promise = updateUser(id);
* promise
* .unwrap()
* .catch((err) => {
* if (err.name === 'AbortError') return;
* // else handle the unexpected error
* })
*
* return () => {
* promise.abort();
* }
* }, [id, updateUser])
* ```
*/
abort(): void
/**
* Unwraps a mutation call to provide the raw response/error.
*
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap"
* addPost({ id: 1, name: 'Example' })
* .unwrap()
* .then((payload) => console.log('fulfilled', payload))
* .catch((error) => console.error('rejected', error));
* ```
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
unwrap(): Promise<ResultTypeFrom<D>>
/**
* A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.
The value returned by the hook will reset to `isUninitialized` afterwards.
*/
reset(): void
}
export function buildInitiate({
serializeQueryArgs,
queryThunk,
mutationThunk,
api,
context,
}: {
serializeQueryArgs: InternalSerializeQueryArgs
queryThunk: QueryThunk
mutationThunk: MutationThunk
api: Api<any, EndpointDefinitions, any, any>
context: ApiContext<EndpointDefinitions>
}) {
const runningQueries: Map<
Dispatch,
Record<string, QueryActionCreatorResult<any> | undefined>
> = new Map()
const runningMutations: Map<
Dispatch,
Record<string, MutationActionCreatorResult<any> | undefined>
> = new Map()
const {
unsubscribeQueryResult,
removeMutationResult,
updateSubscriptionOptions,
} = api.internalActions
return {
buildInitiateQuery,
buildInitiateMutation,
getRunningQueryThunk,
getRunningMutationThunk,
getRunningQueriesThunk,
getRunningMutationsThunk,
}
function getRunningQueryThunk(endpointName: string, queryArgs: any) {
return (dispatch: Dispatch) => {
const endpointDefinition = context.endpointDefinitions[endpointName]
const queryCacheKey = serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName,
})
return runningQueries.get(dispatch)?.[queryCacheKey] as
| QueryActionCreatorResult<never>
| undefined
}
}
function getRunningMutationThunk(
/**
* this is only here to allow TS to infer the result type by input value
* we could use it to validate the result, but it's probably not necessary
*/
_endpointName: string,
fixedCacheKeyOrRequestId: string
) {
return (dispatch: Dispatch) => {
return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId] as
| MutationActionCreatorResult<never>
| undefined
}
}
function getRunningQueriesThunk() {
return (dispatch: Dispatch) =>
Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish)
}
function getRunningMutationsThunk() {
return (dispatch: Dispatch) =>
Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish)
}
function middlewareWarning(dispatch: Dispatch) {
if (process.env.NODE_ENV !== 'production') {
if ((middlewareWarning as any).triggered) return
const returnedValue = dispatch(
api.internalActions.internal_getRTKQSubscriptions()
)
;(middlewareWarning as any).triggered = true
// The RTKQ middleware should return the internal state object,
// but it should _not_ be the action object.
if (
typeof returnedValue !== 'object' ||
typeof returnedValue?.type === 'string'
) {
// Otherwise, must not have been added
throw new Error(
`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`
)
}
}
}
function buildInitiateQuery(
endpointName: string,
endpointDefinition: QueryDefinition<any, any, any, any>
) {
const queryAction: StartQueryActionCreator<any> =
(
arg,
{
subscribe = true,
forceRefetch,
subscriptionOptions,
[forceQueryFnSymbol]: forceQueryFn,
} = {}
) =>
(dispatch, getState) => {
const queryCacheKey = serializeQueryArgs({
queryArgs: arg,
endpointDefinition,
endpointName,
})
const thunk = queryThunk({
type: 'query',
subscribe,
forceRefetch: forceRefetch,
subscriptionOptions,
endpointName,
originalArgs: arg,
queryCacheKey,
[forceQueryFnSymbol]: forceQueryFn,
})
const selector = (
api.endpoints[endpointName] as ApiEndpointQuery<any, any>
).select(arg)
const thunkResult = dispatch(thunk)
const stateAfter = selector(getState())
middlewareWarning(dispatch)
const { requestId, abort } = thunkResult
const skippedSynchronously = stateAfter.requestId !== requestId
const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey]
const selectFromState = () => selector(getState())
const statePromise: QueryActionCreatorResult<any> = Object.assign(
forceQueryFn
? // a query has been forced (upsertQueryData)
// -> we want to resolve it once data has been written with the data that will be written
thunkResult.then(selectFromState)
: skippedSynchronously && !runningQuery
? // a query has been skipped due to a condition and we do not have any currently running query
// -> we want to resolve it immediately with the current data
Promise.resolve(stateAfter)
: // query just started or one is already in flight
// -> wait for the running query, then resolve with data from after that
Promise.all([runningQuery, thunkResult]).then(selectFromState),
{
arg,
requestId,
subscriptionOptions,
queryCacheKey,
abort,
async unwrap() {
const result = await statePromise
if (result.isError) {
throw result.error
}
return result.data
},
refetch: () =>
dispatch(
queryAction(arg, { subscribe: false, forceRefetch: true })
),
unsubscribe() {
if (subscribe)
dispatch(
unsubscribeQueryResult({
queryCacheKey,
requestId,
})
)
},
updateSubscriptionOptions(options: SubscriptionOptions) {
statePromise.subscriptionOptions = options
dispatch(
updateSubscriptionOptions({
endpointName,
requestId,
queryCacheKey,
options,
})
)
},
}
)
if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
const running = runningQueries.get(dispatch) || {}
running[queryCacheKey] = statePromise
runningQueries.set(dispatch, running)
statePromise.then(() => {
delete running[queryCacheKey]
if (!countObjectKeys(running)) {
runningQueries.delete(dispatch)
}
})
}
return statePromise
}
return queryAction
}
function buildInitiateMutation(
endpointName: string
): StartMutationActionCreator<any> {
return (arg, { track = true, fixedCacheKey } = {}) =>
(dispatch, getState) => {
const thunk = mutationThunk({
type: 'mutation',
endpointName,
originalArgs: arg,
track,
fixedCacheKey,
})
const thunkResult = dispatch(thunk)
middlewareWarning(dispatch)
const { requestId, abort, unwrap } = thunkResult
const returnValuePromise = thunkResult
.unwrap()
.then((data) => ({ data }))
.catch((error) => ({ error }))
const reset = () => {
dispatch(removeMutationResult({ requestId, fixedCacheKey }))
}
const ret = Object.assign(returnValuePromise, {
arg: thunkResult.arg,
requestId,
abort,
unwrap,
reset,
})
const running = runningMutations.get(dispatch) || {}
runningMutations.set(dispatch, running)
running[requestId] = ret
ret.then(() => {
delete running[requestId]
if (!countObjectKeys(running)) {
runningMutations.delete(dispatch)
}
})
if (fixedCacheKey) {
running[fixedCacheKey] = ret
ret.then(() => {
if (running[fixedCacheKey] === ret) {
delete running[fixedCacheKey]
if (!countObjectKeys(running)) {
runningMutations.delete(dispatch)
}
}
})
}
return ret
}
}
}