-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
cacheLifecycle.ts
333 lines (311 loc) · 9.8 KB
/
cacheLifecycle.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
import { isAsyncThunkAction, isFulfilled } from '../rtkImports'
import type { UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import type { BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes'
import { DefinitionType } from '../../endpointDefinitions'
import type { RootState } from '../apiState'
import type {
MutationResultSelectorResult,
QueryResultSelectorResult,
} from '../buildSelectors'
import { getMutationCacheKey } from '../buildSlice'
import type { PatchCollection, Recipe } from '../buildThunks'
import type {
ApiMiddlewareInternalHandler,
InternalHandlerBuilder,
PromiseWithKnownReason,
SubMiddlewareApi,
} from './types'
export type ReferenceCacheLifecycle = never
declare module '../../endpointDefinitions' {
export interface QueryBaseLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> extends LifecycleApi<ReducerPath> {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): QueryResultSelectorResult<
{ type: DefinitionType.query } & BaseEndpointDefinition<
QueryArg,
BaseQuery,
ResultType
>
>
/**
* Updates the current cache entry value.
* For documentation see `api.util.updateQueryData`.
*/
updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection
}
export interface MutationBaseLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> extends LifecycleApi<ReducerPath> {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): MutationResultSelectorResult<
{ type: DefinitionType.mutation } & BaseEndpointDefinition<
QueryArg,
BaseQuery,
ResultType
>
>
}
export interface LifecycleApi<ReducerPath extends string = string> {
/**
* The dispatch method for the store
*/
dispatch: ThunkDispatch<any, any, UnknownAction>
/**
* A method to get the current state
*/
getState(): RootState<any, any, ReducerPath>
/**
* `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
*/
extra: unknown
/**
* A unique ID generated for the mutation
*/
requestId: string
}
export interface CacheLifecyclePromises<
ResultType = unknown,
MetaType = unknown,
> {
/**
* Promise that will resolve with the first value for this cache key.
* This allows you to `await` until an actual value is in cache.
*
* If the cache entry is removed from the cache before any value has ever
* been resolved, this Promise will reject with
* `new Error('Promise never resolved before cacheEntryRemoved.')`
* to prevent memory leaks.
* You can just re-throw that error (or not handle it at all) -
* it will be caught outside of `cacheEntryAdded`.
*
* If you don't interact with this promise, it will not throw.
*/
cacheDataLoaded: PromiseWithKnownReason<
{
/**
* The (transformed) query result.
*/
data: ResultType
/**
* The `meta` returned by the `baseQuery`
*/
meta: MetaType
},
typeof neverResolvedError
>
/**
* Promise that allows you to wait for the point in time when the cache entry
* has been removed from the cache, by not being used/subscribed to any more
* in the application for too long or by dispatching `api.util.resetApiState`.
*/
cacheEntryRemoved: Promise<void>
}
export interface QueryCacheLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}
export interface MutationCacheLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> extends MutationBaseLifecycleApi<
QueryArg,
BaseQuery,
ResultType,
ReducerPath
>,
CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}
interface QueryExtraOptions<
TagTypes extends string,
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> {
onCacheEntryAdded?(
arg: QueryArg,
api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
): Promise<void> | void
}
interface MutationExtraOptions<
TagTypes extends string,
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> {
onCacheEntryAdded?(
arg: QueryArg,
api: MutationCacheLifecycleApi<
QueryArg,
BaseQuery,
ResultType,
ReducerPath
>,
): Promise<void> | void
}
}
const neverResolvedError = new Error(
'Promise never resolved before cacheEntryRemoved.',
) as Error & {
message: 'Promise never resolved before cacheEntryRemoved.'
}
export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
api,
reducerPath,
context,
queryThunk,
mutationThunk,
internalState,
}) => {
const isQueryThunk = isAsyncThunkAction(queryThunk)
const isMutationThunk = isAsyncThunkAction(mutationThunk)
const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk)
type CacheLifecycle = {
valueResolved?(value: { data: unknown; meta: unknown }): unknown
cacheEntryRemoved(): void
}
const lifecycleMap: Record<string, CacheLifecycle> = {}
const handler: ApiMiddlewareInternalHandler = (
action,
mwApi,
stateBefore,
) => {
const cacheKey = getCacheKey(action)
if (queryThunk.pending.match(action)) {
const oldState = stateBefore[reducerPath].queries[cacheKey]
const state = mwApi.getState()[reducerPath].queries[cacheKey]
if (!oldState && state) {
handleNewKey(
action.meta.arg.endpointName,
action.meta.arg.originalArgs,
cacheKey,
mwApi,
action.meta.requestId,
)
}
} else if (mutationThunk.pending.match(action)) {
const state = mwApi.getState()[reducerPath].mutations[cacheKey]
if (state) {
handleNewKey(
action.meta.arg.endpointName,
action.meta.arg.originalArgs,
cacheKey,
mwApi,
action.meta.requestId,
)
}
} else if (isFulfilledThunk(action)) {
const lifecycle = lifecycleMap[cacheKey]
if (lifecycle?.valueResolved) {
lifecycle.valueResolved({
data: action.payload,
meta: action.meta.baseQueryMeta,
})
delete lifecycle.valueResolved
}
} else if (
api.internalActions.removeQueryResult.match(action) ||
api.internalActions.removeMutationResult.match(action)
) {
const lifecycle = lifecycleMap[cacheKey]
if (lifecycle) {
delete lifecycleMap[cacheKey]
lifecycle.cacheEntryRemoved()
}
} else if (api.util.resetApiState.match(action)) {
for (const [cacheKey, lifecycle] of Object.entries(lifecycleMap)) {
delete lifecycleMap[cacheKey]
lifecycle.cacheEntryRemoved()
}
}
}
function getCacheKey(action: any) {
if (isQueryThunk(action)) return action.meta.arg.queryCacheKey
if (isMutationThunk(action)) {
return action.meta.arg.fixedCacheKey ?? action.meta.requestId
}
if (api.internalActions.removeQueryResult.match(action))
return action.payload.queryCacheKey
if (api.internalActions.removeMutationResult.match(action))
return getMutationCacheKey(action.payload)
return ''
}
function handleNewKey(
endpointName: string,
originalArgs: any,
queryCacheKey: string,
mwApi: SubMiddlewareApi,
requestId: string,
) {
const endpointDefinition = context.endpointDefinitions[endpointName]
const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded
if (!onCacheEntryAdded) return
let lifecycle = {} as CacheLifecycle
const cacheEntryRemoved = new Promise<void>((resolve) => {
lifecycle.cacheEntryRemoved = resolve
})
const cacheDataLoaded: PromiseWithKnownReason<
{ data: unknown; meta: unknown },
typeof neverResolvedError
> = Promise.race([
new Promise<{ data: unknown; meta: unknown }>((resolve) => {
lifecycle.valueResolved = resolve
}),
cacheEntryRemoved.then(() => {
throw neverResolvedError
}),
])
// prevent uncaught promise rejections from happening.
// if the original promise is used in any way, that will create a new promise that will throw again
cacheDataLoaded.catch(() => {})
lifecycleMap[queryCacheKey] = lifecycle
const selector = (api.endpoints[endpointName] as any).select(
endpointDefinition.type === DefinitionType.query
? originalArgs
: queryCacheKey,
)
const extra = mwApi.dispatch((_, __, extra) => extra)
const lifecycleApi = {
...mwApi,
getCacheEntry: () => selector(mwApi.getState()),
requestId,
extra,
updateCachedData: (endpointDefinition.type === DefinitionType.query
? (updateRecipe: Recipe<any>) =>
mwApi.dispatch(
api.util.updateQueryData(
endpointName as never,
originalArgs,
updateRecipe,
),
)
: undefined) as any,
cacheDataLoaded,
cacheEntryRemoved,
}
const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi)
// if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further
Promise.resolve(runningHandler).catch((e) => {
if (e === neverResolvedError) return
throw e
})
}
return handler
}