-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { isPending, isRejected, isFulfilled } from '@reduxjs/toolkit' | ||
import { toOptionalPromise } from '../../utils/toOptionalPromise' | ||
import { SubMiddlewareBuilder } from './types' | ||
|
||
export const build: SubMiddlewareBuilder = ({ | ||
context, | ||
queryThunk, | ||
mutationThunk, | ||
}) => { | ||
type CacheLifecycle = { | ||
resolve(value: unknown): unknown | ||
reject(value: unknown): unknown | ||
} | ||
const lifecycleMap: Record<string, CacheLifecycle> = {} | ||
|
||
const isPendingThunk = isPending(queryThunk, mutationThunk) | ||
const isRejectedThunk = isRejected(queryThunk, mutationThunk) | ||
const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk) | ||
|
||
return (mwApi) => (next) => (action): any => { | ||
const result = next(action) | ||
|
||
if (isPendingThunk(action)) { | ||
const { | ||
requestId, | ||
arg: { endpointName, originalArgs }, | ||
} = action.meta | ||
const { onQuery } = context.endpointDefinitions[endpointName] | ||
if (onQuery) { | ||
const lifecycle = {} as CacheLifecycle | ||
const resultPromise = toOptionalPromise( | ||
new Promise((resolve, reject) => { | ||
lifecycle.resolve = resolve | ||
lifecycle.reject = reject | ||
}) | ||
) | ||
lifecycleMap[requestId] = lifecycle | ||
onQuery(originalArgs, mwApi, { resultPromise }) | ||
} | ||
} else if (isFullfilledThunk(action)) { | ||
const { requestId } = action.meta | ||
lifecycleMap[requestId].resolve(action.payload) | ||
delete lifecycleMap[requestId] | ||
} else if (isRejectedThunk(action)) { | ||
const { requestId } = action.meta | ||
lifecycleMap[requestId].reject(action.payload ?? action.error) | ||
delete lifecycleMap[requestId] | ||
} | ||
|
||
return result | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters