Initial commit - Dutchie dispensary scraper

This commit is contained in:
Kelly
2025-11-28 19:45:44 -07:00
commit 5757a8e9bd
23375 changed files with 3788799 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
import type { Middleware } from 'redux'
import { isActionCreator as isRTKAction } from './createAction'
export interface ActionCreatorInvariantMiddlewareOptions {
/**
* The function to identify whether a value is an action creator.
* The default checks for a function with a static type property and match method.
*/
isActionCreator?: (action: unknown) => action is Function & { type?: unknown }
}
export function getMessage(type?: unknown) {
const splitType = type ? `${type}`.split('/') : []
const actionName = splitType[splitType.length - 1] || 'actionCreator'
return `Detected an action creator with type "${
type || 'unknown'
}" being dispatched.
Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`
}
export function createActionCreatorInvariantMiddleware(
options: ActionCreatorInvariantMiddlewareOptions = {},
): Middleware {
if (process.env.NODE_ENV === 'production') {
return () => (next) => (action) => next(action)
}
const { isActionCreator = isRTKAction } = options
return () => (next) => (action) => {
if (isActionCreator(action)) {
console.warn(getMessage(action.type))
}
return next(action)
}
}

View File

@@ -0,0 +1,128 @@
import type { StoreEnhancer } from 'redux'
export const SHOULD_AUTOBATCH = 'RTK_autoBatch'
export const prepareAutoBatched =
<T>() =>
(payload: T): { payload: T; meta: unknown } => ({
payload,
meta: { [SHOULD_AUTOBATCH]: true },
})
const createQueueWithTimer = (timeout: number) => {
return (notify: () => void) => {
setTimeout(notify, timeout)
}
}
export type AutoBatchOptions =
| { type: 'tick' }
| { type: 'timer'; timeout: number }
| { type: 'raf' }
| { type: 'callback'; queueNotification: (notify: () => void) => void }
/**
* A Redux store enhancer that watches for "low-priority" actions, and delays
* notifying subscribers until either the queued callback executes or the
* next "standard-priority" action is dispatched.
*
* This allows dispatching multiple "low-priority" actions in a row with only
* a single subscriber notification to the UI after the sequence of actions
* is finished, thus improving UI re-render performance.
*
* Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
* This can be added to `action.meta` manually, or by using the
* `prepareAutoBatched` helper.
*
* By default, it will queue a notification for the end of the event loop tick.
* However, you can pass several other options to configure the behavior:
* - `{type: 'tick'}`: queues using `queueMicrotask`
* - `{type: 'timer', timeout: number}`: queues using `setTimeout`
* - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
* - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
*
*
*/
export const autoBatchEnhancer =
(options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>
(next) =>
(...args) => {
const store = next(...args)
let notifying = true
let shouldNotifyAtEndOfTick = false
let notificationQueued = false
const listeners = new Set<() => void>()
const queueCallback =
options.type === 'tick'
? queueMicrotask
: options.type === 'raf'
? // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
typeof window !== 'undefined' && window.requestAnimationFrame
? window.requestAnimationFrame
: createQueueWithTimer(10)
: options.type === 'callback'
? options.queueNotification
: createQueueWithTimer(options.timeout)
const notifyListeners = () => {
// We're running at the end of the event loop tick.
// Run the real listener callbacks to actually update the UI.
notificationQueued = false
if (shouldNotifyAtEndOfTick) {
shouldNotifyAtEndOfTick = false
listeners.forEach((l) => l())
}
}
return Object.assign({}, store, {
// Override the base `store.subscribe` method to keep original listeners
// from running if we're delaying notifications
subscribe(listener: () => void) {
// Each wrapped listener will only call the real listener if
// the `notifying` flag is currently active when it's called.
// This lets the base store work as normal, while the actual UI
// update becomes controlled by this enhancer.
const wrappedListener: typeof listener = () => notifying && listener()
const unsubscribe = store.subscribe(wrappedListener)
listeners.add(listener)
return () => {
unsubscribe()
listeners.delete(listener)
}
},
// Override the base `store.dispatch` method so that we can check actions
// for the `shouldAutoBatch` flag and determine if batching is active
dispatch(action: any) {
try {
// If the action does _not_ have the `shouldAutoBatch` flag,
// we resume/continue normal notify-after-each-dispatch behavior
notifying = !action?.meta?.[SHOULD_AUTOBATCH]
// If a `notifyListeners` microtask was queued, you can't cancel it.
// Instead, we set a flag so that it's a no-op when it does run
shouldNotifyAtEndOfTick = !notifying
if (shouldNotifyAtEndOfTick) {
// We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue
// a microtask to notify listeners at the end of the event loop tick.
// Make sure we only enqueue this _once_ per tick.
if (!notificationQueued) {
notificationQueued = true
queueCallback(notifyListeners)
}
}
// Go ahead and process the action as usual, including reducers.
// If normal notification behavior is enabled, the store will notify
// all of its own listeners, and the wrapper callbacks above will
// see `notifying` is true and pass on to the real listener callbacks.
// If we're "batching" behavior, then the wrapped callbacks will
// bail out, causing the base store notification behavior to be no-ops.
return store.dispatch(action)
} finally {
// Assume we're back to normal behavior after each action
notifying = true
}
},
})
}

View File

@@ -0,0 +1,487 @@
import type {
PreloadedStateShapeFromReducersMapObject,
Reducer,
StateFromReducersMapObject,
UnknownAction,
} from 'redux'
import { combineReducers } from 'redux'
import { nanoid } from './nanoid'
import type {
Id,
NonUndefined,
Tail,
UnionToIntersection,
WithOptionalProp,
} from './tsHelpers'
import { getOrInsertComputed } from './utils'
type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
reducerPath: ReducerPath
reducer: Reducer<State, any, PreloadedState>
}
type AnySliceLike = SliceLike<string, any>
type SliceLikeReducerPath<A extends AnySliceLike> =
A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never
type SliceLikeState<A extends AnySliceLike> =
A extends SliceLike<any, infer State, any> ? State : never
type SliceLikePreloadedState<A extends AnySliceLike> =
A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never
export type WithSlice<A extends AnySliceLike> = {
[Path in SliceLikeReducerPath<A>]: SliceLikeState<A>
}
export type WithSlicePreloadedState<A extends AnySliceLike> = {
[Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>
}
type ReducerMap = Record<string, Reducer>
type ExistingSliceLike<DeclaredState, PreloadedState> = {
[ReducerPath in keyof DeclaredState]: SliceLike<
ReducerPath & string,
NonUndefined<DeclaredState[ReducerPath]>,
NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>
>
}[keyof DeclaredState]
export type InjectConfig = {
/**
* Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
*/
overrideExisting?: boolean
}
/**
* A reducer that allows for slices/reducers to be injected after initialisation.
*/
export interface CombinedSliceReducer<
InitialState,
DeclaredState extends InitialState = InitialState,
PreloadedState extends Partial<
Record<keyof PreloadedState, any>
> = Partial<DeclaredState>,
> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
/**
* Provide a type for slices that will be injected lazily.
*
* One way to do this would be with interface merging:
* ```ts
*
* export interface LazyLoadedSlices {}
*
* export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
*
* // elsewhere
*
* declare module './reducer' {
* export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
* }
*
* const withBoolean = rootReducer.inject(booleanSlice);
*
* // elsewhere again
*
* declare module './reducer' {
* export interface LazyLoadedSlices {
* customName: CustomState
* }
* }
*
* const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
* ```
*/
withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<
InitialState,
Id<DeclaredState & Partial<Lazy>>,
Id<PreloadedState & Partial<LazyPreloaded>>
>
/**
* Inject a slice.
*
* Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
*
* ```ts
* rootReducer.inject(booleanSlice)
* rootReducer.inject(baseApi)
* rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
* ```
*
*/
inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(
slice: Sl,
config?: InjectConfig,
): CombinedSliceReducer<
InitialState,
Id<DeclaredState & WithSlice<Sl>>,
Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>
>
/**
* Inject a slice.
*
* Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
*
* ```ts
* rootReducer.inject(booleanSlice)
* rootReducer.inject(baseApi)
* rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
* ```
*
*/
inject<ReducerPath extends string, State, PreloadedState = State>(
slice: SliceLike<
ReducerPath,
State & (ReducerPath extends keyof DeclaredState ? never : State),
PreloadedState &
(ReducerPath extends keyof PreloadedState ? never : PreloadedState)
>,
config?: InjectConfig,
): CombinedSliceReducer<
InitialState,
Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>,
Id<
PreloadedState &
WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>
>
>
/**
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
*
* ```ts
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
* // ^? boolean | undefined
*
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
* return state.boolean;
* // ^? boolean
* })
* ```
*
* If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
*
* ```ts
*
* export interface LazyLoadedSlices {};
*
* export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
*
* export const rootReducer = combineSlices({ inner: innerReducer });
*
* export type RootState = ReturnType<typeof rootReducer>;
*
* // elsewhere
*
* declare module "./reducer.ts" {
* export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
* }
*
* const withBool = innerReducer.inject(booleanSlice);
*
* const selectBoolean = withBool.selector(
* (state) => state.boolean,
* (rootState: RootState) => state.inner
* );
* // now expects to be passed RootState instead of innerReducer state
*
* ```
*
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
*
* ```ts
* const injectedReducer = rootReducer.inject(booleanSlice);
* const selectBoolean = injectedReducer.selector((state) => {
* console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
* return state.boolean
* })
* ```
*/
selector: {
/**
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
*
* ```ts
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
* // ^? boolean | undefined
*
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
* return state.boolean;
* // ^? boolean
* })
* ```
*
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
*
* ```ts
* const injectedReducer = rootReducer.inject(booleanSlice);
* const selectBoolean = injectedReducer.selector((state) => {
* console.log(injectedReducer.selector.original(state).boolean) // undefined
* return state.boolean
* })
* ```
*/
<Selector extends (state: DeclaredState, ...args: any[]) => unknown>(
selectorFn: Selector,
): (
state: WithOptionalProp<
Parameters<Selector>[0],
Exclude<keyof DeclaredState, keyof InitialState>
>,
...args: Tail<Parameters<Selector>>
) => ReturnType<Selector>
/**
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
*
* ```ts
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
* // ^? boolean | undefined
*
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
* return state.boolean;
* // ^? boolean
* })
* ```
*
* If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
*
* ```ts
*
* interface LazyLoadedSlices {};
*
* const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
*
* const rootReducer = combineSlices({ inner: innerReducer });
*
* type RootState = ReturnType<typeof rootReducer>;
*
* // elsewhere
*
* declare module "./reducer.ts" {
* interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
* }
*
* const withBool = innerReducer.inject(booleanSlice);
*
* const selectBoolean = withBool.selector(
* (state) => state.boolean,
* (rootState: RootState) => state.inner
* );
* // now expects to be passed RootState instead of innerReducer state
*
* ```
*
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
*
* ```ts
* const injectedReducer = rootReducer.inject(booleanSlice);
* const selectBoolean = injectedReducer.selector((state) => {
* console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
* return state.boolean
* })
* ```
*/
<
Selector extends (state: DeclaredState, ...args: any[]) => unknown,
RootState,
>(
selectorFn: Selector,
selectState: (
rootState: RootState,
...args: Tail<Parameters<Selector>>
) => WithOptionalProp<
Parameters<Selector>[0],
Exclude<keyof DeclaredState, keyof InitialState>
>,
): (
state: RootState,
...args: Tail<Parameters<Selector>>
) => ReturnType<Selector>
/**
* Returns the unproxied state. Useful for debugging.
* @param state state Proxy, that ensures injected reducers have value
* @returns original, unproxied state
* @throws if value passed is not a state Proxy
*/
original: (state: DeclaredState) => InitialState & Partial<DeclaredState>
}
}
type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> =
UnionToIntersection<
Slices[number] extends infer Slice
? Slice extends AnySliceLike
? WithSlice<Slice>
: StateFromReducersMapObject<Slice>
: never
>
type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> =
UnionToIntersection<
Slices[number] extends infer Slice
? Slice extends AnySliceLike
? WithSlicePreloadedState<Slice>
: PreloadedStateShapeFromReducersMapObject<Slice>
: never
>
const isSliceLike = (
maybeSliceLike: AnySliceLike | ReducerMap,
): maybeSliceLike is AnySliceLike =>
'reducerPath' in maybeSliceLike &&
typeof maybeSliceLike.reducerPath === 'string'
const getReducers = (slices: Array<AnySliceLike | ReducerMap>) =>
slices.flatMap<[string, Reducer]>((sliceOrMap) =>
isSliceLike(sliceOrMap)
? [[sliceOrMap.reducerPath, sliceOrMap.reducer]]
: Object.entries(sliceOrMap),
)
const ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original')
const isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE]
const stateProxyMap = new WeakMap<object, object>()
const createStateProxy = <State extends object>(
state: State,
reducerMap: Partial<Record<PropertyKey, Reducer>>,
initialStateCache: Record<PropertyKey, unknown>,
) =>
getOrInsertComputed(
stateProxyMap,
state,
() =>
new Proxy(state, {
get: (target, prop, receiver) => {
if (prop === ORIGINAL_STATE) return target
const result = Reflect.get(target, prop, receiver)
if (typeof result === 'undefined') {
const cached = initialStateCache[prop]
if (typeof cached !== 'undefined') return cached
const reducer = reducerMap[prop]
if (reducer) {
// ensure action type is random, to prevent reducer treating it differently
const reducerResult = reducer(undefined, { type: nanoid() })
if (typeof reducerResult === 'undefined') {
throw new Error(
`The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). ` +
`If the state passed to the reducer is undefined, you must ` +
`explicitly return the initial state. The initial state may ` +
`not be undefined. If you don't want to set a value for this reducer, ` +
`you can use null instead of undefined.`,
)
}
initialStateCache[prop] = reducerResult
return reducerResult
}
}
return result
},
}),
) as State
const original = (state: any) => {
if (!isStateProxy(state)) {
throw new Error('original must be used on state Proxy')
}
return state[ORIGINAL_STATE]
}
const emptyObject = {}
const noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state
export function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(
...slices: Slices
): CombinedSliceReducer<
Id<InitialState<Slices>>,
Id<InitialState<Slices>>,
Partial<Id<InitialPreloadedState<Slices>>>
> {
const reducerMap = Object.fromEntries(getReducers(slices))
const getReducer = () =>
Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer
let reducer = getReducer()
function combinedReducer(
state: Record<string, unknown>,
action: UnknownAction,
) {
return reducer(state, action)
}
combinedReducer.withLazyLoadedSlices = () => combinedReducer
const initialStateCache: Record<PropertyKey, unknown> = {}
const inject = (
slice: AnySliceLike,
config: InjectConfig = {},
): typeof combinedReducer => {
const { reducerPath, reducer: reducerToInject } = slice
const currentReducer = reducerMap[reducerPath]
if (
!config.overrideExisting &&
currentReducer &&
currentReducer !== reducerToInject
) {
if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
console.error(
`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``,
)
}
return combinedReducer
}
if (config.overrideExisting && currentReducer !== reducerToInject) {
delete initialStateCache[reducerPath]
}
reducerMap[reducerPath] = reducerToInject
reducer = getReducer()
return combinedReducer
}
const selector = Object.assign(
function makeSelector<State extends object, RootState, Args extends any[]>(
selectorFn: (state: State, ...args: Args) => any,
selectState?: (rootState: RootState, ...args: Args) => State,
) {
return function selector(state: State, ...args: Args) {
return selectorFn(
createStateProxy(
selectState ? selectState(state as any, ...args) : state,
reducerMap,
initialStateCache,
),
...args,
)
}
},
{ original },
)
return Object.assign(combinedReducer, { inject, selector }) as any
}

View File

@@ -0,0 +1,248 @@
import type {
Reducer,
ReducersMapObject,
Middleware,
Action,
StoreEnhancer,
Store,
UnknownAction,
} from 'redux'
import {
applyMiddleware,
createStore,
compose,
combineReducers,
isPlainObject,
} from './reduxImports'
import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'
import { composeWithDevTools } from './devtoolsExtension'
import type {
ThunkMiddlewareFor,
GetDefaultMiddleware,
} from './getDefaultMiddleware'
import { buildGetDefaultMiddleware } from './getDefaultMiddleware'
import type {
ExtractDispatchExtensions,
ExtractStoreExtensions,
ExtractStateExtensions,
UnknownIfNonSpecific,
} from './tsHelpers'
import type { Tuple } from './utils'
import type { GetDefaultEnhancers } from './getDefaultEnhancers'
import { buildGetDefaultEnhancers } from './getDefaultEnhancers'
/**
* Options for `configureStore()`.
*
* @public
*/
export interface ConfigureStoreOptions<
S = any,
A extends Action = UnknownAction,
M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,
E extends Tuple<Enhancers> = Tuple<Enhancers>,
P = S,
> {
/**
* A single reducer function that will be used as the root reducer, or an
* object of slice reducers that will be passed to `combineReducers()`.
*/
reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>
/**
* An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
* If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
*
* @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
* @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
*/
middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M
/**
* Whether to enable Redux DevTools integration. Defaults to `true`.
*
* Additional configuration can be done by passing Redux DevTools options
*/
devTools?: boolean | DevToolsOptions
/**
* Whether to check for duplicate middleware instances. Defaults to `true`.
*/
duplicateMiddlewareCheck?: boolean
/**
* The initial state, same as Redux's createStore.
* You may optionally specify it to hydrate the state
* from the server in universal apps, or to restore a previously serialized
* user session. If you use `combineReducers()` to produce the root reducer
* function (either directly or indirectly by passing an object as `reducer`),
* this must be an object with the same shape as the reducer map keys.
*/
// we infer here, and instead complain if the reducer doesn't match
preloadedState?: P
/**
* The store enhancers to apply. See Redux's `createStore()`.
* All enhancers will be included before the DevTools Extension enhancer.
* If you need to customize the order of enhancers, supply a callback
* function that will receive a `getDefaultEnhancers` function that returns a Tuple,
* and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
* If you only need to add middleware, you can use the `middleware` parameter instead.
*/
enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E
}
export type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>
type Enhancers = ReadonlyArray<StoreEnhancer>
/**
* A Redux store returned by `configureStore()`. Supports dispatching
* side-effectful _thunks_ in addition to plain actions.
*
* @public
*/
export type EnhancedStore<
S = any,
A extends Action = UnknownAction,
E extends Enhancers = Enhancers,
> = ExtractStoreExtensions<E> &
Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>
/**
* A friendly abstraction over the standard Redux `createStore()` function.
*
* @param options The store configuration.
* @returns A configured Redux store.
*
* @public
*/
export function configureStore<
S = any,
A extends Action = UnknownAction,
M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,
E extends Tuple<Enhancers> = Tuple<
[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]
>,
P = S,
>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {
const getDefaultMiddleware = buildGetDefaultMiddleware<S>()
const {
reducer = undefined,
middleware,
devTools = true,
duplicateMiddlewareCheck = true,
preloadedState = undefined,
enhancers = undefined,
} = options || {}
let rootReducer: Reducer<S, A, P>
if (typeof reducer === 'function') {
rootReducer = reducer
} else if (isPlainObject(reducer)) {
rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>
} else {
throw new Error(
'`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
)
}
if (
process.env.NODE_ENV !== 'production' &&
middleware &&
typeof middleware !== 'function'
) {
throw new Error('`middleware` field must be a callback')
}
let finalMiddleware: Tuple<Middlewares<S>>
if (typeof middleware === 'function') {
finalMiddleware = middleware(getDefaultMiddleware)
if (
process.env.NODE_ENV !== 'production' &&
!Array.isArray(finalMiddleware)
) {
throw new Error(
'when using a middleware builder function, an array of middleware must be returned',
)
}
} else {
finalMiddleware = getDefaultMiddleware()
}
if (
process.env.NODE_ENV !== 'production' &&
finalMiddleware.some((item: any) => typeof item !== 'function')
) {
throw new Error(
'each middleware provided to configureStore must be a function',
)
}
if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {
let middlewareReferences = new Set<Middleware<any, S>>()
finalMiddleware.forEach((middleware) => {
if (middlewareReferences.has(middleware)) {
throw new Error(
'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
)
}
middlewareReferences.add(middleware)
})
}
let finalCompose = compose
if (devTools) {
finalCompose = composeWithDevTools({
// Enable capture of stack traces for dispatched Redux actions
trace: process.env.NODE_ENV !== 'production',
...(typeof devTools === 'object' && devTools),
})
}
const middlewareEnhancer = applyMiddleware(...finalMiddleware)
const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)
if (
process.env.NODE_ENV !== 'production' &&
enhancers &&
typeof enhancers !== 'function'
) {
throw new Error('`enhancers` field must be a callback')
}
let storeEnhancers =
typeof enhancers === 'function'
? enhancers(getDefaultEnhancers)
: getDefaultEnhancers()
if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {
throw new Error('`enhancers` callback must return an array')
}
if (
process.env.NODE_ENV !== 'production' &&
storeEnhancers.some((item: any) => typeof item !== 'function')
) {
throw new Error(
'each enhancer provided to configureStore must be a function',
)
}
if (
process.env.NODE_ENV !== 'production' &&
finalMiddleware.length &&
!storeEnhancers.includes(middlewareEnhancer)
) {
console.error(
'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
)
}
const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers)
return createStore(rootReducer, preloadedState as P, composedEnhancer)
}

View File

@@ -0,0 +1,324 @@
import { isAction } from './reduxImports'
import type {
IsUnknownOrNonInferrable,
IfMaybeUndefined,
IfVoid,
IsAny,
} from './tsHelpers'
import { hasMatchFunction } from './tsHelpers'
/**
* An action with a string type and an associated payload. This is the
* type of action returned by `createAction()` action creators.
*
* @template P The type of the action's payload.
* @template T the type used for the action type.
* @template M The type of the action's meta (optional)
* @template E The type of the action's error (optional)
*
* @public
*/
export type PayloadAction<
P = void,
T extends string = string,
M = never,
E = never,
> = {
payload: P
type: T
} & ([M] extends [never]
? {}
: {
meta: M
}) &
([E] extends [never]
? {}
: {
error: E
})
/**
* A "prepare" method to be used as the second parameter of `createAction`.
* Takes any number of arguments and returns a Flux Standard Action without
* type (will be added later) that *must* contain a payload (might be undefined).
*
* @public
*/
export type PrepareAction<P> =
| ((...args: any[]) => { payload: P })
| ((...args: any[]) => { payload: P; meta: any })
| ((...args: any[]) => { payload: P; error: any })
| ((...args: any[]) => { payload: P; meta: any; error: any })
/**
* Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
*
* @internal
*/
export type _ActionCreatorWithPreparedPayload<
PA extends PrepareAction<any> | void,
T extends string = string,
> =
PA extends PrepareAction<infer P>
? ActionCreatorWithPreparedPayload<
Parameters<PA>,
P,
T,
ReturnType<PA> extends {
error: infer E
}
? E
: never,
ReturnType<PA> extends {
meta: infer M
}
? M
: never
>
: void
/**
* Basic type for all action creators.
*
* @inheritdoc {redux#ActionCreator}
*/
export type BaseActionCreator<P, T extends string, M = never, E = never> = {
type: T
match: (action: unknown) => action is PayloadAction<P, T, M, E>
}
/**
* An action creator that takes multiple arguments that are passed
* to a `PrepareAction` method to create the final Action.
* @typeParam Args arguments for the action creator function
* @typeParam P `payload` type
* @typeParam T `type` name
* @typeParam E optional `error` type
* @typeParam M optional `meta` type
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPreparedPayload<
Args extends unknown[],
P,
T extends string = string,
E = never,
M = never,
> extends BaseActionCreator<P, T, M, E> {
/**
* Calling this {@link redux#ActionCreator} with `Args` will return
* an Action with a payload of type `P` and (depending on the `PrepareAction`
* method used) a `meta`- and `error` property of types `M` and `E` respectively.
*/
(...args: Args): PayloadAction<P, T, M, E>
}
/**
* An action creator of type `T` that takes an optional payload of type `P`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithOptionalPayload<P, T extends string = string>
extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`.
* Calling it without an argument will return a PayloadAction with a payload of `undefined`.
*/
(payload?: P): PayloadAction<P, T>
}
/**
* An action creator of type `T` that takes no payload.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithoutPayload<T extends string = string>
extends BaseActionCreator<undefined, T> {
/**
* Calling this {@link redux#ActionCreator} will
* return a {@link PayloadAction} of type `T` with a payload of `undefined`
*/
(noArgument: void): PayloadAction<undefined, T>
}
/**
* An action creator of type `T` that requires a payload of type P.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPayload<P, T extends string = string>
extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`
*/
(payload: P): PayloadAction<P, T>
}
/**
* An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithNonInferrablePayload<
T extends string = string,
> extends BaseActionCreator<unknown, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload
* of exactly the type of the argument.
*/
<PT extends unknown>(payload: PT): PayloadAction<PT, T>
}
/**
* An action creator that produces actions with a `payload` attribute.
*
* @typeParam P the `payload` type
* @typeParam T the `type` of the resulting action
* @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
*
* @public
*/
export type PayloadActionCreator<
P = void,
T extends string = string,
PA extends PrepareAction<P> | void = void,
> = IfPrepareActionMethodProvided<
PA,
_ActionCreatorWithPreparedPayload<PA, T>,
// else
IsAny<
P,
ActionCreatorWithPayload<any, T>,
IsUnknownOrNonInferrable<
P,
ActionCreatorWithNonInferrablePayload<T>,
// else
IfVoid<
P,
ActionCreatorWithoutPayload<T>,
// else
IfMaybeUndefined<
P,
ActionCreatorWithOptionalPayload<P, T>,
// else
ActionCreatorWithPayload<P, T>
>
>
>
>
>
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overridden so that it returns the action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export function createAction<P = void, T extends string = string>(
type: T,
): PayloadActionCreator<P, T>
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overridden so that it returns the action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export function createAction<
PA extends PrepareAction<any>,
T extends string = string,
>(
type: T,
prepareAction: PA,
): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
export function createAction(type: string, prepareAction?: Function): any {
function actionCreator(...args: any[]) {
if (prepareAction) {
let prepared = prepareAction(...args)
if (!prepared) {
throw new Error('prepareAction did not return an object')
}
return {
type,
payload: prepared.payload,
...('meta' in prepared && { meta: prepared.meta }),
...('error' in prepared && { error: prepared.error }),
}
}
return { type, payload: args[0] }
}
actionCreator.toString = () => `${type}`
actionCreator.type = type
actionCreator.match = (action: unknown): action is PayloadAction =>
isAction(action) && action.type === type
return actionCreator
}
/**
* Returns true if value is an RTK-like action creator, with a static type property and match method.
*/
export function isActionCreator(
action: unknown,
): action is BaseActionCreator<unknown, string> & Function {
return (
typeof action === 'function' &&
'type' in action &&
// hasMatchFunction only wants Matchers but I don't see the point in rewriting it
hasMatchFunction(action as any)
)
}
/**
* Returns true if value is an action with a string type and valid Flux Standard Action keys.
*/
export function isFSA(action: unknown): action is {
type: string
payload?: unknown
error?: unknown
meta?: unknown
} {
return isAction(action) && Object.keys(action).every(isValidKey)
}
function isValidKey(key: string) {
return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1
}
// helper types for more readable typings
type IfPrepareActionMethodProvided<
PA extends PrepareAction<any> | void,
True,
False,
> = PA extends (...args: any[]) => any ? True : False

View File

@@ -0,0 +1,789 @@
import type { Dispatch, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import type { ActionCreatorWithPreparedPayload } from './createAction'
import { createAction } from './createAction'
import { isAnyOf } from './matchers'
import { nanoid } from './nanoid'
import type {
FallbackIfUnknown,
Id,
IsAny,
IsUnknown,
SafePromise,
} from './tsHelpers'
export type BaseThunkAPI<
S,
E,
D extends Dispatch = Dispatch,
RejectedValue = unknown,
RejectedMeta = unknown,
FulfilledMeta = unknown,
> = {
dispatch: D
getState: () => S
extra: E
requestId: string
signal: AbortSignal
abort: (reason?: string) => void
rejectWithValue: IsUnknown<
RejectedMeta,
(value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,
(
value: RejectedValue,
meta: RejectedMeta,
) => RejectWithValue<RejectedValue, RejectedMeta>
>
fulfillWithValue: IsUnknown<
FulfilledMeta,
<FulfilledValue>(value: FulfilledValue) => FulfilledValue,
<FulfilledValue>(
value: FulfilledValue,
meta: FulfilledMeta,
) => FulfillWithMeta<FulfilledValue, FulfilledMeta>
>
}
/**
* @public
*/
export interface SerializedError {
name?: string
message?: string
stack?: string
code?: string
}
const commonProperties: Array<keyof SerializedError> = [
'name',
'message',
'stack',
'code',
]
class RejectWithValue<Payload, RejectedMeta> {
/*
type-only property to distinguish between RejectWithValue and FulfillWithMeta
does not exist at runtime
*/
private readonly _type!: 'RejectWithValue'
constructor(
public readonly payload: Payload,
public readonly meta: RejectedMeta,
) {}
}
class FulfillWithMeta<Payload, FulfilledMeta> {
/*
type-only property to distinguish between RejectWithValue and FulfillWithMeta
does not exist at runtime
*/
private readonly _type!: 'FulfillWithMeta'
constructor(
public readonly payload: Payload,
public readonly meta: FulfilledMeta,
) {}
}
/**
* Serializes an error into a plain object.
* Reworked from https://github.com/sindresorhus/serialize-error
*
* @public
*/
export const miniSerializeError = (value: any): SerializedError => {
if (typeof value === 'object' && value !== null) {
const simpleError: SerializedError = {}
for (const property of commonProperties) {
if (typeof value[property] === 'string') {
simpleError[property] = value[property]
}
}
return simpleError
}
return { message: String(value) }
}
export type AsyncThunkConfig = {
state?: unknown
dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>
extra?: unknown
rejectValue?: unknown
serializedErrorType?: unknown
pendingMeta?: unknown
fulfilledMeta?: unknown
rejectedMeta?: unknown
}
export type GetState<ThunkApiConfig> = ThunkApiConfig extends {
state: infer State
}
? State
: unknown
type GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }
? Extra
: unknown
type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
dispatch: infer Dispatch
}
? FallbackIfUnknown<
Dispatch,
ThunkDispatch<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
UnknownAction
>
>
: ThunkDispatch<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
UnknownAction
>
export type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
GetDispatch<ThunkApiConfig>,
GetRejectValue<ThunkApiConfig>,
GetRejectedMeta<ThunkApiConfig>,
GetFulfilledMeta<ThunkApiConfig>
>
type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
rejectValue: infer RejectValue
}
? RejectValue
: unknown
type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
pendingMeta: infer PendingMeta
}
? PendingMeta
: unknown
type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
fulfilledMeta: infer FulfilledMeta
}
? FulfilledMeta
: unknown
type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
rejectedMeta: infer RejectedMeta
}
? RejectedMeta
: unknown
type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
serializedErrorType: infer GetSerializedErrorType
}
? GetSerializedErrorType
: SerializedError
type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)
/**
* A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunkPayloadCreatorReturnValue<
Returned,
ThunkApiConfig extends AsyncThunkConfig,
> = MaybePromise<
| IsUnknown<
GetFulfilledMeta<ThunkApiConfig>,
Returned,
FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>
>
| RejectWithValue<
GetRejectValue<ThunkApiConfig>,
GetRejectedMeta<ThunkApiConfig>
>
>
/**
* A type describing the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunkPayloadCreator<
Returned,
ThunkArg = void,
ThunkApiConfig extends AsyncThunkConfig = {},
> = (
arg: ThunkArg,
thunkAPI: GetThunkAPI<ThunkApiConfig>,
) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>
/**
* A ThunkAction created by `createAsyncThunk`.
* Dispatching it returns a Promise for either a
* fulfilled or rejected action.
* Also, the returned value contains an `abort()` method
* that allows the asyncAction to be cancelled from the outside.
*
* @public
*/
export type AsyncThunkAction<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = (
dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,
getState: () => GetState<ThunkApiConfig>,
extra: GetExtra<ThunkApiConfig>,
) => SafePromise<
| ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>
| ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>
> & {
abort: (reason?: string) => void
requestId: string
arg: ThunkArg
unwrap: () => Promise<Returned>
}
/**
* Config provided when calling the async thunk action creator.
*/
export interface AsyncThunkDispatchConfig {
/**
* An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
*/
signal?: AbortSignal
}
type AsyncThunkActionCreator<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = IsAny<
ThunkArg,
// any handling
(
arg: ThunkArg,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
// unknown handling
unknown extends ThunkArg
? (
arg: ThunkArg,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined
: [ThunkArg] extends [void] | [undefined]
? (
arg?: undefined,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void
: [void] extends [ThunkArg] // make optional
? (
arg?: ThunkArg,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined
: [undefined] extends [ThunkArg]
? WithStrictNullChecks<
// with strict nullChecks: make optional
(
arg?: ThunkArg,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
// without strict null checks this will match everything, so don't make it optional
(
arg: ThunkArg,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
> // default case: normal argument
: (
arg: ThunkArg,
config?: AsyncThunkDispatchConfig,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
>
/**
* Options object for `createAsyncThunk`.
*
* @public
*/
export type AsyncThunkOptions<
ThunkArg = void,
ThunkApiConfig extends AsyncThunkConfig = {},
> = {
/**
* A method to control whether the asyncThunk should be executed. Has access to the
* `arg`, `api.getState()` and `api.extra` arguments.
*
* @returns `false` if it should be skipped
*/
condition?(
arg: ThunkArg,
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): MaybePromise<boolean | undefined>
/**
* If `condition` returns `false`, the asyncThunk will be skipped.
* This option allows you to control whether a `rejected` action with `meta.condition == false`
* will be dispatched or not.
*
* @default `false`
*/
dispatchConditionRejection?: boolean
serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>
/**
* A function to use when generating the `requestId` for the request sequence.
*
* @default `nanoid`
*/
idGenerator?: (arg: ThunkArg) => string
} & IsUnknown<
GetPendingMeta<ThunkApiConfig>,
{
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*
* Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
* Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
*/
getPendingMeta?(
base: {
arg: ThunkArg
requestId: string
},
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): GetPendingMeta<ThunkApiConfig>
},
{
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*/
getPendingMeta(
base: {
arg: ThunkArg
requestId: string
},
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): GetPendingMeta<ThunkApiConfig>
}
>
export type AsyncThunkPendingActionCreator<
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],
undefined,
string,
never,
{
arg: ThunkArg
requestId: string
requestStatus: 'pending'
} & GetPendingMeta<ThunkApiConfig>
>
export type AsyncThunkRejectedActionCreator<
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[
Error | null,
string,
ThunkArg,
GetRejectValue<ThunkApiConfig>?,
GetRejectedMeta<ThunkApiConfig>?,
],
GetRejectValue<ThunkApiConfig> | undefined,
string,
GetSerializedErrorType<ThunkApiConfig>,
{
arg: ThunkArg
requestId: string
requestStatus: 'rejected'
aborted: boolean
condition: boolean
} & (
| ({ rejectedWithValue: false } & {
[K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined
})
| ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)
)
>
export type AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],
Returned,
string,
never,
{
arg: ThunkArg
requestId: string
requestStatus: 'fulfilled'
} & GetFulfilledMeta<ThunkApiConfig>
>
/**
* A type describing the return value of `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>
rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
fulfilled: AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
>
// matchSettled?
settled: (
action: any,
) => action is ReturnType<
| AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
| AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>
>
typePrefix: string
}
export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
NewConfig & Omit<OldConfig, keyof NewConfig>
>
export type CreateAsyncThunkFunction<
CurriedThunkApiConfig extends AsyncThunkConfig,
> = {
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
// separate signature without `AsyncThunkConfig` for better inference
<Returned, ThunkArg = void>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
CurriedThunkApiConfig
>,
options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,
): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>,
options?: AsyncThunkOptions<
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>,
): AsyncThunk<
Returned,
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
}
type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> =
CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
}
const externalAbortMessage = 'External signal was aborted'
export const createAsyncThunk = /* @__PURE__ */ (() => {
function createAsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
ThunkApiConfig
>,
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,
): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
type RejectedValue = GetRejectValue<ThunkApiConfig>
type PendingMeta = GetPendingMeta<ThunkApiConfig>
type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>
type RejectedMeta = GetRejectedMeta<ThunkApiConfig>
const fulfilled: AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
> = createAction(
typePrefix + '/fulfilled',
(
payload: Returned,
requestId: string,
arg: ThunkArg,
meta?: FulfilledMeta,
) => ({
payload,
meta: {
...((meta as any) || {}),
arg,
requestId,
requestStatus: 'fulfilled' as const,
},
}),
)
const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =
createAction(
typePrefix + '/pending',
(requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({
payload: undefined,
meta: {
...((meta as any) || {}),
arg,
requestId,
requestStatus: 'pending' as const,
},
}),
)
const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =
createAction(
typePrefix + '/rejected',
(
error: Error | null,
requestId: string,
arg: ThunkArg,
payload?: RejectedValue,
meta?: RejectedMeta,
) => ({
payload,
error: ((options && options.serializeError) || miniSerializeError)(
error || 'Rejected',
) as GetSerializedErrorType<ThunkApiConfig>,
meta: {
...((meta as any) || {}),
arg,
requestId,
rejectedWithValue: !!payload,
requestStatus: 'rejected' as const,
aborted: error?.name === 'AbortError',
condition: error?.name === 'ConditionError',
},
}),
)
function actionCreator(
arg: ThunkArg,
{ signal }: AsyncThunkDispatchConfig = {},
): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {
return (dispatch, getState, extra) => {
const requestId = options?.idGenerator
? options.idGenerator(arg)
: nanoid()
const abortController = new AbortController()
let abortHandler: (() => void) | undefined
let abortReason: string | undefined
function abort(reason?: string) {
abortReason = reason
abortController.abort()
}
if (signal) {
if (signal.aborted) {
abort(externalAbortMessage)
} else {
signal.addEventListener(
'abort',
() => abort(externalAbortMessage),
{ once: true },
)
}
}
const promise = (async function () {
let finalAction: ReturnType<typeof fulfilled | typeof rejected>
try {
let conditionResult = options?.condition?.(arg, { getState, extra })
if (isThenable(conditionResult)) {
conditionResult = await conditionResult
}
if (conditionResult === false || abortController.signal.aborted) {
// eslint-disable-next-line no-throw-literal
throw {
name: 'ConditionError',
message: 'Aborted due to condition callback returning false.',
}
}
const abortedPromise = new Promise<never>((_, reject) => {
abortHandler = () => {
reject({
name: 'AbortError',
message: abortReason || 'Aborted',
})
}
abortController.signal.addEventListener('abort', abortHandler)
})
dispatch(
pending(
requestId,
arg,
options?.getPendingMeta?.(
{ requestId, arg },
{ getState, extra },
),
) as any,
)
finalAction = await Promise.race([
abortedPromise,
Promise.resolve(
payloadCreator(arg, {
dispatch,
getState,
extra,
requestId,
signal: abortController.signal,
abort,
rejectWithValue: ((
value: RejectedValue,
meta?: RejectedMeta,
) => {
return new RejectWithValue(value, meta)
}) as any,
fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {
return new FulfillWithMeta(value, meta)
}) as any,
}),
).then((result) => {
if (result instanceof RejectWithValue) {
throw result
}
if (result instanceof FulfillWithMeta) {
return fulfilled(result.payload, requestId, arg, result.meta)
}
return fulfilled(result as any, requestId, arg)
}),
])
} catch (err) {
finalAction =
err instanceof RejectWithValue
? rejected(null, requestId, arg, err.payload, err.meta)
: rejected(err as any, requestId, arg)
} finally {
if (abortHandler) {
abortController.signal.removeEventListener('abort', abortHandler)
}
}
// We dispatch the result action _after_ the catch, to avoid having any errors
// here get swallowed by the try/catch block,
// per https://twitter.com/dan_abramov/status/770914221638942720
// and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks
const skipDispatch =
options &&
!options.dispatchConditionRejection &&
rejected.match(finalAction) &&
(finalAction as any).meta.condition
if (!skipDispatch) {
dispatch(finalAction as any)
}
return finalAction
})()
return Object.assign(promise as SafePromise<any>, {
abort,
requestId,
arg,
unwrap() {
return promise.then<any>(unwrapResult)
},
})
}
}
return Object.assign(
actionCreator as AsyncThunkActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
>,
{
pending,
rejected,
fulfilled,
settled: isAnyOf(rejected, fulfilled),
typePrefix,
},
)
}
createAsyncThunk.withTypes = () => createAsyncThunk
return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>
})()
interface UnwrappableAction {
payload: any
meta?: any
error?: any
}
type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<
T,
{ error: any }
>['payload']
/**
* @public
*/
export function unwrapResult<R extends UnwrappableAction>(
action: R,
): UnwrappedActionPayload<R> {
if (action.meta && action.meta.rejectedWithValue) {
throw action.payload
}
if (action.error) {
throw action.error
}
return action.payload
}
type WithStrictNullChecks<True, False> = undefined extends boolean
? False
: True
function isThenable(value: any): value is PromiseLike<any> {
return (
value !== null &&
typeof value === 'object' &&
typeof value.then === 'function'
)
}

View File

@@ -0,0 +1,30 @@
import { current, isDraft } from './immerImports'
import { createSelectorCreator, weakMapMemoize } from './reselectImports'
export const createDraftSafeSelectorCreator: typeof createSelectorCreator = (
...args: unknown[]
) => {
const createSelector = (createSelectorCreator as any)(...args)
const createDraftSafeSelector = Object.assign(
(...args: unknown[]) => {
const selector = createSelector(...args)
const wrappedSelector = (value: unknown, ...rest: unknown[]) =>
selector(isDraft(value) ? current(value) : value, ...rest)
Object.assign(wrappedSelector, selector)
return wrappedSelector as any
},
{ withTypes: () => createDraftSafeSelector },
)
return createDraftSafeSelector
}
/**
* "Draft-Safe" version of `reselect`'s `createSelector`:
* If an `immer`-drafted object is passed into the resulting selector's first argument,
* the selector will act on the current draft value, instead of returning a cached value
* that might be possibly outdated if the draft has been modified since.
* @public
*/
export const createDraftSafeSelector =
/* @__PURE__ */
createDraftSafeSelectorCreator(weakMapMemoize)

View File

@@ -0,0 +1,233 @@
import type { Draft } from 'immer'
import {
createNextState,
isDraft,
isDraftable,
setUseStrictIteration,
} from './immerImports'
import type { Action, Reducer, UnknownAction } from 'redux'
import type { ActionReducerMapBuilder } from './mapBuilders'
import { executeReducerBuilderCallback } from './mapBuilders'
import type { NoInfer, TypeGuard } from './tsHelpers'
import { freezeDraftable } from './utils'
// Immer 10.2 defaults to still using strict iteration (specifically
// `Reflect.ownKeys()` for symbols support). However, we assume that
// Redux users are not using symbols as state keys, so we'll override
// this to prefer `Object.keys()` instead, as it provides a ~10% speedup.
// If users do need symbol support, they can call `setUseStrictIteration(true)` themselves.
setUseStrictIteration(false)
/**
* Defines a mapping from action types to corresponding action object shapes.
*
* @deprecated This should not be used manually - it is only used for internal
* inference purposes and should not have any further value.
* It might be removed in the future.
* @public
*/
export type Actions<T extends keyof any = string> = Record<T, Action>
export type ActionMatcherDescription<S, A extends Action> = {
matcher: TypeGuard<A>
reducer: CaseReducer<S, NoInfer<A>>
}
export type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<
ActionMatcherDescription<S, any>
>
export type ActionMatcherDescriptionCollection<S> = Array<
ActionMatcherDescription<S, any>
>
/**
* A *case reducer* is a reducer function for a specific action type. Case
* reducers can be composed to full reducers using `createReducer()`.
*
* Unlike a normal Redux reducer, a case reducer is never called with an
* `undefined` state to determine the initial state. Instead, the initial
* state is explicitly specified as an argument to `createReducer()`.
*
* In addition, a case reducer can choose to mutate the passed-in `state`
* value directly instead of returning a new state. This does not actually
* cause the store state to be mutated directly; instead, thanks to
* [immer](https://github.com/mweststrate/immer), the mutations are
* translated to copy operations that result in a new state.
*
* @public
*/
export type CaseReducer<S = any, A extends Action = UnknownAction> = (
state: Draft<S>,
action: A,
) => NoInfer<S> | void | Draft<NoInfer<S>>
/**
* A mapping from action types to case reducers for `createReducer()`.
*
* @deprecated This should not be used manually - it is only used
* for internal inference purposes and using it manually
* would lead to type erasure.
* It might be removed in the future.
* @public
*/
export type CaseReducers<S, AS extends Actions> = {
[T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void
}
export type NotFunction<T> = T extends Function ? never : T
function isStateFunction<S>(x: unknown): x is () => S {
return typeof x === 'function'
}
export type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
getInitialState: () => S
}
/**
* A utility function that allows defining a reducer as a mapping from action
* type to *case reducer* functions that handle these action types. The
* reducer's initial state is passed as the first argument.
*
* @remarks
* The body of every case reducer is implicitly wrapped with a call to
* `produce()` from the [immer](https://github.com/mweststrate/immer) library.
* This means that rather than returning a new state object, you can also
* mutate the passed-in state object directly; these mutations will then be
* automatically and efficiently translated into copies, giving you both
* convenience and immutability.
*
* @overloadSummary
* This function accepts a callback that receives a `builder` object as its argument.
* That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
* called to define what actions this reducer will handle.
*
* @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
* @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
* @example
```ts
import {
createAction,
createReducer,
UnknownAction,
PayloadAction,
} from "@reduxjs/toolkit";
const increment = createAction<number>("increment");
const decrement = createAction<number>("decrement");
function isActionWithNumberPayload(
action: UnknownAction
): action is PayloadAction<number> {
return typeof action.payload === "number";
}
const reducer = createReducer(
{
counter: 0,
sumOfNumberPayloads: 0,
unhandledActions: 0,
},
(builder) => {
builder
.addCase(increment, (state, action) => {
// action is inferred correctly here
state.counter += action.payload;
})
// You can chain calls, or have separate `builder.addCase()` lines each time
.addCase(decrement, (state, action) => {
state.counter -= action.payload;
})
// You can apply a "matcher function" to incoming actions
.addMatcher(isActionWithNumberPayload, (state, action) => {})
// and provide a default case if no other handlers matched
.addDefaultCase((state, action) => {});
}
);
```
* @public
*/
export function createReducer<S extends NotFunction<any>>(
initialState: S | (() => S),
mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void,
): ReducerWithInitialState<S> {
if (process.env.NODE_ENV !== 'production') {
if (typeof mapOrBuilderCallback === 'object') {
throw new Error(
"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer",
)
}
}
let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =
executeReducerBuilderCallback(mapOrBuilderCallback)
// Ensure the initial state gets frozen either way (if draftable)
let getInitialState: () => S
if (isStateFunction(initialState)) {
getInitialState = () => freezeDraftable(initialState())
} else {
const frozenInitialState = freezeDraftable(initialState)
getInitialState = () => frozenInitialState
}
function reducer(state = getInitialState(), action: any): S {
let caseReducers = [
actionsMap[action.type],
...finalActionMatchers
.filter(({ matcher }) => matcher(action))
.map(({ reducer }) => reducer),
]
if (caseReducers.filter((cr) => !!cr).length === 0) {
caseReducers = [finalDefaultCaseReducer]
}
return caseReducers.reduce((previousState, caseReducer): S => {
if (caseReducer) {
if (isDraft(previousState)) {
// If it's already a draft, we must already be inside a `createNextState` call,
// likely because this is being wrapped in `createReducer`, `createSlice`, or nested
// inside an existing draft. It's safe to just pass the draft to the mutator.
const draft = previousState as Draft<S> // We can assume this is already a draft
const result = caseReducer(draft, action)
if (result === undefined) {
return previousState
}
return result as S
} else if (!isDraftable(previousState)) {
// If state is not draftable (ex: a primitive, such as 0), we want to directly
// return the caseReducer func and not wrap it with produce.
const result = caseReducer(previousState as any, action)
if (result === undefined) {
if (previousState === null) {
return previousState
}
throw Error(
'A case reducer on a non-draftable value must not return undefined',
)
}
return result as S
} else {
// @ts-ignore createNextState() produces an Immutable<Draft<S>> rather
// than an Immutable<S>, and TypeScript cannot find out how to reconcile
// these two types.
return createNextState(previousState, (draft: Draft<S>) => {
return caseReducer(draft, action)
})
}
}
return previousState
}, state)
}
reducer.getInitialState = getInitialState
return reducer as ReducerWithInitialState<S>
}

1073
frontend/node_modules/@reduxjs/toolkit/src/createSlice.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,241 @@
import type { Action, ActionCreator, StoreEnhancer } from 'redux'
import { compose } from './reduxImports'
/**
* @public
*/
export interface DevToolsEnhancerOptions {
/**
* the instance name to be showed on the monitor page. Default value is `document.title`.
* If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
*/
name?: string
/**
* action creators functions to be available in the Dispatcher.
*/
actionCreators?: ActionCreator<any>[] | { [key: string]: ActionCreator<any> }
/**
* if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
* It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
* Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
*
* @default 500 ms.
*/
latency?: number
/**
* (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
*
* @default 50
*/
maxAge?: number
/**
* Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
* were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
* functions.
*/
serialize?:
| boolean
| {
/**
* - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
* - `false` - will handle also circular references.
* - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
* - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
* For each of them you can indicate if to include (by setting as `true`).
* For `function` key you can also specify a custom function which handles serialization.
* See [`jsan`](https://github.com/kolodny/jsan) for more details.
*/
options?:
| undefined
| boolean
| {
date?: true
regex?: true
undefined?: true
error?: true
symbol?: true
map?: true
set?: true
function?: true | ((fn: (...args: any[]) => any) => string)
}
/**
* [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
* In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
* key. So you can deserialize it back while importing or persisting data.
* Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
*/
replacer?: (key: string, value: unknown) => any
/**
* [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
* used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
* as an example on how to serialize special data types and get them back.
*/
reviver?: (key: string, value: unknown) => any
/**
* Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
* Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
* The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
*/
immutable?: any
/**
* ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
*/
refs?: any
}
/**
* function which takes `action` object and id number as arguments, and should return `action` object back.
*/
actionSanitizer?: <A extends Action>(action: A, id: number) => A
/**
* function which takes `state` object and index as arguments, and should return `state` object back.
*/
stateSanitizer?: <S>(state: S, index: number) => S
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
*/
actionsDenylist?: string | string[]
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
*/
actionsAllowlist?: string | string[]
/**
* called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
* Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
*/
predicate?: <S, A extends Action>(state: S, action: A) => boolean
/**
* if specified as `false`, it will not record the changes till clicking on `Start recording` button.
* Available only for Redux enhancer, for others use `autoPause`.
*
* @default true
*/
shouldRecordChanges?: boolean
/**
* if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
* If not specified, will commit when paused. Available only for Redux enhancer.
*
* @default "@@PAUSED""
*/
pauseActionType?: string
/**
* auto pauses when the extensions window is not opened, and so has zero impact on your app when not in use.
* Not available for Redux enhancer (as it already does it but storing the data to be sent).
*
* @default false
*/
autoPause?: boolean
/**
* if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
* Available only for Redux enhancer.
*
* @default false
*/
shouldStartLocked?: boolean
/**
* if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
*
* @default true
*/
shouldHotReload?: boolean
/**
* if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
*
* @default false
*/
shouldCatchErrors?: boolean
/**
* If you want to restrict the extension, specify the features you allow.
* If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
* Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
* Otherwise, you'll get/set the data right from the monitor part.
*/
features?: {
/**
* start/pause recording of dispatched actions
*/
pause?: boolean
/**
* lock/unlock dispatching actions and side effects
*/
lock?: boolean
/**
* persist states on page reloading
*/
persist?: boolean
/**
* export history of actions in a file
*/
export?: boolean | 'custom'
/**
* import history of actions from a file
*/
import?: boolean | 'custom'
/**
* jump back and forth (time travelling)
*/
jump?: boolean
/**
* skip (cancel) actions
*/
skip?: boolean
/**
* drag and drop actions in the history list
*/
reorder?: boolean
/**
* dispatch custom actions or action creators
*/
dispatch?: boolean
/**
* generate tests for the selected actions
*/
test?: boolean
}
/**
* Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
* Defaults to false.
*/
trace?: boolean | (<A extends Action>(action: A) => string)
/**
* The maximum number of stack trace entries to record per action. Defaults to 10.
*/
traceLimit?: number
}
type Compose = typeof compose
interface ComposeWithDevTools {
(options: DevToolsEnhancerOptions): Compose
<StoreExt extends {}>(
...funcs: StoreEnhancer<StoreExt>[]
): StoreEnhancer<StoreExt>
}
/**
* @public
*/
export const composeWithDevTools: ComposeWithDevTools =
typeof window !== 'undefined' &&
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
: function () {
if (arguments.length === 0) return undefined
if (typeof arguments[0] === 'object') return compose
return compose.apply(null, arguments as any as Function[])
}
/**
* @public
*/
export const devToolsEnhancer: {
(options: DevToolsEnhancerOptions): StoreEnhancer<any>
} =
typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__
? (window as any).__REDUX_DEVTOOLS_EXTENSION__
: function () {
return function (noop) {
return noop
}
}

View File

@@ -0,0 +1,93 @@
import type { Dispatch, Middleware, UnknownAction } from 'redux'
import { compose } from '../reduxImports'
import { createAction } from '../createAction'
import { isAllOf } from '../matchers'
import { nanoid } from '../nanoid'
import { getOrInsertComputed } from '../utils'
import type {
AddMiddleware,
DynamicMiddleware,
DynamicMiddlewareInstance,
MiddlewareEntry,
WithMiddleware,
} from './types'
export type {
DynamicMiddlewareInstance,
GetDispatchType as GetDispatch,
MiddlewareApiConfig,
} from './types'
const createMiddlewareEntry = <
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(
middleware: Middleware<any, State, DispatchType>,
): MiddlewareEntry<State, DispatchType> => ({
middleware,
applied: new Map(),
})
const matchInstance =
(instanceId: string) =>
(action: any): action is { meta: { instanceId: string } } =>
action?.meta?.instanceId === instanceId
export const createDynamicMiddleware = <
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(): DynamicMiddlewareInstance<State, DispatchType> => {
const instanceId = nanoid()
const middlewareMap = new Map<
Middleware<any, State, DispatchType>,
MiddlewareEntry<State, DispatchType>
>()
const withMiddleware = Object.assign(
createAction(
'dynamicMiddleware/add',
(...middlewares: Middleware<any, State, DispatchType>[]) => ({
payload: middlewares,
meta: {
instanceId,
},
}),
),
{ withTypes: () => withMiddleware },
) as WithMiddleware<State, DispatchType>
const addMiddleware = Object.assign(
function addMiddleware(
...middlewares: Middleware<any, State, DispatchType>[]
) {
middlewares.forEach((middleware) => {
getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)
})
},
{ withTypes: () => addMiddleware },
) as AddMiddleware<State, DispatchType>
const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {
const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>
getOrInsertComputed(entry.applied, api, entry.middleware),
)
return compose(...appliedMiddleware)
}
const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId))
const middleware: DynamicMiddleware<State, DispatchType> =
(api) => (next) => (action) => {
if (isWithMiddleware(action)) {
addMiddleware(...action.payload)
return api.dispatch
}
return getFinalMiddleware(api)(next)(action)
}
return {
middleware,
addMiddleware,
withMiddleware,
instanceId,
}
}

View File

@@ -0,0 +1,101 @@
import type {
DynamicMiddlewareInstance,
GetDispatch,
GetState,
MiddlewareApiConfig,
TSHelpersExtractDispatchExtensions,
} from '@reduxjs/toolkit'
import { createDynamicMiddleware as cDM } from '@reduxjs/toolkit'
import type { Context } from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import {
createDispatchHook,
ReactReduxContext,
useDispatch as useDefaultDispatch,
} from 'react-redux'
import type { Action, Dispatch, Middleware, UnknownAction } from 'redux'
export type UseDispatchWithMiddlewareHook<
Middlewares extends Middleware<any, State, DispatchType>[] = [],
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType
export type CreateDispatchWithMiddlewareHook<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
<
Middlewares extends [
Middleware<any, State, DispatchType>,
...Middleware<any, State, DispatchType>[],
],
>(
...middlewares: Middlewares
): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>
withTypes<
MiddlewareConfig extends MiddlewareApiConfig,
>(): CreateDispatchWithMiddlewareHook<
GetState<MiddlewareConfig>,
GetDispatch<MiddlewareConfig>
>
}
type ActionFromDispatch<DispatchType extends Dispatch<Action>> =
DispatchType extends Dispatch<infer Action> ? Action : never
type ReactDynamicMiddlewareInstance<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = DynamicMiddlewareInstance<State, DispatchType> & {
createDispatchWithMiddlewareHookFactory: (
context?: Context<ReactReduxContextValue<
State,
ActionFromDispatch<DispatchType>
> | null>,
) => CreateDispatchWithMiddlewareHook<State, DispatchType>
createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<
State,
DispatchType
>
}
export const createDynamicMiddleware = <
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {
const instance = cDM<State, DispatchType>()
const createDispatchWithMiddlewareHookFactory = (
// @ts-ignore
context: Context<ReactReduxContextValue<
State,
ActionFromDispatch<DispatchType>
> | null> = ReactReduxContext,
) => {
const useDispatch =
context === ReactReduxContext
? useDefaultDispatch
: createDispatchHook(context)
function createDispatchWithMiddlewareHook<
Middlewares extends Middleware<any, State, DispatchType>[],
>(...middlewares: Middlewares) {
instance.addMiddleware(...middlewares)
return useDispatch
}
createDispatchWithMiddlewareHook.withTypes = () =>
createDispatchWithMiddlewareHook
return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<
State,
DispatchType
>
}
const createDispatchWithMiddlewareHook =
createDispatchWithMiddlewareHookFactory()
return {
...instance,
createDispatchWithMiddlewareHookFactory,
createDispatchWithMiddlewareHook,
}
}

View File

@@ -0,0 +1,95 @@
import type { Action, Middleware, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { configureStore } from '../../configureStore'
import { createDynamicMiddleware } from '../index'
const untypedInstance = createDynamicMiddleware()
interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
(n: 1): 1
}
const typedInstance = createDynamicMiddleware<number, AppDispatch>()
declare const staticMiddleware: Middleware<(n: 1) => 1>
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(typedInstance.middleware).concat(staticMiddleware),
})
declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
declare const addedMiddleware: Middleware<(n: 2) => 2>
describe('type tests', () => {
test('instance typed at creation ensures middleware compatibility with store', () => {
const store = configureStore({
reducer: () => '',
// @ts-expect-error
middleware: (gDM) => gDM().prepend(typedInstance.middleware),
})
})
test('instance typed at creation enforces correct middleware type', () => {
typedInstance.addMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const dispatch = store.dispatch(
typedInstance.withMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
),
)
})
test('withTypes() enforces correct middleware type', () => {
const addMiddleware = untypedInstance.addMiddleware.withTypes<{
state: number
dispatch: AppDispatch
}>()
addMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const withMiddleware = untypedInstance.withMiddleware.withTypes<{
state: number
dispatch: AppDispatch
}>()
const dispatch = store.dispatch(
withMiddleware(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
),
)
})
test('withMiddleware returns typed dispatch, with any applicable extensions', () => {
const dispatch = store.dispatch(
typedInstance.withMiddleware(addedMiddleware),
)
// standard
expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
// thunk
expectTypeOf(dispatch(() => 'foo')).toBeString()
// static
expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
// added
expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
})
})

View File

@@ -0,0 +1,74 @@
import type { Middleware } from 'redux'
import { createDynamicMiddleware } from '../index'
import { configureStore } from '../../configureStore'
import type { BaseActionCreator, PayloadAction } from '../../createAction'
import { createAction } from '../../createAction'
import { isAllOf } from '../../matchers'
const probeType = 'probeableMW/probe'
export interface ProbeMiddleware
extends BaseActionCreator<number, typeof probeType> {
<Id extends number>(id: Id): PayloadAction<Id, typeof probeType>
}
export const probeMiddleware = createAction(probeType) as ProbeMiddleware
const matchId =
<Id extends number>(id: Id) =>
(action: any): action is PayloadAction<Id> =>
action.payload === id
export const makeProbeableMiddleware = <Id extends number>(
id: Id,
): Middleware<{
(action: PayloadAction<Id, typeof probeType>): Id
}> => {
const isMiddlewareAction = isAllOf(probeMiddleware, matchId(id))
return (api) => (next) => (action) => {
if (isMiddlewareAction(action)) {
return id
}
return next(action)
}
}
const staticMiddleware = makeProbeableMiddleware(1)
describe('createDynamicMiddleware', () => {
it('allows injecting middleware after store instantiation', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
// normal, pre-inject
expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
// static
expect(store.dispatch(probeMiddleware(1))).toBe(1)
// inject
dynamicInstance.addMiddleware(makeProbeableMiddleware(2))
// injected
expect(store.dispatch(probeMiddleware(2))).toBe(2)
})
it('returns dispatch when withMiddleware is dispatched', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) => gDM().prepend(dynamicInstance.middleware),
})
// normal, pre-inject
expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
const dispatch = store.dispatch(
dynamicInstance.withMiddleware(makeProbeableMiddleware(2)),
)
expect(dispatch).toEqual(expect.any(Function))
expect(dispatch(probeMiddleware(2))).toBe(2)
})
})

View File

@@ -0,0 +1,81 @@
import type { Context } from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import type { Action, Middleware, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { createDynamicMiddleware } from '../react'
interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
(n: 1): 1
}
const untypedInstance = createDynamicMiddleware()
const typedInstance = createDynamicMiddleware<number, AppDispatch>()
declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
declare const customContext: Context<ReactReduxContextValue | null>
declare const addedMiddleware: Middleware<(n: 2) => 2>
describe('type tests', () => {
test('instance typed at creation enforces correct middleware type', () => {
const useDispatch = typedInstance.createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const createDispatchWithMiddlewareHook =
typedInstance.createDispatchWithMiddlewareHookFactory(customContext)
const useDispatchWithContext = createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
})
test('withTypes() enforces correct middleware type', () => {
const createDispatchWithMiddlewareHook =
untypedInstance.createDispatchWithMiddlewareHook.withTypes<{
state: number
dispatch: AppDispatch
}>()
const useDispatch = createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const createCustomDispatchWithMiddlewareHook = untypedInstance
.createDispatchWithMiddlewareHookFactory(customContext)
.withTypes<{
state: number
dispatch: AppDispatch
}>()
const useCustomDispatch = createCustomDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
})
test('useDispatchWithMW returns typed dispatch, with any applicable extensions', () => {
const useDispatchWithMW =
typedInstance.createDispatchWithMiddlewareHook(addedMiddleware)
const dispatch = useDispatchWithMW()
// standard
expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
// thunk
expectTypeOf(dispatch(() => 'foo')).toBeString()
// static
expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
// added
expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
})
})

View File

@@ -0,0 +1,101 @@
import * as React from 'react'
import { createDynamicMiddleware } from '../react'
import { configureStore } from '../../configureStore'
import { makeProbeableMiddleware, probeMiddleware } from './index.test'
import { render } from '@testing-library/react'
import type { Dispatch } from 'redux'
import type { ReactReduxContextValue } from 'react-redux'
import { Provider } from 'react-redux'
const staticMiddleware = makeProbeableMiddleware(1)
describe('createReactDynamicMiddleware', () => {
describe('createDispatchWithMiddlewareHook', () => {
it('injects middleware upon creation', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
// normal, pre-inject
expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
// static
expect(store.dispatch(probeMiddleware(1))).toBe(1)
const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
makeProbeableMiddleware(2),
)
// injected
expect(store.dispatch(probeMiddleware(2))).toBe(2)
})
it('returns dispatch', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
makeProbeableMiddleware(2),
)
let dispatch: Dispatch | undefined
function Component() {
dispatch = useDispatch()
return null
}
render(<Component />, {
wrapper: ({ children }) => (
<Provider store={store}>{children}</Provider>
),
})
expect(dispatch).toBe(store.dispatch)
})
})
describe('createDispatchWithMiddlewareHookFactory', () => {
it('returns the correct store dispatch', () => {
const dynamicInstance = createDynamicMiddleware()
const store = configureStore({
reducer: () => 0,
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
const store2 = configureStore({
reducer: () => '',
middleware: (gDM) =>
gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
})
const context = React.createContext<ReactReduxContextValue | null>(null)
const createDispatchWithMiddlewareHook =
dynamicInstance.createDispatchWithMiddlewareHookFactory(context)
const useDispatch = createDispatchWithMiddlewareHook(
makeProbeableMiddleware(2),
)
let dispatch: Dispatch | undefined
function Component() {
dispatch = useDispatch()
return null
}
render(<Component />, {
wrapper: ({ children }) => (
<Provider store={store}>
<Provider context={context} store={store2}>
{children}
</Provider>
</Provider>
),
})
expect(dispatch).toBe(store2.dispatch)
})
})
})

View File

@@ -0,0 +1,82 @@
import type { Dispatch, Middleware, MiddlewareAPI, UnknownAction } from 'redux'
import type { BaseActionCreator, PayloadAction } from '../createAction'
import type { GetState } from '../createAsyncThunk'
import type { ExtractDispatchExtensions, FallbackIfUnknown } from '../tsHelpers'
export type GetMiddlewareApi<MiddlewareApiConfig> = MiddlewareAPI<
GetDispatchType<MiddlewareApiConfig>,
GetState<MiddlewareApiConfig>
>
export type MiddlewareApiConfig = {
state?: unknown
dispatch?: Dispatch
}
// TODO: consolidate with cAT helpers?
export type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
dispatch: infer DispatchType
}
? FallbackIfUnknown<DispatchType, Dispatch>
: Dispatch
export type AddMiddleware<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
(...middlewares: Middleware<any, State, DispatchType>[]): void
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<
GetState<MiddlewareConfig>,
GetDispatchType<MiddlewareConfig>
>
}
export type WithMiddleware<
State = any,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = BaseActionCreator<
Middleware<any, State, DispatchType>[],
'dynamicMiddleware/add',
{ instanceId: string }
> & {
<Middlewares extends Middleware<any, State, DispatchType>[]>(
...middlewares: Middlewares
): PayloadAction<Middlewares, 'dynamicMiddleware/add', { instanceId: string }>
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<
GetState<MiddlewareConfig>,
GetDispatchType<MiddlewareConfig>
>
}
export interface DynamicDispatch {
// return a version of dispatch that knows about middleware
<Middlewares extends Middleware<any>[]>(
action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>,
): ExtractDispatchExtensions<Middlewares> & this
}
export type MiddlewareEntry<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
middleware: Middleware<any, State, DispatchType>
applied: Map<
MiddlewareAPI<DispatchType, State>,
ReturnType<Middleware<any, State, DispatchType>>
>
}
export type DynamicMiddleware<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = Middleware<DynamicDispatch, State, DispatchType>
export type DynamicMiddlewareInstance<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
middleware: DynamicMiddleware<State, DispatchType>
addMiddleware: AddMiddleware<State, DispatchType>
withMiddleware: WithMiddleware<State, DispatchType>
instanceId: string
}

View File

@@ -0,0 +1,47 @@
import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'
import { createInitialStateFactory } from './entity_state'
import { createSelectorsFactory } from './state_selectors'
import { createSortedStateAdapter } from './sorted_state_adapter'
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
import type { WithRequiredProp } from '../tsHelpers'
export function createEntityAdapter<T, Id extends EntityId>(
options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,
): EntityAdapter<T, Id>
export function createEntityAdapter<T extends { id: EntityId }>(
options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,
): EntityAdapter<T, T['id']>
/**
*
* @param options
*
* @public
*/
export function createEntityAdapter<T>(
options: EntityAdapterOptions<T, EntityId> = {},
): EntityAdapter<T, EntityId> {
const {
selectId,
sortComparer,
}: Required<EntityAdapterOptions<T, EntityId>> = {
sortComparer: false,
selectId: (instance: any) => instance.id,
...options,
}
const stateAdapter = sortComparer
? createSortedStateAdapter(selectId, sortComparer)
: createUnsortedStateAdapter(selectId)
const stateFactory = createInitialStateFactory(stateAdapter)
const selectorsFactory = createSelectorsFactory<T, EntityId>()
return {
selectId,
sortComparer,
...stateFactory,
...selectorsFactory,
...stateAdapter,
}
}

View File

@@ -0,0 +1,38 @@
import type {
EntityId,
EntityState,
EntityStateAdapter,
EntityStateFactory,
} from './models'
export function getInitialEntityState<T, Id extends EntityId>(): EntityState<
T,
Id
> {
return {
ids: [],
entities: {} as Record<Id, T>,
}
}
export function createInitialStateFactory<T, Id extends EntityId>(
stateAdapter: EntityStateAdapter<T, Id>,
): EntityStateFactory<T, Id> {
function getInitialState(
state?: undefined,
entities?: readonly T[] | Record<Id, T>,
): EntityState<T, Id>
function getInitialState<S extends object>(
additionalState: S,
entities?: readonly T[] | Record<Id, T>,
): EntityState<T, Id> & S
function getInitialState(
additionalState: any = {},
entities?: readonly T[] | Record<Id, T>,
): any {
const state = Object.assign(getInitialEntityState(), additionalState)
return entities ? stateAdapter.setAll(state, entities) : state
}
return { getInitialState }
}

View File

@@ -0,0 +1,8 @@
export { createEntityAdapter } from './create_adapter'
export type {
EntityState,
EntityAdapter,
Update,
IdSelector,
Comparer,
} from './models'

View File

@@ -0,0 +1,198 @@
import type { Draft } from 'immer'
import type { PayloadAction } from '../createAction'
import type { CastAny, Id } from '../tsHelpers'
import type { UncheckedIndexedAccess } from '../uncheckedindexed.js'
import type { GetSelectorsOptions } from './state_selectors'
/**
* @public
*/
export type EntityId = number | string
/**
* @public
*/
export type Comparer<T> = (a: T, b: T) => number
/**
* @public
*/
export type IdSelector<T, Id extends EntityId> = (model: T) => Id
/**
* @public
*/
export type Update<T, Id extends EntityId> = { id: Id; changes: Partial<T> }
/**
* @public
*/
export interface EntityState<T, Id extends EntityId> {
ids: Id[]
entities: Record<Id, T>
}
/**
* @public
*/
export interface EntityAdapterOptions<T, Id extends EntityId> {
selectId?: IdSelector<T, Id>
sortComparer?: false | Comparer<T>
}
export type PreventAny<S, T, Id extends EntityId> = CastAny<
S,
EntityState<T, Id>
>
export type DraftableEntityState<T, Id extends EntityId> =
| EntityState<T, Id>
| Draft<EntityState<T, Id>>
/**
* @public
*/
export interface EntityStateAdapter<T, Id extends EntityId> {
addOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: T,
): S
addOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
action: PayloadAction<T>,
): S
addMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
addMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
setOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: T,
): S
setOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
action: PayloadAction<T>,
): S
setMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
setMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
setAll<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
setAll<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
removeOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
key: Id,
): S
removeOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
key: PayloadAction<Id>,
): S
removeMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
keys: readonly Id[],
): S
removeMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
keys: PayloadAction<readonly Id[]>,
): S
removeAll<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
): S
updateOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
update: Update<T, Id>,
): S
updateOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
update: PayloadAction<Update<T, Id>>,
): S
updateMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
updates: ReadonlyArray<Update<T, Id>>,
): S
updateMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
updates: PayloadAction<ReadonlyArray<Update<T, Id>>>,
): S
upsertOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: T,
): S
upsertOne<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entity: PayloadAction<T>,
): S
upsertMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: readonly T[] | Record<Id, T>,
): S
upsertMany<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
entities: PayloadAction<readonly T[] | Record<Id, T>>,
): S
}
/**
* @public
*/
export interface EntitySelectors<T, V, IdType extends EntityId> {
selectIds: (state: V) => IdType[]
selectEntities: (state: V) => Record<IdType, T>
selectAll: (state: V) => T[]
selectTotal: (state: V) => number
selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>
}
/**
* @public
*/
export interface EntityStateFactory<T, Id extends EntityId> {
getInitialState(
state?: undefined,
entities?: Record<Id, T> | readonly T[],
): EntityState<T, Id>
getInitialState<S extends object>(
state: S,
entities?: Record<Id, T> | readonly T[],
): EntityState<T, Id> & S
}
/**
* @public
*/
export interface EntityAdapter<T, Id extends EntityId>
extends EntityStateAdapter<T, Id>,
EntityStateFactory<T, Id>,
Required<EntityAdapterOptions<T, Id>> {
getSelectors(
selectState?: undefined,
options?: GetSelectorsOptions,
): EntitySelectors<T, EntityState<T, Id>, Id>
getSelectors<V>(
selectState: (state: V) => EntityState<T, Id>,
options?: GetSelectorsOptions,
): EntitySelectors<T, V, Id>
}

View File

@@ -0,0 +1,266 @@
import type {
IdSelector,
Comparer,
EntityStateAdapter,
Update,
EntityId,
DraftableEntityState,
} from './models'
import { createStateOperator } from './state_adapter'
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
import {
selectIdValue,
ensureEntitiesArray,
splitAddedUpdatedEntities,
getCurrent,
} from './utils'
// Borrowed from Replay
export function findInsertIndex<T>(
sortedItems: T[],
item: T,
comparisonFunction: Comparer<T>,
): number {
let lowIndex = 0
let highIndex = sortedItems.length
while (lowIndex < highIndex) {
let middleIndex = (lowIndex + highIndex) >>> 1
const currentItem = sortedItems[middleIndex]
const res = comparisonFunction(item, currentItem)
if (res >= 0) {
lowIndex = middleIndex + 1
} else {
highIndex = middleIndex
}
}
return lowIndex
}
export function insert<T>(
sortedItems: T[],
item: T,
comparisonFunction: Comparer<T>,
): T[] {
const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction)
sortedItems.splice(insertAtIndex, 0, item)
return sortedItems
}
export function createSortedStateAdapter<T, Id extends EntityId>(
selectId: IdSelector<T, Id>,
comparer: Comparer<T>,
): EntityStateAdapter<T, Id> {
type R = DraftableEntityState<T, Id>
const { removeOne, removeMany, removeAll } =
createUnsortedStateAdapter(selectId)
function addOneMutably(entity: T, state: R): void {
return addManyMutably([entity], state)
}
function addManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
existingIds?: Id[],
): void {
newEntities = ensureEntitiesArray(newEntities)
const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids))
const addedKeys = new Set<Id>();
const models = newEntities.filter(
(model) => {
const modelId = selectIdValue(model, selectId);
const notAdded = !addedKeys.has(modelId);
if (notAdded) addedKeys.add(modelId);
return !existingKeys.has(modelId) && notAdded;
}
)
if (models.length !== 0) {
mergeFunction(state, models)
}
}
function setOneMutably(entity: T, state: R): void {
return setManyMutably([entity], state)
}
function setManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
let deduplicatedEntities = {} as Record<Id, T>;
newEntities = ensureEntitiesArray(newEntities)
if (newEntities.length !== 0) {
for (const item of newEntities) {
const entityId = selectId(item);
// For multiple items with the same ID, we should keep the last one.
deduplicatedEntities[entityId] = item;
delete (state.entities as Record<Id, T>)[entityId]
}
newEntities = ensureEntitiesArray(deduplicatedEntities);
mergeFunction(state, newEntities)
}
}
function setAllMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
state.entities = {} as Record<Id, T>
state.ids = []
addManyMutably(newEntities, state, [])
}
function updateOneMutably(update: Update<T, Id>, state: R): void {
return updateManyMutably([update], state)
}
function updateManyMutably(
updates: ReadonlyArray<Update<T, Id>>,
state: R,
): void {
let appliedUpdates = false
let replacedIds = false
for (let update of updates) {
const entity: T | undefined = (state.entities as Record<Id, T>)[update.id]
if (!entity) {
continue
}
appliedUpdates = true
Object.assign(entity, update.changes)
const newId = selectId(entity)
if (update.id !== newId) {
// We do support the case where updates can change an item's ID.
// This makes things trickier - go ahead and swap the IDs in state now.
replacedIds = true
delete (state.entities as Record<Id, T>)[update.id]
const oldIndex = (state.ids as Id[]).indexOf(update.id)
state.ids[oldIndex] = newId
;(state.entities as Record<Id, T>)[newId] = entity
}
}
if (appliedUpdates) {
mergeFunction(state, [], appliedUpdates, replacedIds)
}
}
function upsertOneMutably(entity: T, state: R): void {
return upsertManyMutably([entity], state)
}
function upsertManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(
newEntities,
selectId,
state,
)
if (added.length) {
addManyMutably(added, state, existingIdsArray)
}
if (updated.length) {
updateManyMutably(updated, state)
}
}
function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {
if (a.length !== b.length) {
return false
}
for (let i = 0; i < a.length; i++) {
if (a[i] === b[i]) {
continue
}
return false
}
return true
}
type MergeFunction = (
state: R,
addedItems: readonly T[],
appliedUpdates?: boolean,
replacedIds?: boolean,
) => void
const mergeFunction: MergeFunction = (
state,
addedItems,
appliedUpdates,
replacedIds,
) => {
const currentEntities = getCurrent(state.entities)
const currentIds = getCurrent(state.ids)
const stateEntities = state.entities as Record<Id, T>
let ids: Iterable<Id> = currentIds
if (replacedIds) {
ids = new Set(currentIds)
}
let sortedEntities: T[] = []
for (const id of ids) {
const entity = currentEntities[id]
if (entity) {
sortedEntities.push(entity)
}
}
const wasPreviouslyEmpty = sortedEntities.length === 0
// Insert/overwrite all new/updated
for (const item of addedItems) {
stateEntities[selectId(item)] = item
if (!wasPreviouslyEmpty) {
// Binary search insertion generally requires fewer comparisons
insert(sortedEntities, item, comparer)
}
}
if (wasPreviouslyEmpty) {
// All we have is the incoming values, sort them
sortedEntities = addedItems.slice().sort(comparer)
} else if (appliedUpdates) {
// We should have a _mostly_-sorted array already
sortedEntities.sort(comparer)
}
const newSortedIds = sortedEntities.map(selectId)
if (!areArraysEqual(currentIds, newSortedIds)) {
state.ids = newSortedIds
}
}
return {
removeOne,
removeMany,
removeAll,
addOne: createStateOperator(addOneMutably),
updateOne: createStateOperator(updateOneMutably),
upsertOne: createStateOperator(upsertOneMutably),
setOne: createStateOperator(setOneMutably),
setMany: createStateOperator(setManyMutably),
setAll: createStateOperator(setAllMutably),
addMany: createStateOperator(addManyMutably),
updateMany: createStateOperator(updateManyMutably),
upsertMany: createStateOperator(upsertManyMutably),
}
}

View File

@@ -0,0 +1,58 @@
import { createNextState, isDraft } from '../immerImports'
import type { Draft } from 'immer'
import type { EntityId, DraftableEntityState, PreventAny } from './models'
import type { PayloadAction } from '../createAction'
import { isFSA } from '../createAction'
export const isDraftTyped = isDraft as <T>(
value: T | Draft<T>,
) => value is Draft<T>
export function createSingleArgumentStateOperator<T, Id extends EntityId>(
mutator: (state: DraftableEntityState<T, Id>) => void,
) {
const operator = createStateOperator(
(_: undefined, state: DraftableEntityState<T, Id>) => mutator(state),
)
return function operation<S extends DraftableEntityState<T, Id>>(
state: PreventAny<S, T, Id>,
): S {
return operator(state as S, undefined)
}
}
export function createStateOperator<T, Id extends EntityId, R>(
mutator: (arg: R, state: DraftableEntityState<T, Id>) => void,
) {
return function operation<S extends DraftableEntityState<T, Id>>(
state: S,
arg: R | PayloadAction<R>,
): S {
function isPayloadActionArgument(
arg: R | PayloadAction<R>,
): arg is PayloadAction<R> {
return isFSA(arg)
}
const runMutator = (draft: DraftableEntityState<T, Id>) => {
if (isPayloadActionArgument(arg)) {
mutator(arg.payload, draft)
} else {
mutator(arg, draft)
}
}
if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {
// we must already be inside a `createNextState` call, likely because
// this is being wrapped in `createReducer` or `createSlice`.
// It's safe to just pass the draft to the mutator.
runMutator(state)
// since it's a draft, we'll just return it
return state
}
return createNextState(state, runMutator)
}
}

View File

@@ -0,0 +1,77 @@
import type { CreateSelectorFunction, Selector } from 'reselect'
import { createDraftSafeSelector } from '../createDraftSafeSelector'
import type { EntityId, EntitySelectors, EntityState } from './models'
type AnyFunction = (...args: any) => any
type AnyCreateSelectorFunction = CreateSelectorFunction<
<F extends AnyFunction>(f: F) => F,
<F extends AnyFunction>(f: F) => F
>
export type GetSelectorsOptions = {
createSelector?: AnyCreateSelectorFunction
}
export function createSelectorsFactory<T, Id extends EntityId>() {
function getSelectors(
selectState?: undefined,
options?: GetSelectorsOptions,
): EntitySelectors<T, EntityState<T, Id>, Id>
function getSelectors<V>(
selectState: (state: V) => EntityState<T, Id>,
options?: GetSelectorsOptions,
): EntitySelectors<T, V, Id>
function getSelectors<V>(
selectState?: (state: V) => EntityState<T, Id>,
options: GetSelectorsOptions = {},
): EntitySelectors<T, any, Id> {
const {
createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,
} = options
const selectIds = (state: EntityState<T, Id>) => state.ids
const selectEntities = (state: EntityState<T, Id>) => state.entities
const selectAll = createSelector(
selectIds,
selectEntities,
(ids, entities): T[] => ids.map((id) => entities[id]!),
)
const selectId = (_: unknown, id: Id) => id
const selectById = (entities: Record<Id, T>, id: Id) => entities[id]
const selectTotal = createSelector(selectIds, (ids) => ids.length)
if (!selectState) {
return {
selectIds,
selectEntities,
selectAll,
selectTotal,
selectById: createSelector(selectEntities, selectId, selectById),
}
}
const selectGlobalizedEntities = createSelector(
selectState as Selector<V, EntityState<T, Id>>,
selectEntities,
)
return {
selectIds: createSelector(selectState, selectIds),
selectEntities: selectGlobalizedEntities,
selectAll: createSelector(selectState, selectAll),
selectTotal: createSelector(selectState, selectTotal),
selectById: createSelector(
selectGlobalizedEntities,
selectId,
selectById,
),
}
}
return { getSelectors }
}

View File

@@ -0,0 +1,59 @@
import { createEntityAdapter, createSlice } from '../..'
import type {
PayloadAction,
Slice,
SliceCaseReducers,
UnknownAction,
} from '../..'
import type { EntityId, EntityState, IdSelector } from '../models'
import type { BookModel } from './fixtures/book'
describe('Entity Slice Enhancer', () => {
let slice: Slice<EntityState<BookModel, BookModel['id']>>
beforeEach(() => {
const indieSlice = entitySliceEnhancer({
name: 'book',
selectId: (book: BookModel) => book.id,
})
slice = indieSlice
})
it('exposes oneAdded', () => {
const book = {
id: '0',
title: 'Der Steppenwolf',
author: 'Herman Hesse',
}
const action = slice.actions.oneAdded(book)
const oneAdded = slice.reducer(undefined, action as UnknownAction)
expect(oneAdded.entities['0']).toBe(book)
})
})
interface EntitySliceArgs<T, Id extends EntityId> {
name: string
selectId: IdSelector<T, Id>
modelReducer?: SliceCaseReducers<T>
}
function entitySliceEnhancer<T, Id extends EntityId>({
name,
selectId,
modelReducer,
}: EntitySliceArgs<T, Id>) {
const modelAdapter = createEntityAdapter({
selectId,
})
return createSlice({
name,
initialState: modelAdapter.getInitialState(),
reducers: {
oneAdded(state, action: PayloadAction<T>) {
modelAdapter.addOne(state, action.payload)
},
...modelReducer,
},
})
}

View File

@@ -0,0 +1,104 @@
import type { EntityAdapter } from '../index'
import { createEntityAdapter } from '../index'
import type { PayloadAction } from '../../createAction'
import { createAction } from '../../createAction'
import { createSlice } from '../../createSlice'
import type { BookModel } from './fixtures/book'
describe('Entity State', () => {
let adapter: EntityAdapter<BookModel, string>
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
})
it('should let you get the initial state', () => {
const initialState = adapter.getInitialState()
expect(initialState).toEqual({
ids: [],
entities: {},
})
})
it('should let you provide additional initial state properties', () => {
const additionalProperties = { isHydrated: true }
const initialState = adapter.getInitialState(additionalProperties)
expect(initialState).toEqual({
...additionalProperties,
ids: [],
entities: {},
})
})
it('should let you provide initial entities', () => {
const book1: BookModel = { id: 'a', title: 'First' }
const initialState = adapter.getInitialState(undefined, [book1])
expect(initialState).toEqual({
ids: [book1.id],
entities: { [book1.id]: book1 },
})
const additionalProperties = { isHydrated: true }
const initialState2 = adapter.getInitialState(additionalProperties, [book1])
expect(initialState2).toEqual({
...additionalProperties,
ids: [book1.id],
entities: { [book1.id]: book1 },
})
})
it('should allow methods to be passed as reducers', () => {
const upsertBook = createAction<BookModel>('otherBooks/upsert')
const booksSlice = createSlice({
name: 'books',
initialState: adapter.getInitialState(),
reducers: {
addOne: adapter.addOne,
removeOne(state, action: PayloadAction<string>) {
// TODO The nested `produce` calls don't mutate `state` here as I would have expected.
// TODO (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
// TODO However, this works if we _return_ the new plain result value instead
// TODO See https://github.com/immerjs/immer/issues/533
const result = adapter.removeOne(state, action)
return result
},
},
extraReducers: (builder) => {
builder.addCase(upsertBook, (state, action) => {
return adapter.upsertOne(state, action)
})
},
})
const { addOne, removeOne } = booksSlice.actions
const { reducer } = booksSlice
const selectors = adapter.getSelectors()
const book1: BookModel = { id: 'a', title: 'First' }
const book1a: BookModel = { id: 'a', title: 'Second' }
const afterAddOne = reducer(undefined, addOne(book1))
expect(afterAddOne.entities[book1.id]).toBe(book1)
const afterRemoveOne = reducer(afterAddOne, removeOne(book1.id))
expect(afterRemoveOne.entities[book1.id]).toBeUndefined()
expect(selectors.selectTotal(afterRemoveOne)).toBe(0)
const afterUpsertFirst = reducer(afterRemoveOne, upsertBook(book1))
const afterUpsertSecond = reducer(afterUpsertFirst, upsertBook(book1a))
expect(afterUpsertSecond.entities[book1.id]).toEqual(book1a)
expect(selectors.selectTotal(afterUpsertSecond)).toBe(1)
})
})

View File

@@ -0,0 +1,26 @@
export interface BookModel {
id: string
title: string
author?: string
}
export const AClockworkOrange: BookModel = Object.freeze({
id: 'aco',
title: 'A Clockwork Orange',
})
export const AnimalFarm: BookModel = Object.freeze({
id: 'af',
title: 'Animal Farm',
})
export const TheGreatGatsby: BookModel = Object.freeze({
id: 'tgg',
title: 'The Great Gatsby',
})
export const TheHobbit: BookModel = Object.freeze({
id: 'th',
title: 'The Hobbit',
author: 'J. R. R. Tolkien',
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
import type { EntityAdapter } from '../index'
import { createEntityAdapter } from '../index'
import type { PayloadAction } from '../../createAction'
import { configureStore } from '../../configureStore'
import { createSlice } from '../../createSlice'
import type { BookModel } from './fixtures/book'
describe('createStateOperator', () => {
let adapter: EntityAdapter<BookModel, string>
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
})
it('Correctly mutates a draft state when inside `createNextState', () => {
const booksSlice = createSlice({
name: 'books',
initialState: adapter.getInitialState(),
reducers: {
// We should be able to call an adapter method as a mutating helper in a larger reducer
addOne(state, action: PayloadAction<BookModel>) {
// Originally, having nested `produce` calls don't mutate `state` here as I would have expected.
// (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
// One woarkound was to return the new plain result value instead
// See https://github.com/immerjs/immer/issues/533
// However, after tweaking `createStateOperator` to check if the argument is a draft,
// we can just treat the operator as strictly mutating, without returning a result,
// and the result should be correct.
const result = adapter.addOne(state, action)
expect(result.ids.length).toBe(1)
//Deliberately _don't_ return result
},
// We should also be able to pass them individually as case reducers
addAnother: adapter.addOne,
},
})
const { addOne, addAnother } = booksSlice.actions
const store = configureStore({
reducer: {
books: booksSlice.reducer,
},
})
const book1: BookModel = { id: 'a', title: 'First' }
store.dispatch(addOne(book1))
const state1 = store.getState()
expect(state1.books.ids.length).toBe(1)
expect(state1.books.entities['a']).toBe(book1)
const book2: BookModel = { id: 'b', title: 'Second' }
store.dispatch(addAnother(book2))
const state2 = store.getState()
expect(state2.books.ids.length).toBe(2)
expect(state2.books.entities['b']).toBe(book2)
})
})

View File

@@ -0,0 +1,154 @@
import { createDraftSafeSelectorCreator } from '../../createDraftSafeSelector'
import type { EntityAdapter, EntityState } from '../index'
import { createEntityAdapter } from '../index'
import type { EntitySelectors } from '../models'
import type { BookModel } from './fixtures/book'
import { AClockworkOrange, AnimalFarm, TheGreatGatsby } from './fixtures/book'
import type { Selector } from 'reselect'
import { createSelector, weakMapMemoize } from 'reselect'
import { vi } from 'vitest'
describe('Entity State Selectors', () => {
describe('Composed Selectors', () => {
interface State {
books: EntityState<BookModel, string>
}
let adapter: EntityAdapter<BookModel, string>
let selectors: EntitySelectors<BookModel, State, string>
let state: State
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
state = {
books: adapter.setAll(adapter.getInitialState(), [
AClockworkOrange,
AnimalFarm,
TheGreatGatsby,
]),
}
selectors = adapter.getSelectors((state: State) => state.books)
})
it('should create a selector for selecting the ids', () => {
const ids = selectors.selectIds(state)
expect(ids).toEqual(state.books.ids)
})
it('should create a selector for selecting the entities', () => {
const entities = selectors.selectEntities(state)
expect(entities).toEqual(state.books.entities)
})
it('should create a selector for selecting the list of models', () => {
const models = selectors.selectAll(state)
expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
})
it('should create a selector for selecting the count of models', () => {
const total = selectors.selectTotal(state)
expect(total).toEqual(3)
})
it('should create a selector for selecting a single item by ID', () => {
const first = selectors.selectById(state, AClockworkOrange.id)
expect(first).toBe(AClockworkOrange)
const second = selectors.selectById(state, AnimalFarm.id)
expect(second).toBe(AnimalFarm)
})
})
describe('Uncomposed Selectors', () => {
type State = EntityState<BookModel, string>
let adapter: EntityAdapter<BookModel, string>
let selectors: EntitySelectors<
BookModel,
EntityState<BookModel, string>,
string
>
let state: State
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
state = adapter.setAll(adapter.getInitialState(), [
AClockworkOrange,
AnimalFarm,
TheGreatGatsby,
])
selectors = adapter.getSelectors()
})
it('should create a selector for selecting the ids', () => {
const ids = selectors.selectIds(state)
expect(ids).toEqual(state.ids)
})
it('should create a selector for selecting the entities', () => {
const entities = selectors.selectEntities(state)
expect(entities).toEqual(state.entities)
})
it('should type single entity from Dictionary as entity type or undefined', () => {
expectType<
Selector<EntityState<BookModel, string>, BookModel | undefined>
>(createSelector(selectors.selectEntities, (entities) => entities[0]))
})
it('should create a selector for selecting the list of models', () => {
const models = selectors.selectAll(state)
expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
})
it('should create a selector for selecting the count of models', () => {
const total = selectors.selectTotal(state)
expect(total).toEqual(3)
})
it('should create a selector for selecting a single item by ID', () => {
const first = selectors.selectById(state, AClockworkOrange.id)
expect(first).toBe(AClockworkOrange)
const second = selectors.selectById(state, AnimalFarm.id)
expect(second).toBe(AnimalFarm)
})
})
describe('custom createSelector instance', () => {
it('should use the custom createSelector function if provided', () => {
const memoizeSpy = vi.fn(
// test that we're allowed to pass memoizers with different options, as long as they're optional
<F extends (...args: any[]) => any>(fn: F, param?: boolean) => fn,
)
const createCustomSelector = createDraftSafeSelectorCreator(memoizeSpy)
const adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
adapter.getSelectors(undefined, { createSelector: createCustomSelector })
expect(memoizeSpy).toHaveBeenCalled()
memoizeSpy.mockClear()
})
})
})
function expectType<T>(t: T) {
return t
}

View File

@@ -0,0 +1,759 @@
import type { EntityAdapter, EntityState } from '../models'
import { createEntityAdapter } from '../create_adapter'
import type { BookModel } from './fixtures/book'
import {
TheGreatGatsby,
AClockworkOrange,
AnimalFarm,
TheHobbit,
} from './fixtures/book'
import { createNextState } from '../..'
describe('Unsorted State Adapter', () => {
let adapter: EntityAdapter<BookModel, string>
let state: EntityState<BookModel, string>
beforeAll(() => {
//eslint-disable-next-line
Object.defineProperty(Array.prototype, 'unwantedField', {
enumerable: true,
configurable: true,
value: 'This should not appear anywhere',
})
})
afterAll(() => {
delete (Array.prototype as any).unwantedField
})
beforeEach(() => {
adapter = createEntityAdapter({
selectId: (book: BookModel) => book.id,
})
state = { ids: [], entities: {} }
})
it('should let you add one entity to the state', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
expect(withOneEntity).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
},
})
})
it('should not change state if you attempt to re-add an entity', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const readded = adapter.addOne(withOneEntity, TheGreatGatsby)
expect(readded).toBe(withOneEntity)
})
it('should let you add many entities to the state', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withManyMore = adapter.addMany(withOneEntity, [
AClockworkOrange,
AnimalFarm,
])
expect(withManyMore).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you add many entities to the state from a dictionary', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withManyMore = adapter.addMany(withOneEntity, {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
})
expect(withManyMore).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you add the only first occurrence for duplicate ids', () => {
const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
const withOne = adapter.setAll(state, [TheGreatGatsby])
const withMany = adapter.addMany(withOne, [
{ ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
])
expect(withMany).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
[AClockworkOrange.id]: {
...AClockworkOrange,
...firstEntry,
},
},
})
})
it('should remove existing and add new ones on setAll', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withAll = adapter.setAll(withOneEntity, [
AClockworkOrange,
AnimalFarm,
])
expect(withAll).toEqual({
ids: [AClockworkOrange.id, AnimalFarm.id],
entities: {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should remove existing and add new ones on setAll when passing in a dictionary', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withAll = adapter.setAll(withOneEntity, {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
})
expect(withAll).toEqual({
ids: [AClockworkOrange.id, AnimalFarm.id],
entities: {
[AClockworkOrange.id]: AClockworkOrange,
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you add remove an entity from the state', () => {
const withOneEntity = adapter.addOne(state, TheGreatGatsby)
const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)
expect(withoutOne).toEqual({
ids: [],
entities: {},
})
})
it('should let you remove many entities by id from the state', () => {
const withAll = adapter.setAll(state, [
TheGreatGatsby,
AClockworkOrange,
AnimalFarm,
])
const withoutMany = adapter.removeMany(withAll, [
TheGreatGatsby.id,
AClockworkOrange.id,
])
expect(withoutMany).toEqual({
ids: [AnimalFarm.id],
entities: {
[AnimalFarm.id]: AnimalFarm,
},
})
})
it('should let you remove all entities from the state', () => {
const withAll = adapter.setAll(state, [
TheGreatGatsby,
AClockworkOrange,
AnimalFarm,
])
const withoutAll = adapter.removeAll(withAll)
expect(withoutAll).toEqual({
ids: [],
entities: {},
})
})
it('should let you update an entity in the state', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const withUpdates = adapter.updateOne(withOne, {
id: TheGreatGatsby.id,
changes,
})
expect(withUpdates).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...changes,
},
},
})
})
it('should not change state if you attempt to update an entity that has not been added', () => {
const withUpdates = adapter.updateOne(state, {
id: TheGreatGatsby.id,
changes: { title: 'A New Title' },
})
expect(withUpdates).toBe(state)
})
it('should not change ids state if you attempt to update an entity that has already been added', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const withUpdates = adapter.updateOne(withOne, {
id: TheGreatGatsby.id,
changes,
})
expect(withOne.ids).toBe(withUpdates.ids)
})
it('should let you update the id of entity', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { id: 'A New Id' }
const withUpdates = adapter.updateOne(withOne, {
id: TheGreatGatsby.id,
changes,
})
expect(withUpdates).toEqual({
ids: [changes.id],
entities: {
[changes.id]: {
...TheGreatGatsby,
...changes,
},
},
})
})
it('should let you update many entities by id in the state', () => {
const firstChange = { title: 'First Change' }
const secondChange = { title: 'Second Change' }
const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])
const withUpdates = adapter.updateMany(withMany, [
{ id: TheGreatGatsby.id, changes: firstChange },
{ id: AClockworkOrange.id, changes: secondChange },
])
expect(withUpdates).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...firstChange,
},
[AClockworkOrange.id]: {
...AClockworkOrange,
...secondChange,
},
},
})
})
it("doesn't break when multiple renames of one item occur", () => {
const withA = adapter.addOne(state, { id: 'a', title: 'First' })
const withUpdates = adapter.updateMany(withA, [
{ id: 'a', changes: { id: 'b' } },
{ id: 'a', changes: { id: 'c' } },
])
const { ids, entities } = withUpdates
/*
Original code failed with a mish-mash of values, like:
{
ids: [ 'c' ],
entities: { b: { id: 'b', title: 'First' }, c: { id: 'c' } }
}
We now expect that only 'c' will be left:
{
ids: [ 'c' ],
entities: { c: { id: 'c', title: 'First' } }
}
*/
expect(ids.length).toBe(1)
expect(ids).toEqual(['c'])
expect(entities.a).toBeFalsy()
expect(entities.b).toBeFalsy()
expect(entities.c).toBeTruthy()
})
it('should let you add one entity to the state with upsert()', () => {
const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)
expect(withOneEntity).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
},
})
})
it('should let you update an entity in the state with upsert()', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const withUpdates = adapter.upsertOne(withOne, {
...TheGreatGatsby,
...changes,
})
expect(withUpdates).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...changes,
},
},
})
})
it('should let you upsert many entities in the state', () => {
const firstChange = { title: 'First Change' }
const withMany = adapter.setAll(state, [TheGreatGatsby])
const withUpserts = adapter.upsertMany(withMany, [
{ ...TheGreatGatsby, ...firstChange },
AClockworkOrange,
])
expect(withUpserts).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...firstChange,
},
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it('should let you upsert many entities in the state when passing in a dictionary', () => {
const firstChange = { title: 'Zack' }
const withMany = adapter.setAll(state, [TheGreatGatsby])
const withUpserts = adapter.upsertMany(withMany, {
[TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },
[AClockworkOrange.id]: AClockworkOrange,
})
expect(withUpserts).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: {
...TheGreatGatsby,
...firstChange,
},
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it('should let you add a new entity then apply changes to it', () => {
const firstChange = { author: TheHobbit.author }
const secondChange = { title: 'Zack' }
const withMany = adapter.setAll(state, [TheGreatGatsby])
const withUpserts = adapter.upsertMany(withMany, [
{...AClockworkOrange}, { ...AClockworkOrange, ...firstChange }, {...AClockworkOrange, ...secondChange}
])
expect(withUpserts).toEqual({
ids: [TheGreatGatsby.id, AClockworkOrange.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
[AClockworkOrange.id]: {
...AClockworkOrange,
...firstChange,
...secondChange,
},
},
})
})
it('should let you add a new entity in the state with setOne()', () => {
const withOne = adapter.setOne(state, TheGreatGatsby)
expect(withOne).toEqual({
ids: [TheGreatGatsby.id],
entities: {
[TheGreatGatsby.id]: TheGreatGatsby,
},
})
})
it('should let you replace an entity in the state with setOne()', () => {
let withOne = adapter.setOne(state, TheHobbit)
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
withOne = adapter.setOne(withOne, changeWithoutAuthor)
expect(withOne).toEqual({
ids: [TheHobbit.id],
entities: {
[TheHobbit.id]: changeWithoutAuthor,
},
})
})
it('should let you set many entities in the state', () => {
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
const withMany = adapter.setAll(state, [TheHobbit])
const withSetMany = adapter.setMany(withMany, [
changeWithoutAuthor,
AClockworkOrange,
])
expect(withSetMany).toEqual({
ids: [TheHobbit.id, AClockworkOrange.id],
entities: {
[TheHobbit.id]: changeWithoutAuthor,
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it('should let you set many entities in the state when passing in a dictionary', () => {
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
const withMany = adapter.setAll(state, [TheHobbit])
const withSetMany = adapter.setMany(withMany, {
[TheHobbit.id]: changeWithoutAuthor,
[AClockworkOrange.id]: AClockworkOrange,
})
expect(withSetMany).toEqual({
ids: [TheHobbit.id, AClockworkOrange.id],
entities: {
[TheHobbit.id]: changeWithoutAuthor,
[AClockworkOrange.id]: AClockworkOrange,
},
})
})
it("only returns one entry for that id in the id's array", () => {
const book1: BookModel = { id: 'a', title: 'First' }
const book2: BookModel = { id: 'b', title: 'Second' }
const initialState = adapter.getInitialState()
const withItems = adapter.addMany(initialState, [book1, book2])
expect(withItems.ids).toEqual(['a', 'b'])
const withUpdate = adapter.updateOne(withItems, {
id: 'a',
changes: { id: 'b' },
})
expect(withUpdate.ids).toEqual(['b'])
expect(withUpdate.entities['b']!.title).toBe(book1.title)
})
describe('can be used mutably when wrapped in createNextState', () => {
test('removeAll', () => {
const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
const result = createNextState(withTwo, (draft) => {
adapter.removeAll(draft)
})
expect(result).toEqual({
entities: {},
ids: [],
})
})
test('addOne', () => {
const result = createNextState(state, (draft) => {
adapter.addOne(draft, TheGreatGatsby)
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg'],
})
})
test('addMany', () => {
const result = createNextState(state, (draft) => {
adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg', 'af'],
})
})
test('setAll', () => {
const result = createNextState(state, (draft) => {
adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg', 'af'],
})
})
test('updateOne', () => {
const withOne = adapter.addOne(state, TheGreatGatsby)
const changes = { title: 'A New Hope' }
const result = createNextState(withOne, (draft) => {
adapter.updateOne(draft, {
id: TheGreatGatsby.id,
changes,
})
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'A New Hope',
},
},
ids: ['tgg'],
})
})
test('updateMany', () => {
const firstChange = { title: 'First Change' }
const secondChange = { title: 'Second Change' }
const thirdChange = { title: 'Third Change' }
const fourthChange = { author: 'Fourth Change' }
const withMany = adapter.setAll(state, [
TheGreatGatsby,
AClockworkOrange,
TheHobbit,
])
const result = createNextState(withMany, (draft) => {
adapter.updateMany(draft, [
{ id: TheHobbit.id, changes: firstChange },
{ id: TheGreatGatsby.id, changes: secondChange },
{ id: AClockworkOrange.id, changes: thirdChange },
{ id: TheHobbit.id, changes: fourthChange },
])
})
expect(result).toEqual({
entities: {
aco: {
id: 'aco',
title: 'Third Change',
},
tgg: {
id: 'tgg',
title: 'Second Change',
},
th: {
author: 'Fourth Change',
id: 'th',
title: 'First Change',
},
},
ids: ['tgg', 'aco', 'th'],
})
})
test('upsertOne (insert)', () => {
const result = createNextState(state, (draft) => {
adapter.upsertOne(draft, TheGreatGatsby)
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg'],
})
})
test('upsertOne (update)', () => {
const withOne = adapter.upsertOne(state, TheGreatGatsby)
const result = createNextState(withOne, (draft) => {
adapter.upsertOne(draft, {
id: TheGreatGatsby.id,
title: 'A New Hope',
})
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'A New Hope',
},
},
ids: ['tgg'],
})
})
test('upsertMany', () => {
const withOne = adapter.upsertOne(state, TheGreatGatsby)
const result = createNextState(withOne, (draft) => {
adapter.upsertMany(draft, [
{
id: TheGreatGatsby.id,
title: 'A New Hope',
},
AnimalFarm,
])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
tgg: {
id: 'tgg',
title: 'A New Hope',
},
},
ids: ['tgg', 'af'],
})
})
test('setOne (insert)', () => {
const result = createNextState(state, (draft) => {
adapter.setOne(draft, TheGreatGatsby)
})
expect(result).toEqual({
entities: {
tgg: {
id: 'tgg',
title: 'The Great Gatsby',
},
},
ids: ['tgg'],
})
})
test('setOne (update)', () => {
const withOne = adapter.setOne(state, TheHobbit)
const result = createNextState(withOne, (draft) => {
adapter.setOne(draft, {
id: TheHobbit.id,
title: 'Silmarillion',
})
})
expect(result).toEqual({
entities: {
th: {
id: 'th',
title: 'Silmarillion',
},
},
ids: ['th'],
})
})
test('setMany', () => {
const withOne = adapter.setOne(state, TheHobbit)
const result = createNextState(withOne, (draft) => {
adapter.setMany(draft, [
{
id: TheHobbit.id,
title: 'Silmarillion',
},
AnimalFarm,
])
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
th: {
id: 'th',
title: 'Silmarillion',
},
},
ids: ['th', 'af'],
})
})
test('removeOne', () => {
const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
const result = createNextState(withTwo, (draft) => {
adapter.removeOne(draft, TheGreatGatsby.id)
})
expect(result).toEqual({
entities: {
af: {
id: 'af',
title: 'Animal Farm',
},
},
ids: ['af'],
})
})
test('removeMany', () => {
const withThree = adapter.addMany(state, [
TheGreatGatsby,
AnimalFarm,
AClockworkOrange,
])
const result = createNextState(withThree, (draft) => {
adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])
})
expect(result).toEqual({
entities: {
aco: {
id: 'aco',
title: 'A Clockwork Orange',
},
},
ids: ['aco'],
})
})
})
})

View File

@@ -0,0 +1,71 @@
import { noop } from '@internal/listenerMiddleware/utils'
import { AClockworkOrange } from './fixtures/book'
describe('Entity utils', () => {
describe(`selectIdValue()`, () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
beforeEach(() => {
vi.resetModules() // this is important - it clears the cache
vi.stubEnv('NODE_ENV', 'development')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.clearAllMocks()
})
afterAll(() => {
vi.restoreAllMocks()
})
it('should not warn when key does exist', async () => {
const { selectIdValue } = await import('../utils')
selectIdValue(AClockworkOrange, (book: any) => book.id)
expect(consoleWarnSpy).not.toHaveBeenCalled()
})
it('should warn when key does not exist in dev mode', async () => {
const { selectIdValue } = await import('../utils')
expect(process.env.NODE_ENV).toBe('development')
selectIdValue(AClockworkOrange, (book: any) => book.foo)
expect(consoleWarnSpy).toHaveBeenCalledOnce()
})
it('should warn when key is undefined in dev mode', async () => {
const { selectIdValue } = await import('../utils')
expect(process.env.NODE_ENV).toBe('development')
const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
expect(consoleWarnSpy).toHaveBeenCalledOnce()
})
it('should not warn when key does not exist in prod mode', async () => {
vi.stubEnv('NODE_ENV', 'production')
const { selectIdValue } = await import('../utils')
selectIdValue(AClockworkOrange, (book: any) => book.foo)
expect(consoleWarnSpy).not.toHaveBeenCalled()
})
it('should not warn when key is undefined in prod mode', async () => {
vi.stubEnv('NODE_ENV', 'production')
const { selectIdValue } = await import('../utils')
const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
expect(consoleWarnSpy).not.toHaveBeenCalled()
})
})
})

View File

@@ -0,0 +1,204 @@
import type { Draft } from 'immer'
import type {
EntityStateAdapter,
IdSelector,
Update,
EntityId,
DraftableEntityState,
} from './models'
import {
createStateOperator,
createSingleArgumentStateOperator,
} from './state_adapter'
import {
selectIdValue,
ensureEntitiesArray,
splitAddedUpdatedEntities,
} from './utils'
export function createUnsortedStateAdapter<T, Id extends EntityId>(
selectId: IdSelector<T, Id>,
): EntityStateAdapter<T, Id> {
type R = DraftableEntityState<T, Id>
function addOneMutably(entity: T, state: R): void {
const key = selectIdValue(entity, selectId)
if (key in state.entities) {
return
}
state.ids.push(key as Id & Draft<Id>)
;(state.entities as Record<Id, T>)[key] = entity
}
function addManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
for (const entity of newEntities) {
addOneMutably(entity, state)
}
}
function setOneMutably(entity: T, state: R): void {
const key = selectIdValue(entity, selectId)
if (!(key in state.entities)) {
state.ids.push(key as Id & Draft<Id>)
}
;(state.entities as Record<Id, T>)[key] = entity
}
function setManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
for (const entity of newEntities) {
setOneMutably(entity, state)
}
}
function setAllMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
newEntities = ensureEntitiesArray(newEntities)
state.ids = []
state.entities = {} as Record<Id, T>
addManyMutably(newEntities, state)
}
function removeOneMutably(key: Id, state: R): void {
return removeManyMutably([key], state)
}
function removeManyMutably(keys: readonly Id[], state: R): void {
let didMutate = false
keys.forEach((key) => {
if (key in state.entities) {
delete (state.entities as Record<Id, T>)[key]
didMutate = true
}
})
if (didMutate) {
state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as
| Id[]
| Draft<Id[]>
}
}
function removeAllMutably(state: R): void {
Object.assign(state, {
ids: [],
entities: {},
})
}
function takeNewKey(
keys: { [id: string]: Id },
update: Update<T, Id>,
state: R,
): boolean {
const original: T | undefined = (state.entities as Record<Id, T>)[update.id]
if (original === undefined) {
return false
}
const updated: T = Object.assign({}, original, update.changes)
const newKey = selectIdValue(updated, selectId)
const hasNewKey = newKey !== update.id
if (hasNewKey) {
keys[update.id] = newKey
delete (state.entities as Record<Id, T>)[update.id]
}
;(state.entities as Record<Id, T>)[newKey] = updated
return hasNewKey
}
function updateOneMutably(update: Update<T, Id>, state: R): void {
return updateManyMutably([update], state)
}
function updateManyMutably(
updates: ReadonlyArray<Update<T, Id>>,
state: R,
): void {
const newKeys: { [id: string]: Id } = {}
const updatesPerEntity: { [id: string]: Update<T, Id> } = {}
updates.forEach((update) => {
// Only apply updates to entities that currently exist
if (update.id in state.entities) {
// If there are multiple updates to one entity, merge them together
updatesPerEntity[update.id] = {
id: update.id,
// Spreads ignore falsy values, so this works even if there isn't
// an existing update already at this key
changes: {
...updatesPerEntity[update.id]?.changes,
...update.changes,
},
}
}
})
updates = Object.values(updatesPerEntity)
const didMutateEntities = updates.length > 0
if (didMutateEntities) {
const didMutateIds =
updates.filter((update) => takeNewKey(newKeys, update, state)).length >
0
if (didMutateIds) {
state.ids = Object.values(state.entities).map((e) =>
selectIdValue(e as T, selectId),
)
}
}
}
function upsertOneMutably(entity: T, state: R): void {
return upsertManyMutably([entity], state)
}
function upsertManyMutably(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
const [added, updated] = splitAddedUpdatedEntities<T, Id>(
newEntities,
selectId,
state,
)
addManyMutably(added, state)
updateManyMutably(updated, state)
}
return {
removeAll: createSingleArgumentStateOperator(removeAllMutably),
addOne: createStateOperator(addOneMutably),
addMany: createStateOperator(addManyMutably),
setOne: createStateOperator(setOneMutably),
setMany: createStateOperator(setManyMutably),
setAll: createStateOperator(setAllMutably),
updateOne: createStateOperator(updateOneMutably),
updateMany: createStateOperator(updateManyMutably),
upsertOne: createStateOperator(upsertOneMutably),
upsertMany: createStateOperator(upsertManyMutably),
removeOne: createStateOperator(removeOneMutably),
removeMany: createStateOperator(removeManyMutably),
}
}

View File

@@ -0,0 +1,68 @@
import type { Draft } from 'immer'
import { current, isDraft } from '../immerImports'
import type {
DraftableEntityState,
EntityId,
IdSelector,
Update,
} from './models'
export function selectIdValue<T, Id extends EntityId>(
entity: T,
selectId: IdSelector<T, Id>,
) {
const key = selectId(entity)
if (process.env.NODE_ENV !== 'production' && key === undefined) {
console.warn(
'The entity passed to the `selectId` implementation returned undefined.',
'You should probably provide your own `selectId` implementation.',
'The entity that was passed:',
entity,
'The `selectId` implementation:',
selectId.toString(),
)
}
return key
}
export function ensureEntitiesArray<T, Id extends EntityId>(
entities: readonly T[] | Record<Id, T>,
): readonly T[] {
if (!Array.isArray(entities)) {
entities = Object.values(entities)
}
return entities
}
export function getCurrent<T>(value: T | Draft<T>): T {
return (isDraft(value) ? current(value) : value) as T
}
export function splitAddedUpdatedEntities<T, Id extends EntityId>(
newEntities: readonly T[] | Record<Id, T>,
selectId: IdSelector<T, Id>,
state: DraftableEntityState<T, Id>,
): [T[], Update<T, Id>[], Id[]] {
newEntities = ensureEntitiesArray(newEntities)
const existingIdsArray = getCurrent(state.ids)
const existingIds = new Set<Id>(existingIdsArray)
const added: T[] = []
const addedIds = new Set<Id>([])
const updated: Update<T, Id>[] = []
for (const entity of newEntities) {
const id = selectIdValue(entity, selectId)
if (existingIds.has(id) || addedIds.has(id)) {
updated.push({ id, changes: entity })
} else {
addedIds.add(id)
added.push(entity)
}
}
return [added, updated, existingIdsArray]
}

View File

@@ -0,0 +1,13 @@
/**
* Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
*
* Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
* during build.
* @param {number} code
*/
export function formatProdErrorMessage(code: number) {
return (
`Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` +
'use the non-minified dev environment for full errors. '
)
}

View File

@@ -0,0 +1,31 @@
import type { StoreEnhancer } from 'redux'
import type { AutoBatchOptions } from './autoBatchEnhancer'
import { autoBatchEnhancer } from './autoBatchEnhancer'
import { Tuple } from './utils'
import type { Middlewares } from './configureStore'
import type { ExtractDispatchExtensions } from './tsHelpers'
type GetDefaultEnhancersOptions = {
autoBatch?: boolean | AutoBatchOptions
}
export type GetDefaultEnhancers<M extends Middlewares<any>> = (
options?: GetDefaultEnhancersOptions,
) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>
export const buildGetDefaultEnhancers = <M extends Middlewares<any>>(
middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>,
): GetDefaultEnhancers<M> =>
function getDefaultEnhancers(options) {
const { autoBatch = true } = options ?? {}
let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer)
if (autoBatch) {
enhancerArray.push(
autoBatchEnhancer(
typeof autoBatch === 'object' ? autoBatch : undefined,
),
)
}
return enhancerArray as any
}

View File

@@ -0,0 +1,113 @@
import type { Middleware, UnknownAction } from 'redux'
import type { ThunkMiddleware } from 'redux-thunk'
import { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk'
import type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
import { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'
/* PROD_START_REMOVE_UMD */
import { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'
/* PROD_STOP_REMOVE_UMD */
import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'
import { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'
import type { ExcludeFromTuple } from './tsHelpers'
import { Tuple } from './utils'
function isBoolean(x: any): x is boolean {
return typeof x === 'boolean'
}
interface ThunkOptions<E = any> {
extraArgument: E
}
interface GetDefaultMiddlewareOptions {
thunk?: boolean | ThunkOptions
immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions
serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions
actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions
}
export type ThunkMiddlewareFor<
S,
O extends GetDefaultMiddlewareOptions = {},
> = O extends {
thunk: false
}
? never
: O extends { thunk: { extraArgument: infer E } }
? ThunkMiddleware<S, UnknownAction, E>
: ThunkMiddleware<S, UnknownAction>
export type GetDefaultMiddleware<S = any> = <
O extends GetDefaultMiddlewareOptions = {
thunk: true
immutableCheck: true
serializableCheck: true
actionCreatorCheck: true
},
>(
options?: O,
) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>
export const buildGetDefaultMiddleware = <S = any>(): GetDefaultMiddleware<S> =>
function getDefaultMiddleware(options) {
const {
thunk = true,
immutableCheck = true,
serializableCheck = true,
actionCreatorCheck = true,
} = options ?? {}
let middlewareArray = new Tuple<Middleware[]>()
if (thunk) {
if (isBoolean(thunk)) {
middlewareArray.push(thunkMiddleware)
} else {
middlewareArray.push(withExtraArgument(thunk.extraArgument))
}
}
if (process.env.NODE_ENV !== 'production') {
if (immutableCheck) {
/* PROD_START_REMOVE_UMD */
let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}
if (!isBoolean(immutableCheck)) {
immutableOptions = immutableCheck
}
middlewareArray.unshift(
createImmutableStateInvariantMiddleware(immutableOptions),
)
/* PROD_STOP_REMOVE_UMD */
}
if (serializableCheck) {
let serializableOptions: SerializableStateInvariantMiddlewareOptions =
{}
if (!isBoolean(serializableCheck)) {
serializableOptions = serializableCheck
}
middlewareArray.push(
createSerializableStateInvariantMiddleware(serializableOptions),
)
}
if (actionCreatorCheck) {
let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}
if (!isBoolean(actionCreatorCheck)) {
actionCreatorOptions = actionCreatorCheck
}
middlewareArray.unshift(
createActionCreatorInvariantMiddleware(actionCreatorOptions),
)
}
}
return middlewareArray as any
}

View File

@@ -0,0 +1,7 @@
export {
current,
isDraft,
produce as createNextState,
isDraftable,
setUseStrictIteration,
} from 'immer'

View File

@@ -0,0 +1,263 @@
import type { Middleware } from 'redux'
import type { IgnorePaths } from './serializableStateInvariantMiddleware'
import { getTimeMeasureUtils } from './utils'
type EntryProcessor = (key: string, value: any) => any
/**
* The default `isImmutable` function.
*
* @public
*/
export function isImmutableDefault(value: unknown): boolean {
return typeof value !== 'object' || value == null || Object.isFrozen(value)
}
export function trackForMutations(
isImmutable: IsImmutableFunc,
ignorePaths: IgnorePaths | undefined,
obj: any,
) {
const trackedProperties = trackProperties(isImmutable, ignorePaths, obj)
return {
detectMutations() {
return detectMutations(isImmutable, ignorePaths, trackedProperties, obj)
},
}
}
interface TrackedProperty {
value: any
children: Record<string, any>
}
function trackProperties(
isImmutable: IsImmutableFunc,
ignorePaths: IgnorePaths = [],
obj: Record<string, any>,
path: string = '',
checkedObjects: Set<Record<string, any>> = new Set(),
) {
const tracked: Partial<TrackedProperty> = { value: obj }
if (!isImmutable(obj) && !checkedObjects.has(obj)) {
checkedObjects.add(obj)
tracked.children = {}
for (const key in obj) {
const childPath = path ? path + '.' + key : key
if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
continue
}
tracked.children[key] = trackProperties(
isImmutable,
ignorePaths,
obj[key],
childPath,
)
}
}
return tracked as TrackedProperty
}
function detectMutations(
isImmutable: IsImmutableFunc,
ignoredPaths: IgnorePaths = [],
trackedProperty: TrackedProperty,
obj: any,
sameParentRef: boolean = false,
path: string = '',
): { wasMutated: boolean; path?: string } {
const prevObj = trackedProperty ? trackedProperty.value : undefined
const sameRef = prevObj === obj
if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
return { wasMutated: true, path }
}
if (isImmutable(prevObj) || isImmutable(obj)) {
return { wasMutated: false }
}
// Gather all keys from prev (tracked) and after objs
const keysToDetect: Record<string, boolean> = {}
for (let key in trackedProperty.children) {
keysToDetect[key] = true
}
for (let key in obj) {
keysToDetect[key] = true
}
const hasIgnoredPaths = ignoredPaths.length > 0
for (let key in keysToDetect) {
const nestedPath = path ? path + '.' + key : key
if (hasIgnoredPaths) {
const hasMatches = ignoredPaths.some((ignored) => {
if (ignored instanceof RegExp) {
return ignored.test(nestedPath)
}
return nestedPath === ignored
})
if (hasMatches) {
continue
}
}
const result = detectMutations(
isImmutable,
ignoredPaths,
trackedProperty.children[key],
obj[key],
sameRef,
nestedPath,
)
if (result.wasMutated) {
return result
}
}
return { wasMutated: false }
}
type IsImmutableFunc = (value: any) => boolean
/**
* Options for `createImmutableStateInvariantMiddleware()`.
*
* @public
*/
export interface ImmutableStateInvariantMiddlewareOptions {
/**
Callback function to check if a value is considered to be immutable.
This function is applied recursively to every value contained in the state.
The default implementation will return true for primitive types
(like numbers, strings, booleans, null and undefined).
*/
isImmutable?: IsImmutableFunc
/**
An array of dot-separated path strings that match named nodes from
the root state to ignore when checking for immutability.
Defaults to undefined
*/
ignoredPaths?: IgnorePaths
/** Print a warning if checks take longer than N ms. Default: 32ms */
warnAfter?: number
}
/**
* Creates a middleware that checks whether any state was mutated in between
* dispatches or during a dispatch. If any mutations are detected, an error is
* thrown.
*
* @param options Middleware options.
*
* @public
*/
export function createImmutableStateInvariantMiddleware(
options: ImmutableStateInvariantMiddlewareOptions = {},
): Middleware {
if (process.env.NODE_ENV === 'production') {
return () => (next) => (action) => next(action)
} else {
function stringify(
obj: any,
serializer?: EntryProcessor,
indent?: string | number,
decycler?: EntryProcessor,
): string {
return JSON.stringify(obj, getSerialize(serializer, decycler), indent)
}
function getSerialize(
serializer?: EntryProcessor,
decycler?: EntryProcessor,
): EntryProcessor {
let stack: any[] = [],
keys: any[] = []
if (!decycler)
decycler = function (_: string, value: any) {
if (stack[0] === value) return '[Circular ~]'
return (
'[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
)
}
return function (this: any, key: string, value: any) {
if (stack.length > 0) {
var thisPos = stack.indexOf(this)
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
if (~stack.indexOf(value)) value = decycler!.call(this, key, value)
} else stack.push(value)
return serializer == null ? value : serializer.call(this, key, value)
}
}
let {
isImmutable = isImmutableDefault,
ignoredPaths,
warnAfter = 32,
} = options
const track = trackForMutations.bind(null, isImmutable, ignoredPaths)
return ({ getState }) => {
let state = getState()
let tracker = track(state)
let result
return (next) => (action) => {
const measureUtils = getTimeMeasureUtils(
warnAfter,
'ImmutableStateInvariantMiddleware',
)
measureUtils.measureTime(() => {
state = getState()
result = tracker.detectMutations()
// Track before potentially not meeting the invariant
tracker = track(state)
if (result.wasMutated) {
throw new Error(
`A state mutation was detected between dispatches, in the path '${
result.path || ''
}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
)
}
})
const dispatchedAction = next(action)
measureUtils.measureTime(() => {
state = getState()
result = tracker.detectMutations()
// Track before potentially not meeting the invariant
tracker = track(state)
if (result.wasMutated) {
throw new Error(
`A state mutation was detected inside a dispatch, in the path: ${
result.path || ''
}. Take a look at the reducer(s) handling the action ${stringify(
action,
)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
)
}
})
measureUtils.warnIfExceeded()
return dispatchedAction
}
}
}
}

213
frontend/node_modules/@reduxjs/toolkit/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,213 @@
// This must remain here so that the `mangleErrors.cjs` build script
// does not have to import this into each source file it rewrites.
import { formatProdErrorMessage } from './formatProdErrorMessage'
export * from 'redux'
export { freeze, original } from 'immer'
export { createNextState, current, isDraft } from './immerImports'
export type { Draft, WritableDraft } from 'immer'
export { createSelector, lruMemoize } from 'reselect'
export { createSelectorCreator, weakMapMemoize } from './reselectImports'
export type { Selector, OutputSelector } from 'reselect'
export {
createDraftSafeSelector,
createDraftSafeSelectorCreator,
} from './createDraftSafeSelector'
export type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'
export {
// js
configureStore,
} from './configureStore'
export type {
// types
ConfigureStoreOptions,
EnhancedStore,
} from './configureStore'
export type { DevToolsEnhancerOptions } from './devtoolsExtension'
export {
// js
createAction,
isActionCreator,
isFSA as isFluxStandardAction,
} from './createAction'
export type {
// types
PayloadAction,
PayloadActionCreator,
ActionCreatorWithNonInferrablePayload,
ActionCreatorWithOptionalPayload,
ActionCreatorWithPayload,
ActionCreatorWithoutPayload,
ActionCreatorWithPreparedPayload,
PrepareAction,
} from './createAction'
export {
// js
createReducer,
} from './createReducer'
export type {
// types
Actions,
CaseReducer,
CaseReducers,
} from './createReducer'
export {
// js
createSlice,
buildCreateSlice,
asyncThunkCreator,
ReducerType,
} from './createSlice'
export type {
// types
CreateSliceOptions,
Slice,
CaseReducerActions,
SliceCaseReducers,
ValidateSliceCaseReducers,
CaseReducerWithPrepare,
ReducerCreators,
SliceSelectors,
} from './createSlice'
export type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
export { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
export {
// js
createImmutableStateInvariantMiddleware,
isImmutableDefault,
} from './immutableStateInvariantMiddleware'
export type {
// types
ImmutableStateInvariantMiddlewareOptions,
} from './immutableStateInvariantMiddleware'
export {
// js
createSerializableStateInvariantMiddleware,
findNonSerializableValue,
isPlain,
} from './serializableStateInvariantMiddleware'
export type {
// types
SerializableStateInvariantMiddlewareOptions,
} from './serializableStateInvariantMiddleware'
export type {
// types
ActionReducerMapBuilder,
AsyncThunkReducers,
} from './mapBuilders'
export { Tuple } from './utils'
export { createEntityAdapter } from './entities/create_adapter'
export type {
EntityState,
EntityAdapter,
EntitySelectors,
EntityStateAdapter,
EntityId,
Update,
IdSelector,
Comparer,
} from './entities/models'
export {
createAsyncThunk,
unwrapResult,
miniSerializeError,
} from './createAsyncThunk'
export type {
AsyncThunk,
AsyncThunkConfig,
AsyncThunkDispatchConfig,
AsyncThunkOptions,
AsyncThunkAction,
AsyncThunkPayloadCreatorReturnValue,
AsyncThunkPayloadCreator,
GetState,
GetThunkAPI,
SerializedError,
CreateAsyncThunkFunction,
} from './createAsyncThunk'
export {
// js
isAllOf,
isAnyOf,
isPending,
isRejected,
isFulfilled,
isAsyncThunkAction,
isRejectedWithValue,
} from './matchers'
export type {
// types
ActionMatchingAllOf,
ActionMatchingAnyOf,
} from './matchers'
export { nanoid } from './nanoid'
export type {
ListenerEffect,
ListenerMiddleware,
ListenerEffectAPI,
ListenerMiddlewareInstance,
CreateListenerMiddlewareOptions,
ListenerErrorHandler,
TypedStartListening,
TypedAddListener,
TypedStopListening,
TypedRemoveListener,
UnsubscribeListener,
UnsubscribeListenerOptions,
ForkedTaskExecutor,
ForkedTask,
ForkedTaskAPI,
AsyncTaskExecutor,
SyncTaskExecutor,
TaskCancelled,
TaskRejected,
TaskResolved,
TaskResult,
} from './listenerMiddleware/index'
export type { AnyListenerPredicate } from './listenerMiddleware/types'
export {
createListenerMiddleware,
addListener,
removeListener,
clearAllListeners,
TaskAbortError,
} from './listenerMiddleware/index'
export type {
AddMiddleware,
DynamicDispatch,
DynamicMiddlewareInstance,
GetDispatchType as GetDispatch,
MiddlewareApiConfig,
} from './dynamicMiddleware/types'
export { createDynamicMiddleware } from './dynamicMiddleware/index'
export {
SHOULD_AUTOBATCH,
prepareAutoBatched,
autoBatchEnhancer,
} from './autoBatchEnhancer'
export type { AutoBatchOptions } from './autoBatchEnhancer'
export { combineSlices } from './combineSlices'
export type {
CombinedSliceReducer,
WithSlice,
WithSlicePreloadedState,
} from './combineSlices'
export type {
ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions,
SafePromise,
} from './tsHelpers'
export { formatProdErrorMessage } from './formatProdErrorMessage'

View File

@@ -0,0 +1,20 @@
import type { SerializedError } from '@reduxjs/toolkit'
const task = 'task'
const listener = 'listener'
const completed = 'completed'
const cancelled = 'cancelled'
/* TaskAbortError error codes */
export const taskCancelled = `task-${cancelled}` as const
export const taskCompleted = `task-${completed}` as const
export const listenerCancelled = `${listener}-${cancelled}` as const
export const listenerCompleted = `${listener}-${completed}` as const
export class TaskAbortError implements SerializedError {
name = 'TaskAbortError'
message: string
constructor(public code: string | undefined) {
this.message = `${task} ${cancelled} (reason: ${code})`
}
}

View File

@@ -0,0 +1,567 @@
import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'
import { isAction } from '../reduxImports'
import type { ThunkDispatch } from 'redux-thunk'
import { createAction } from '../createAction'
import { nanoid } from '../nanoid'
import {
TaskAbortError,
listenerCancelled,
listenerCompleted,
taskCancelled,
taskCompleted,
} from './exceptions'
import {
createDelay,
createPause,
raceWithSignal,
runTask,
validateActive,
} from './task'
import type {
AbortSignalWithReason,
AddListenerOverloads,
AnyListenerPredicate,
CreateListenerMiddlewareOptions,
FallbackAddListenerOptions,
ForkOptions,
ForkedTask,
ForkedTaskExecutor,
ListenerEntry,
ListenerErrorHandler,
ListenerErrorInfo,
ListenerMiddleware,
ListenerMiddlewareInstance,
TakePattern,
TaskResult,
TypedAddListener,
TypedCreateListenerEntry,
TypedRemoveListener,
UnsubscribeListener,
UnsubscribeListenerOptions,
} from './types'
import {
abortControllerWithReason,
addAbortSignalListener,
assertFunction,
catchRejection,
noop,
} from './utils'
export { TaskAbortError } from './exceptions'
export type {
AsyncTaskExecutor,
CreateListenerMiddlewareOptions,
ForkedTask,
ForkedTaskAPI,
ForkedTaskExecutor,
ListenerEffect,
ListenerEffectAPI,
ListenerErrorHandler,
ListenerMiddleware,
ListenerMiddlewareInstance,
SyncTaskExecutor,
TaskCancelled,
TaskRejected,
TaskResolved,
TaskResult,
TypedAddListener,
TypedRemoveListener,
TypedStartListening,
TypedStopListening,
UnsubscribeListener,
UnsubscribeListenerOptions,
} from './types'
//Overly-aggressive byte-shaving
const { assign } = Object
/**
* @internal
*/
const INTERNAL_NIL_TOKEN = {} as const
const alm = 'listenerMiddleware' as const
const createFork = (
parentAbortSignal: AbortSignalWithReason<unknown>,
parentBlockingPromises: Promise<any>[],
) => {
const linkControllers = (controller: AbortController) =>
addAbortSignalListener(parentAbortSignal, () =>
abortControllerWithReason(controller, parentAbortSignal.reason),
)
return <T>(
taskExecutor: ForkedTaskExecutor<T>,
opts?: ForkOptions,
): ForkedTask<T> => {
assertFunction(taskExecutor, 'taskExecutor')
const childAbortController = new AbortController()
linkControllers(childAbortController)
const result = runTask<T>(
async (): Promise<T> => {
validateActive(parentAbortSignal)
validateActive(childAbortController.signal)
const result = (await taskExecutor({
pause: createPause(childAbortController.signal),
delay: createDelay(childAbortController.signal),
signal: childAbortController.signal,
})) as T
validateActive(childAbortController.signal)
return result
},
() => abortControllerWithReason(childAbortController, taskCompleted),
)
if (opts?.autoJoin) {
parentBlockingPromises.push(result.catch(noop))
}
return {
result: createPause<TaskResult<T>>(parentAbortSignal)(result),
cancel() {
abortControllerWithReason(childAbortController, taskCancelled)
},
}
}
}
const createTakePattern = <S>(
startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>,
signal: AbortSignal,
): TakePattern<S> => {
/**
* A function that takes a ListenerPredicate and an optional timeout,
* and resolves when either the predicate returns `true` based on an action
* state combination or when the timeout expires.
* If the parent listener is canceled while waiting, this will throw a
* TaskAbortError.
*/
const take = async <P extends AnyListenerPredicate<S>>(
predicate: P,
timeout: number | undefined,
) => {
validateActive(signal)
// Placeholder unsubscribe function until the listener is added
let unsubscribe: UnsubscribeListener = () => {}
const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {
// Inside the Promise, we synchronously add the listener.
let stopListening = startListening({
predicate: predicate as any,
effect: (action, listenerApi): void => {
// One-shot listener that cleans up as soon as the predicate passes
listenerApi.unsubscribe()
// Resolve the promise with the same arguments the predicate saw
resolve([
action,
listenerApi.getState(),
listenerApi.getOriginalState(),
])
},
})
unsubscribe = () => {
stopListening()
reject()
}
})
const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise]
if (timeout != null) {
promises.push(
new Promise<null>((resolve) => setTimeout(resolve, timeout, null)),
)
}
try {
const output = await raceWithSignal(signal, Promise.race(promises))
validateActive(signal)
return output
} finally {
// Always clean up the listener
unsubscribe()
}
}
return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) =>
catchRejection(take(predicate, timeout))) as TakePattern<S>
}
const getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {
let { type, actionCreator, matcher, predicate, effect } = options
if (type) {
predicate = createAction(type).match
} else if (actionCreator) {
type = actionCreator!.type
predicate = actionCreator.match
} else if (matcher) {
predicate = matcher
} else if (predicate) {
// pass
} else {
throw new Error(
'Creating or removing a listener requires one of the known fields for matching an action',
)
}
assertFunction(effect, 'options.listener')
return { predicate, type, effect }
}
/** Accepts the possible options for creating a listener, and returns a formatted listener entry */
export const createListenerEntry: TypedCreateListenerEntry<unknown> =
/* @__PURE__ */ assign(
(options: FallbackAddListenerOptions) => {
const { type, predicate, effect } = getListenerEntryPropsFrom(options)
const entry: ListenerEntry<unknown> = {
id: nanoid(),
effect,
type,
predicate,
pending: new Set<AbortController>(),
unsubscribe: () => {
throw new Error('Unsubscribe not initialized')
},
}
return entry
},
{ withTypes: () => createListenerEntry },
) as unknown as TypedCreateListenerEntry<unknown>
const findListenerEntry = (
listenerMap: Map<string, ListenerEntry>,
options: FallbackAddListenerOptions,
) => {
const { type, effect, predicate } = getListenerEntryPropsFrom(options)
return Array.from(listenerMap.values()).find((entry) => {
const matchPredicateOrType =
typeof type === 'string'
? entry.type === type
: entry.predicate === predicate
return matchPredicateOrType && entry.effect === effect
})
}
const cancelActiveListeners = (
entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
) => {
entry.pending.forEach((controller) => {
abortControllerWithReason(controller, listenerCancelled)
})
}
const createClearListenerMiddleware = (
listenerMap: Map<string, ListenerEntry>,
executingListeners: Map<ListenerEntry, number>,
) => {
return () => {
for (const listener of executingListeners.keys()) {
cancelActiveListeners(listener)
}
listenerMap.clear()
}
}
/**
* Safely reports errors to the `errorHandler` provided.
* Errors that occur inside `errorHandler` are notified in a new task.
* Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)
* @param errorHandler
* @param errorToNotify
*/
const safelyNotifyError = (
errorHandler: ListenerErrorHandler,
errorToNotify: unknown,
errorInfo: ListenerErrorInfo,
): void => {
try {
errorHandler(errorToNotify, errorInfo)
} catch (errorHandlerError) {
// We cannot let an error raised here block the listener queue.
// The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...
setTimeout(() => {
throw errorHandlerError
}, 0)
}
}
/**
* @public
*/
export const addListener = /* @__PURE__ */ assign(
/* @__PURE__ */ createAction(`${alm}/add`),
{
withTypes: () => addListener,
},
) as unknown as TypedAddListener<unknown>
/**
* @public
*/
export const clearAllListeners = /* @__PURE__ */ createAction(
`${alm}/removeAll`,
)
/**
* @public
*/
export const removeListener = /* @__PURE__ */ assign(
/* @__PURE__ */ createAction(`${alm}/remove`),
{
withTypes: () => removeListener,
},
) as unknown as TypedRemoveListener<unknown>
const defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {
console.error(`${alm}/error`, ...args)
}
/**
* @public
*/
export const createListenerMiddleware = <
StateType = unknown,
DispatchType extends Dispatch<Action> = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
>(
middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},
) => {
const listenerMap = new Map<string, ListenerEntry>()
// Track listeners whose effect is currently executing so clearListeners can
// abort even listeners that have become unsubscribed while executing.
const executingListeners = new Map<ListenerEntry, number>()
const trackExecutingListener = (entry: ListenerEntry) => {
const count = executingListeners.get(entry) ?? 0
executingListeners.set(entry, count + 1)
}
const untrackExecutingListener = (entry: ListenerEntry) => {
const count = executingListeners.get(entry) ?? 1
if (count === 1) {
executingListeners.delete(entry)
} else {
executingListeners.set(entry, count - 1)
}
}
const { extra, onError = defaultErrorHandler } = middlewareOptions
assertFunction(onError, 'onError')
const insertEntry = (entry: ListenerEntry) => {
entry.unsubscribe = () => listenerMap.delete(entry.id)
listenerMap.set(entry.id, entry)
return (cancelOptions?: UnsubscribeListenerOptions) => {
entry.unsubscribe()
if (cancelOptions?.cancelActive) {
cancelActiveListeners(entry)
}
}
}
const startListening = ((options: FallbackAddListenerOptions) => {
const entry =
findListenerEntry(listenerMap, options) ??
createListenerEntry(options as any)
return insertEntry(entry)
}) as AddListenerOverloads<any>
assign(startListening, {
withTypes: () => startListening,
})
const stopListening = (
options: FallbackAddListenerOptions & UnsubscribeListenerOptions,
): boolean => {
const entry = findListenerEntry(listenerMap, options)
if (entry) {
entry.unsubscribe()
if (options.cancelActive) {
cancelActiveListeners(entry)
}
}
return !!entry
}
assign(stopListening, {
withTypes: () => stopListening,
})
const notifyListener = async (
entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
action: unknown,
api: MiddlewareAPI,
getOriginalState: () => StateType,
) => {
const internalTaskController = new AbortController()
const take = createTakePattern(
startListening as AddListenerOverloads<any>,
internalTaskController.signal,
)
const autoJoinPromises: Promise<any>[] = []
try {
entry.pending.add(internalTaskController)
trackExecutingListener(entry)
await Promise.resolve(
entry.effect(
action,
// Use assign() rather than ... to avoid extra helper functions added to bundle
assign({}, api, {
getOriginalState,
condition: (
predicate: AnyListenerPredicate<any>,
timeout?: number,
) => take(predicate, timeout).then(Boolean),
take,
delay: createDelay(internalTaskController.signal),
pause: createPause<any>(internalTaskController.signal),
extra,
signal: internalTaskController.signal,
fork: createFork(internalTaskController.signal, autoJoinPromises),
unsubscribe: entry.unsubscribe,
subscribe: () => {
listenerMap.set(entry.id, entry)
},
cancelActiveListeners: () => {
entry.pending.forEach((controller, _, set) => {
if (controller !== internalTaskController) {
abortControllerWithReason(controller, listenerCancelled)
set.delete(controller)
}
})
},
cancel: () => {
abortControllerWithReason(
internalTaskController,
listenerCancelled,
)
entry.pending.delete(internalTaskController)
},
throwIfCancelled: () => {
validateActive(internalTaskController.signal)
},
}),
),
)
} catch (listenerError) {
if (!(listenerError instanceof TaskAbortError)) {
safelyNotifyError(onError, listenerError, {
raisedBy: 'effect',
})
}
} finally {
await Promise.all(autoJoinPromises)
abortControllerWithReason(internalTaskController, listenerCompleted) // Notify that the task has completed
untrackExecutingListener(entry)
entry.pending.delete(internalTaskController)
}
}
const clearListenerMiddleware = createClearListenerMiddleware(
listenerMap,
executingListeners,
)
const middleware: ListenerMiddleware<
StateType,
DispatchType,
ExtraArgument
> = (api) => (next) => (action) => {
if (!isAction(action)) {
// we only want to notify listeners for action objects
return next(action)
}
if (addListener.match(action)) {
return startListening(action.payload as any)
}
if (clearAllListeners.match(action)) {
clearListenerMiddleware()
return
}
if (removeListener.match(action)) {
return stopListening(action.payload)
}
// Need to get this state _before_ the reducer processes the action
let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState()
// `getOriginalState` can only be called synchronously.
// @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820
const getOriginalState = (): StateType => {
if (originalState === INTERNAL_NIL_TOKEN) {
throw new Error(
`${alm}: getOriginalState can only be called synchronously`,
)
}
return originalState as StateType
}
let result: unknown
try {
// Actually forward the action to the reducer before we handle listeners
result = next(action)
if (listenerMap.size > 0) {
const currentState = api.getState()
// Work around ESBuild+TS transpilation issue
const listenerEntries = Array.from(listenerMap.values())
for (const entry of listenerEntries) {
let runListener = false
try {
runListener = entry.predicate(action, currentState, originalState)
} catch (predicateError) {
runListener = false
safelyNotifyError(onError, predicateError, {
raisedBy: 'predicate',
})
}
if (!runListener) {
continue
}
notifyListener(entry, action, api, getOriginalState)
}
}
} finally {
// Remove `originalState` store from this scope.
originalState = INTERNAL_NIL_TOKEN
}
return result
}
return {
middleware,
startListening,
stopListening,
clearListeners: clearListenerMiddleware,
} as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>
}

View File

@@ -0,0 +1,101 @@
import { TaskAbortError } from './exceptions'
import type { AbortSignalWithReason, TaskResult } from './types'
import { addAbortSignalListener, catchRejection, noop } from './utils'
/**
* Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.
* @param signal
* @param reason
* @see {TaskAbortError}
*/
export const validateActive = (signal: AbortSignal): void => {
if (signal.aborted) {
const { reason } = signal as AbortSignalWithReason<string>
throw new TaskAbortError(reason)
}
}
/**
* Generates a race between the promise(s) and the AbortSignal
* This avoids `Promise.race()`-related memory leaks:
* https://github.com/nodejs/node/issues/17469#issuecomment-349794909
*/
export function raceWithSignal<T>(
signal: AbortSignalWithReason<string>,
promise: Promise<T>,
): Promise<T> {
let cleanup = noop
return new Promise<T>((resolve, reject) => {
const notifyRejection = () => reject(new TaskAbortError(signal.reason))
if (signal.aborted) {
notifyRejection()
return
}
cleanup = addAbortSignalListener(signal, notifyRejection)
promise.finally(() => cleanup()).then(resolve, reject)
}).finally(() => {
// after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more
cleanup = noop
})
}
/**
* Runs a task and returns promise that resolves to {@link TaskResult}.
* Second argument is an optional `cleanUp` function that always runs after task.
*
* **Note:** `runTask` runs the executor in the next microtask.
* @returns
*/
export const runTask = async <T>(
task: () => Promise<T>,
cleanUp?: () => void,
): Promise<TaskResult<T>> => {
try {
await Promise.resolve()
const value = await task()
return {
status: 'ok',
value,
}
} catch (error: any) {
return {
status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',
error,
}
} finally {
cleanUp?.()
}
}
/**
* Given an input `AbortSignal` and a promise returns another promise that resolves
* as soon the input promise is provided or rejects as soon as
* `AbortSignal.abort` is `true`.
* @param signal
* @returns
*/
export const createPause = <T>(signal: AbortSignal) => {
return (promise: Promise<T>): Promise<T> => {
return catchRejection(
raceWithSignal(signal, promise).then((output) => {
validateActive(signal)
return output
}),
)
}
}
/**
* Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves
* after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.
* @param signal
* @returns
*/
export const createDelay = (signal: AbortSignal) => {
const pause = createPause<void>(signal)
return (timeoutMs: number): Promise<void> => {
return pause(new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)))
}
}

View File

@@ -0,0 +1,498 @@
import { noop } from '@internal/listenerMiddleware/utils'
import type { PayloadAction } from '@reduxjs/toolkit'
import {
configureStore,
createAction,
createListenerMiddleware,
createSlice,
isAnyOf,
TaskAbortError,
} from '@reduxjs/toolkit'
describe('Saga-style Effects Scenarios', () => {
interface CounterState {
value: number
}
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
let { reducer } = counterSlice
let listenerMiddleware = createListenerMiddleware<CounterState>()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
const testAction1 = createAction<string>('testAction1')
type TestAction1 = ReturnType<typeof testAction1>
const testAction2 = createAction<string>('testAction2')
type TestAction2 = ReturnType<typeof testAction2>
const testAction3 = createAction<string>('testAction3')
type TestAction3 = ReturnType<typeof testAction3>
type RootState = ReturnType<typeof store.getState>
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
beforeEach(() => {
listenerMiddleware = createListenerMiddleware<CounterState>()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
afterEach(() => {
vi.clearAllMocks()
})
afterAll(() => {
vi.restoreAllMocks()
})
test('throttle', async () => {
// Ignore incoming actions for a given period of time while processing a task.
// Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
// Stop listening until further notice
listenerApi.unsubscribe()
// Queue to start listening again after a delay
setTimeout(listenerApi.subscribe, 15)
workPerformed++
},
})
// Dispatch 3 actions. First triggers listener, next two ignored.
store.dispatch(increment())
store.dispatch(increment())
store.dispatch(increment())
// Wait for resubscription
await delay(25)
// Dispatch 2 more actions, first triggers, second ignored
store.dispatch(increment())
store.dispatch(increment())
// Wait for work
await delay(5)
// Both listener calls completed
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(2)
})
test('debounce / takeLatest', async () => {
// Repeated calls cancel previous ones, no work performed
// until the specified delay elapses without another call
// NOTE: This is also basically identical to `takeLatest`.
// Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args
// Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Cancel any in-progress instances of this listener
listenerApi.cancelActiveListeners()
// Delay before starting actual work
await listenerApi.delay(15)
workPerformed++
},
})
// First action, listener 1 starts, nothing to cancel
store.dispatch(increment())
// Second action, listener 2 starts, cancels 1
store.dispatch(increment())
// Third action, listener 3 starts, cancels 2
store.dispatch(increment())
// 3 listeners started, third is still paused
expect(listenerCalls).toBe(3)
expect(workPerformed).toBe(0)
await delay(25)
// All 3 started
expect(listenerCalls).toBe(3)
// First two canceled, `delay()` threw JobCanceled and skipped work.
// Third actually completed.
expect(workPerformed).toBe(1)
})
test('takeEvery', async () => {
// Runs the listener on every action match
// Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args
// NOTE: This is already the default behavior - nothing special here!
let listenerCalls = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
},
})
store.dispatch(increment())
expect(listenerCalls).toBe(1)
store.dispatch(increment())
expect(listenerCalls).toBe(2)
})
test('takeLeading', async () => {
// Starts listener on first action, ignores others until task completes
// Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Stop listening for this action
listenerApi.unsubscribe()
// Pretend we're doing expensive work
await listenerApi.delay(25)
workPerformed++
// Re-enable the listener
listenerApi.subscribe()
},
})
// First action starts the listener, which unsubscribes
store.dispatch(increment())
// Second action is ignored
store.dispatch(increment())
// One instance in progress, but not complete
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(5)
// In-progress listener not done yet
store.dispatch(increment())
// No changes in status
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(50)
// Work finished, should have resubscribed
expect(workPerformed).toBe(1)
// Listener is re-subscribed, will trigger again
store.dispatch(increment())
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(1)
await delay(50)
expect(workPerformed).toBe(2)
})
test('fork + join', async () => {
// fork starts a child job, join waits for the child to complete and return a value
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
// Ref: https://redux-saga.js.org/docs/api#jointask
let childResult = 0
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const childOutput = 42
// Spawn a child job and start it immediately
const result = await listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(5)
// Complete the child by returning an Outcome-wrapped value
return childOutput
}).result
// Unwrap the child result in the listener
if (result.status === 'ok') {
childResult = result.value
}
},
})
store.dispatch(increment())
await delay(10)
expect(childResult).toBe(42)
})
test('fork + cancel', async () => {
// fork starts a child job, cancel will raise an exception if the
// child is paused in the middle of an effect
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
let childResult = 0
let listenerCompleted = false
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
// Spawn a child job and start it immediately
const forkedTask = listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(15)
// Complete the child by returning an Outcome-wrapped value
childResult = 42
return 0
})
await listenerApi.delay(5)
forkedTask.cancel()
listenerCompleted = true
},
})
// Starts listener, which starts child
store.dispatch(increment())
// Wait for child to have maybe completed
await delay(20)
// Listener finished, but the child was canceled and threw an exception, so it never finished
expect(listenerCompleted).toBe(true)
expect(childResult).toBe(0)
})
test('canceled', async () => {
// canceled allows checking if the current task was canceled
// Ref: https://redux-saga.js.org/docs/api#cancelled
let canceledAndCaught = false
let canceledCheck = false
startListening({
matcher: isAnyOf(increment, decrement, incrementByAmount),
effect: async (action, listenerApi) => {
if (increment.match(action)) {
// Have this branch wait around to be canceled by the other
try {
await listenerApi.delay(10)
} catch (err) {
// Can check cancelation based on the exception and its reason
if (err instanceof TaskAbortError) {
canceledAndCaught = true
}
}
} else if (incrementByAmount.match(action)) {
// do a non-cancelation-aware wait
await delay(15)
if (listenerApi.signal.aborted) {
canceledCheck = true
}
} else if (decrement.match(action)) {
listenerApi.cancelActiveListeners()
}
},
})
// Start first branch
store.dispatch(increment())
// Cancel first listener
store.dispatch(decrement())
// Have to wait for the delay to resolve
// TODO Can we make ``Job.delay()` be a race?
await delay(15)
expect(canceledAndCaught).toBe(true)
// Start second branch
store.dispatch(incrementByAmount(42))
// Cancel second listener, although it won't know about that until later
store.dispatch(decrement())
expect(canceledCheck).toBe(false)
await delay(20)
expect(canceledCheck).toBe(true)
})
test('long-running listener with immediate unsubscribe is cancelable', async () => {
let runCount = 0
let abortCount = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
runCount++
// Stop listening for this action
listenerApi.unsubscribe()
try {
// Wait indefinitely
await listenerApi.condition(() => false)
} catch (err) {
if (err instanceof TaskAbortError) {
abortCount++
}
}
},
})
// First action starts the listener, which unsubscribes
store.dispatch(increment())
expect(runCount).toBe(1)
// Verify that the first action unsubscribed the listener
store.dispatch(increment())
expect(runCount).toBe(1)
// Now call clearListeners, which should abort the running effect, even
// though the listener is no longer subscribed
listenerMiddleware.clearListeners()
await delay(0)
expect(abortCount).toBe(1)
})
test('long-running listener with unsubscribe race is cancelable', async () => {
let runCount = 0
let abortCount = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
runCount++
if (runCount === 2) {
// On the second run, stop listening for this action
listenerApi.unsubscribe()
return
}
try {
// Wait indefinitely
await listenerApi.condition(() => false)
} catch (err) {
if (err instanceof TaskAbortError) {
abortCount++
}
}
},
})
// First action starts the hanging effect
store.dispatch(increment())
expect(runCount).toBe(1)
// Second action starts the fast effect, which unsubscribes
store.dispatch(increment())
expect(runCount).toBe(2)
// Third action should be a noop
store.dispatch(increment())
expect(runCount).toBe(2)
// The hanging effect should still be hanging
expect(abortCount).toBe(0)
// Now call clearListeners, which should abort the hanging effect, even
// though the listener is no longer subscribed
listenerMiddleware.clearListeners()
await delay(0)
expect(abortCount).toBe(1)
})
test('long-running listener with immediate unsubscribe and forked child is cancelable', async () => {
let outerAborted = false
let innerAborted = false
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
// Stop listening for this action
listenerApi.unsubscribe()
const pollingTask = listenerApi.fork(async (forkApi) => {
try {
// Cancellation-aware indefinite pause
await forkApi.pause(new Promise(() => {}))
} catch (err) {
if (err instanceof TaskAbortError) {
innerAborted = true
}
}
})
try {
// Wait indefinitely
await listenerApi.condition(() => false)
pollingTask.cancel()
} catch (err) {
if (err instanceof TaskAbortError) {
outerAborted = true
}
}
},
})
store.dispatch(increment())
await delay(0)
listenerMiddleware.clearListeners()
await delay(0)
expect(outerAborted).toBe(true)
expect(innerAborted).toBe(true)
})
})

View File

@@ -0,0 +1,530 @@
import type { EnhancedStore } from '@reduxjs/toolkit'
import { configureStore, createSlice, createAction } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type {
AbortSignalWithReason,
ForkedTaskExecutor,
TaskResult,
} from '../types'
import { createListenerMiddleware, TaskAbortError } from '../index'
import {
listenerCancelled,
listenerCompleted,
taskCancelled,
taskCompleted,
} from '../exceptions'
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
// @see https://deno.land/std@0.95.0/async/deferred.ts (MIT)
export interface Deferred<T> extends Promise<T> {
resolve(value?: T | PromiseLike<T>): void
reject(reason?: any): void
}
/** Creates a Promise with the `reject` and `resolve` functions
* placed as methods on the promise object itself. It allows you to do:
*
* const p = deferred<number>();
* // ...
* p.resolve(42);
*/
export function deferred<T>(): Deferred<T> {
let methods
const promise = new Promise<T>((resolve, reject): void => {
methods = { resolve, reject }
})
return Object.assign(promise, methods) as Deferred<T>
}
interface CounterSlice {
value: number
}
describe('fork', () => {
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterSlice,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
let listenerMiddleware = createListenerMiddleware()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
beforeEach(() => {
listenerMiddleware = createListenerMiddleware()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
stopListening = listenerMiddleware.stopListening
store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
it('runs executors in the next microtask', async () => {
let hasRunSyncExector = false
let hasRunAsyncExecutor = false
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
listenerApi.fork(() => {
hasRunSyncExector = true
})
listenerApi.fork(async () => {
hasRunAsyncExecutor = true
})
},
})
store.dispatch(increment())
expect(hasRunSyncExector).toBe(false)
expect(hasRunAsyncExecutor).toBe(false)
await Promise.resolve()
expect(hasRunSyncExector).toBe(true)
expect(hasRunAsyncExecutor).toBe(true)
})
test('forkedTask.result rejects TaskAbortError if listener is cancelled', async () => {
const deferredForkedTaskError = deferred()
startListening({
actionCreator: increment,
async effect(_, listenerApi) {
listenerApi.cancelActiveListeners()
listenerApi
.fork(async () => {
await delay(10)
throw new Error('unreachable code')
})
.result.then(
deferredForkedTaskError.resolve,
deferredForkedTaskError.resolve,
)
},
})
store.dispatch(increment())
store.dispatch(increment())
expect(await deferredForkedTaskError).toEqual(
new TaskAbortError(listenerCancelled),
)
})
it('synchronously throws TypeError error if the provided executor is not a function', () => {
const invalidExecutors = [null, {}, undefined, 1]
startListening({
predicate: () => true,
effect: async (_, listenerApi) => {
invalidExecutors.forEach((invalidExecutor) => {
let caughtError
try {
listenerApi.fork(invalidExecutor as any)
} catch (err) {
caughtError = err
}
expect(caughtError).toBeInstanceOf(TypeError)
})
},
})
store.dispatch(increment())
expect.assertions(invalidExecutors.length)
})
it('does not run an executor if the task is synchronously cancelled', async () => {
const storeStateAfter = deferred()
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
const forkedTask = listenerApi.fork(() => {
listenerApi.dispatch(decrement())
listenerApi.dispatch(decrement())
listenerApi.dispatch(decrement())
})
forkedTask.cancel()
const result = await forkedTask.result
storeStateAfter.resolve(listenerApi.getState())
},
})
store.dispatch(increment())
await expect(storeStateAfter).resolves.toEqual({ value: 1 })
})
it.each<{
desc: string
executor: ForkedTaskExecutor<any>
cancelAfterMs?: number
expected: TaskResult<any>
}>([
{
desc: 'sync exec - success',
executor: () => 42,
expected: { status: 'ok', value: 42 },
},
{
desc: 'sync exec - error',
executor: () => {
throw new Error('2020')
},
expected: { status: 'rejected', error: new Error('2020') },
},
{
desc: 'sync exec - sync cancel',
executor: () => 42,
cancelAfterMs: -1,
expected: {
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
},
},
{
desc: 'sync exec - async cancel',
executor: () => 42,
cancelAfterMs: 0,
expected: { status: 'ok', value: 42 },
},
{
desc: 'async exec - async cancel',
executor: async (forkApi) => {
await forkApi.delay(100)
throw new Error('2020')
},
cancelAfterMs: 10,
expected: {
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
},
},
{
desc: 'async exec - success',
executor: async () => {
await delay(20)
return Promise.resolve(21)
},
expected: { status: 'ok', value: 21 },
},
{
desc: 'async exec - error',
executor: async () => {
await Promise.resolve()
throw new Error('2020')
},
expected: { status: 'rejected', error: new Error('2020') },
},
{
desc: 'async exec - success with forkApi.pause',
executor: async (forkApi) => {
return forkApi.pause(Promise.resolve(2))
},
expected: { status: 'ok', value: 2 },
},
{
desc: 'async exec - error with forkApi.pause',
executor: async (forkApi) => {
return forkApi.pause(Promise.reject(22))
},
expected: { status: 'rejected', error: 22 },
},
{
desc: 'async exec - success with forkApi.delay',
executor: async (forkApi) => {
await forkApi.delay(10)
return 5
},
expected: { status: 'ok', value: 5 },
},
])('$desc', async ({ executor, expected, cancelAfterMs }) => {
let deferredResult = deferred()
let forkedTask: any = {}
startListening({
predicate: () => true,
effect: async (_, listenerApi) => {
forkedTask = listenerApi.fork(executor)
deferredResult.resolve(await forkedTask.result)
},
})
store.dispatch({ type: '' })
if (typeof cancelAfterMs === 'number') {
if (cancelAfterMs < 0) {
forkedTask.cancel()
} else {
await delay(cancelAfterMs)
forkedTask.cancel()
}
}
const result = await deferredResult
expect(result).toEqual(expected)
})
describe('forkAPI', () => {
test('forkApi.delay rejects as soon as the task is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const forkedTask = listenerApi.fork(async (forkApi) => {
await forkApi.delay(100)
return 4
})
await listenerApi.delay(10)
forkedTask.cancel()
deferredResult.resolve(await forkedTask.result)
},
})
store.dispatch(increment())
expect(await deferredResult).toEqual({
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
})
})
test('forkApi.delay rejects as soon as the parent listener is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
listenerApi.cancelActiveListeners()
await listenerApi.fork(async (forkApi) => {
await forkApi
.delay(100)
.then(deferredResult.resolve, deferredResult.resolve)
return 4
}).result
deferredResult.resolve(new Error('unreachable'))
},
})
store.dispatch(increment())
await Promise.resolve()
store.dispatch(increment())
expect(await deferredResult).toEqual(
new TaskAbortError(listenerCancelled),
)
})
it.each([
{
autoJoin: true,
expectedAbortReason: taskCompleted,
cancelListener: false,
},
{
autoJoin: false,
expectedAbortReason: listenerCompleted,
cancelListener: false,
},
{
autoJoin: true,
expectedAbortReason: listenerCancelled,
cancelListener: true,
},
{
autoJoin: false,
expectedAbortReason: listenerCancelled,
cancelListener: true,
},
])(
'signal is $expectedAbortReason when autoJoin: $autoJoin, cancelListener: $cancelListener',
async ({ autoJoin, cancelListener, expectedAbortReason }) => {
let deferredResult = deferred()
const unsubscribe = startListening({
actionCreator: increment,
async effect(_, listenerApi) {
listenerApi.fork(
async (forkApi) => {
forkApi.signal.addEventListener('abort', () => {
deferredResult.resolve(
(forkApi.signal as AbortSignalWithReason<unknown>).reason,
)
})
await forkApi.delay(10)
},
{ autoJoin },
)
},
})
store.dispatch(increment())
// let task start
await Promise.resolve()
if (cancelListener) unsubscribe({ cancelActive: true })
expect(await deferredResult).toBe(expectedAbortReason)
},
)
test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => {
let deferredCompletedEvt = deferred()
let deferredCancelledEvt = deferred()
// Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620
// This test just fails if an `unhandledRejection` occurs.
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const completedTask = listenerApi.fork(async (forkApi) => {
forkApi.signal.addEventListener(
'abort',
deferredCompletedEvt.resolve,
{ once: true },
)
forkApi.delay(100) // missing await
return 4
})
deferredCompletedEvt.resolve(await completedTask.result)
const godotPauseTrigger = deferred()
const cancelledTask = listenerApi.fork(async (forkApi) => {
forkApi.signal.addEventListener(
'abort',
deferredCompletedEvt.resolve,
{ once: true },
)
forkApi.delay(1_000) // missing await
await forkApi.pause(godotPauseTrigger)
return 4
})
await Promise.resolve()
cancelledTask.cancel()
deferredCancelledEvt.resolve(await cancelledTask.result)
},
})
store.dispatch(increment())
expect(await deferredCompletedEvt).toBeDefined()
expect(await deferredCancelledEvt).toBeDefined()
})
})
test('forkApi.pause rejects if task is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const forkedTask = listenerApi.fork(async (forkApi) => {
await forkApi.pause(delay(1_000))
return 4
})
await Promise.resolve()
forkedTask.cancel()
deferredResult.resolve(await forkedTask.result)
},
})
store.dispatch(increment())
expect(await deferredResult).toEqual({
status: 'cancelled',
error: new TaskAbortError(taskCancelled),
})
})
test('forkApi.pause rejects as soon as the parent listener is cancelled', async () => {
let deferredResult = deferred()
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
listenerApi.cancelActiveListeners()
const forkedTask = listenerApi.fork(async (forkApi) => {
await forkApi
.pause(delay(100))
.then(deferredResult.resolve, deferredResult.resolve)
return 4
})
await forkedTask.result
deferredResult.resolve(new Error('unreachable'))
},
})
store.dispatch(increment())
await Promise.resolve()
store.dispatch(increment())
expect(await deferredResult).toEqual(new TaskAbortError(listenerCancelled))
})
test('forkApi.pause rejects if listener is cancelled', async () => {
const incrementByInListener = createAction<number>('incrementByInListener')
startListening({
actionCreator: incrementByInListener,
async effect({ payload: amountToIncrement }, listenerApi) {
listenerApi.cancelActiveListeners()
await listenerApi.fork(async (forkApi) => {
await forkApi.pause(delay(10))
listenerApi.dispatch(incrementByAmount(amountToIncrement))
}).result
listenerApi.dispatch(incrementByAmount(2 * amountToIncrement))
},
})
store.dispatch(incrementByInListener(10))
store.dispatch(incrementByInListener(100))
await delay(50)
expect(store.getState().value).toEqual(300)
})
})

View File

@@ -0,0 +1,540 @@
import { createListenerEntry } from '@internal/listenerMiddleware'
import type {
Action,
PayloadAction,
TypedAddListener,
TypedStartListening,
UnknownAction,
UnsubscribeListener,
} from '@reduxjs/toolkit'
import {
addListener,
configureStore,
createAction,
createListenerMiddleware,
createSlice,
isFluxStandardAction,
} from '@reduxjs/toolkit'
const listenerMiddleware = createListenerMiddleware()
const { startListening } = listenerMiddleware
const addTypedListenerAction = addListener as TypedAddListener<CounterState>
interface CounterState {
value: number
}
const testAction1 = createAction<string>('testAction1')
const testAction2 = createAction<string>('testAction2')
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
describe('type tests', () => {
const store = configureStore({
reducer: () => 42,
middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),
})
test('Allows passing an extra argument on middleware creation', () => {
const originalExtra = 42
const listenerMiddleware = createListenerMiddleware({
extra: originalExtra,
})
const store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),
})
let foundExtra: number | null = null
const typedAddListener =
listenerMiddleware.startListening as TypedStartListening<
CounterState,
typeof store.dispatch,
typeof originalExtra
>
typedAddListener({
matcher: (action): action is Action => true,
effect: (action, listenerApi) => {
foundExtra = listenerApi.extra
expectTypeOf(listenerApi.extra).toMatchTypeOf(originalExtra)
},
})
store.dispatch(testAction1('a'))
expect(foundExtra).toBe(originalExtra)
})
test('unsubscribing via callback from dispatch', () => {
const unsubscribe = store.dispatch(
addListener({
actionCreator: testAction1,
effect: () => {},
}),
)
expectTypeOf(unsubscribe).toEqualTypeOf<UnsubscribeListener>()
store.dispatch(testAction1('a'))
unsubscribe()
store.dispatch(testAction2('b'))
store.dispatch(testAction1('c'))
})
test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', () => {
type ExpectedTakeResultType =
| readonly [ReturnType<typeof increment>, CounterState, CounterState]
| null
let timeout: number | undefined = undefined
let done = false
const startAppListening =
startListening as TypedStartListening<CounterState>
startAppListening({
predicate: incrementByAmount.match,
effect: async (_, listenerApi) => {
let takeResult = await listenerApi.take(increment.match, timeout)
timeout = 1
takeResult = await listenerApi.take(increment.match, timeout)
expect(takeResult).toBeNull()
expectTypeOf(takeResult).toMatchTypeOf<ExpectedTakeResultType>()
done = true
},
})
expect(done).toBe(true)
})
test('State args default to unknown', () => {
createListenerEntry({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).toBeUnknown()
expectTypeOf(previousState).toBeUnknown()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
})
startListening({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).toBeUnknown()
expectTypeOf(previousState).toBeUnknown()
return true
},
effect: (action, listenerApi) => {},
})
startListening({
matcher: increment.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
})
store.dispatch(
addListener({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).toBeUnknown()
expectTypeOf(previousState).toBeUnknown()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
}),
)
store.dispatch(
addListener({
matcher: increment.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toBeUnknown()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = getState()
expectTypeOf(thunkState).toBeUnknown()
})
},
}),
)
})
test('Action type is inferred from args', () => {
startListening({
type: 'abcd',
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
},
})
startListening({
actionCreator: incrementByAmount,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
})
startListening({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
})
startListening({
predicate: (
action,
currentState,
previousState,
): action is PayloadAction<number> => {
return (
isFluxStandardAction(action) && typeof action.payload === 'boolean'
)
},
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
},
})
startListening({
predicate: (action, currentState) => {
return (
isFluxStandardAction(action) && typeof action.payload === 'number'
)
},
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<UnknownAction>()
},
})
store.dispatch(
addListener({
type: 'abcd',
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
},
}),
)
store.dispatch(
addListener({
actionCreator: incrementByAmount,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
}),
)
store.dispatch(
addListener({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
},
}),
)
})
test('Can create a pre-typed middleware', () => {
const typedMiddleware = createListenerMiddleware<CounterState>()
typedMiddleware.startListening({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
// Can pass a predicate function with fewer args
typedMiddleware.startListening({
predicate: (action, currentState): action is PayloadAction<number> => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
typedMiddleware.startListening({
actionCreator: incrementByAmount,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
store.dispatch(
addTypedListenerAction({
predicate: (
action,
currentState,
previousState,
): action is ReturnType<typeof incrementByAmount> => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
store.dispatch(
addTypedListenerAction({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
})
test('Can create pre-typed versions of startListening and addListener', () => {
const typedAddListener = startListening as TypedStartListening<CounterState>
const typedAddListenerAction = addListener as TypedAddListener<CounterState>
typedAddListener({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
typedAddListener({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
})
store.dispatch(
typedAddListenerAction({
predicate: (
action,
currentState,
previousState,
): action is UnknownAction => {
expectTypeOf(currentState).not.toBeAny()
expectTypeOf(previousState).not.toBeAny()
expectTypeOf(currentState).toEqualTypeOf<CounterState>()
expectTypeOf(previousState).toEqualTypeOf<CounterState>()
return true
},
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
store.dispatch(
typedAddListenerAction({
matcher: incrementByAmount.match,
effect: (action, listenerApi) => {
const listenerState = listenerApi.getState()
expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
listenerApi.dispatch((dispatch, getState) => {
const thunkState = listenerApi.getState()
expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
})
},
}),
)
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,159 @@
import type {
Action,
ThunkAction,
TypedAddListener,
TypedRemoveListener,
TypedStartListening,
TypedStopListening,
} from '@reduxjs/toolkit'
import {
addListener,
configureStore,
createAsyncThunk,
createListenerMiddleware,
createSlice,
removeListener,
} from '@reduxjs/toolkit'
import { describe, expectTypeOf, test } from 'vitest'
export interface CounterState {
counter: number
}
const initialState: CounterState = {
counter: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) {
state.counter++
},
},
})
export function fetchCount(amount = 1) {
return new Promise<{ data: number }>((resolve) =>
setTimeout(() => resolve({ data: amount }), 500),
)
}
export const incrementAsync = createAsyncThunk(
'counter/fetchCount',
async (amount: number) => {
const response = await fetchCount(amount)
// The value we return becomes the `fulfilled` action payload
return response.data
},
)
const { increment } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer,
})
type AppStore = typeof store
type AppDispatch = typeof store.dispatch
type RootState = ReturnType<typeof store.getState>
type AppThunk<ThunkReturnType = void> = ThunkAction<
ThunkReturnType,
RootState,
unknown,
Action
>
type ExtraArgument = { foo: string }
describe('listenerMiddleware.withTypes<RootState, AppDispatch>()', () => {
const listenerMiddleware = createListenerMiddleware()
let timeout: number | undefined = undefined
let done = false
type ExpectedTakeResultType =
| [ReturnType<typeof increment>, RootState, RootState]
| null
test('startListening.withTypes', () => {
const startAppListening = listenerMiddleware.startListening.withTypes<
RootState,
AppDispatch,
ExtraArgument
>()
expectTypeOf(startAppListening).toEqualTypeOf<
TypedStartListening<RootState, AppDispatch, ExtraArgument>
>()
startAppListening({
predicate: increment.match,
effect: async (action, listenerApi) => {
const stateBefore = listenerApi.getState()
expectTypeOf(increment).returns.toEqualTypeOf(action)
expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()
expectTypeOf(stateBefore).toEqualTypeOf<RootState>()
let takeResult = await listenerApi.take(increment.match, timeout)
const stateCurrent = listenerApi.getState()
expectTypeOf(takeResult).toEqualTypeOf<ExpectedTakeResultType>()
expectTypeOf(stateCurrent).toEqualTypeOf<RootState>()
expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()
timeout = 1
takeResult = await listenerApi.take(increment.match, timeout)
done = true
},
})
})
test('addListener.withTypes', () => {
const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArgument>()
expectTypeOf(addAppListener).toEqualTypeOf<
TypedAddListener<RootState, AppDispatch, ExtraArgument>
>()
store.dispatch(
addAppListener({
matcher: increment.match,
effect: (action, listenerApi) => {
const state = listenerApi.getState()
expectTypeOf(state).toEqualTypeOf<RootState>()
expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()
expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()
},
}),
)
})
test('removeListener.withTypes', () => {
const removeAppListener = removeListener.withTypes<RootState, AppDispatch, ExtraArgument>()
expectTypeOf(removeAppListener).toEqualTypeOf<
TypedRemoveListener<RootState, AppDispatch, ExtraArgument>
>()
})
test('stopListening.withTypes', () => {
const stopAppListening = listenerMiddleware.stopListening.withTypes<
RootState,
AppDispatch,
ExtraArgument
>()
expectTypeOf(stopAppListening).toEqualTypeOf<
TypedStopListening<RootState, AppDispatch, ExtraArgument>
>()
})
})

View File

@@ -0,0 +1,120 @@
import type { Action } from 'redux'
import type { ThunkAction } from 'redux-thunk'
import { describe, expect, test } from 'vitest'
import { configureStore } from '../../configureStore'
import { createAsyncThunk } from '../../createAsyncThunk'
import { createSlice } from '../../createSlice'
import { addListener, createListenerMiddleware, removeListener } from '../index'
export interface CounterState {
counter: number
}
const initialState: CounterState = {
counter: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) {
state.counter++
},
},
})
export function fetchCount(amount = 1) {
return new Promise<{ data: number }>((resolve) =>
setTimeout(() => resolve({ data: amount }), 500),
)
}
export const incrementAsync = createAsyncThunk(
'counter/fetchCount',
async (amount: number) => {
const response = await fetchCount(amount)
// The value we return becomes the `fulfilled` action payload
return response.data
},
)
const { increment } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer,
})
type AppStore = typeof store
type AppDispatch = typeof store.dispatch
type RootState = ReturnType<typeof store.getState>
type AppThunk<ThunkReturnType = void> = ThunkAction<
ThunkReturnType,
RootState,
unknown,
Action
>
type ExtraArgument = { foo: string }
const listenerMiddleware = createListenerMiddleware()
const startAppListening = listenerMiddleware.startListening.withTypes<
RootState,
AppDispatch,
ExtraArgument
>()
const stopAppListening = listenerMiddleware.stopListening.withTypes<
RootState,
AppDispatch,
ExtraArgument
>()
const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArgument>()
const removeAppListener = removeListener.withTypes<RootState, AppDispatch, ExtraArgument>()
describe('startAppListening.withTypes', () => {
test('should return startListening', () => {
expect(startAppListening.withTypes).toEqual(expect.any(Function))
expect(startAppListening.withTypes().withTypes).toEqual(
expect.any(Function),
)
expect(startAppListening).toBe(listenerMiddleware.startListening)
})
})
describe('stopAppListening.withTypes', () => {
test('should return stopListening', () => {
expect(stopAppListening.withTypes).toEqual(expect.any(Function))
expect(stopAppListening.withTypes().withTypes).toEqual(expect.any(Function))
expect(stopAppListening).toBe(listenerMiddleware.stopListening)
})
})
describe('addAppListener.withTypes', () => {
test('should return addListener', () => {
expect(addAppListener.withTypes).toEqual(expect.any(Function))
expect(addAppListener.withTypes().withTypes).toEqual(expect.any(Function))
expect(addAppListener).toBe(addListener)
})
})
describe('removeAppListener.withTypes', () => {
test('should return removeListener', () => {
expect(removeAppListener.withTypes).toEqual(expect.any(Function))
expect(removeAppListener.withTypes().withTypes).toEqual(
expect.any(Function),
)
expect(removeAppListener).toBe(removeListener)
})
})

View File

@@ -0,0 +1,175 @@
import {
configureStore,
createAction,
createSlice,
isAnyOf,
} from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import { createListenerMiddleware } from '../index'
import type { TypedAddListener } from '../index'
import { TaskAbortError } from '../exceptions'
interface CounterState {
value: number
}
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
describe('Saga-style Effects Scenarios', () => {
let listenerMiddleware = createListenerMiddleware<CounterState>()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
const testAction1 = createAction<string>('testAction1')
type TestAction1 = ReturnType<typeof testAction1>
const testAction2 = createAction<string>('testAction2')
type TestAction2 = ReturnType<typeof testAction2>
const testAction3 = createAction<string>('testAction3')
type TestAction3 = ReturnType<typeof testAction3>
type RootState = ReturnType<typeof store.getState>
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
beforeEach(() => {
listenerMiddleware = createListenerMiddleware<CounterState>()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
test('Long polling loop', async () => {
// Reimplementation of a saga-based long-polling loop that is controlled
// by "start/stop" actions. The infinite loop waits for a message from the
// server, processes it somehow, and waits for the next message.
// Ref: https://gist.github.com/markerikson/5203e71a69fa9dff203c9e27c3d84154
const eventPollingStarted = createAction('serverPolling/started')
const eventPollingStopped = createAction('serverPolling/stopped')
// For this example, we're going to fake up a "server event poll" async
// function by wrapping an event emitter so that every call returns a
// promise that is resolved the next time an event is emitted.
// This is the tiniest event emitter I could find to copy-paste in here.
let createNanoEvents = () => ({
events: {} as Record<string, any>,
emit(event: string, ...args: any[]) {
;(this.events[event] || []).forEach((i: any) => i(...args))
},
on(event: string, cb: (...args: any[]) => void) {
;(this.events[event] = this.events[event] || []).push(cb)
return () =>
(this.events[event] = (this.events[event] || []).filter(
(l: any) => l !== cb,
))
},
})
const emitter = createNanoEvents()
// Rig up a dummy "receive a message from the server" API we can trigger manually
function pollForEvent() {
return new Promise<{ type: string }>((resolve, reject) => {
const unsubscribe = emitter.on('serverEvent', (arg1: string) => {
unsubscribe()
resolve({ type: arg1 })
})
})
}
// Track how many times each message was processed by the loop
const receivedMessages = {
a: 0,
b: 0,
c: 0,
}
let pollingTaskStarted = false
let pollingTaskCanceled = false
startListening({
actionCreator: eventPollingStarted,
effect: async (action, listenerApi) => {
listenerApi.unsubscribe()
// Start a child job that will infinitely loop receiving messages
const pollingTask = listenerApi.fork(async (forkApi) => {
pollingTaskStarted = true
try {
while (true) {
// Cancelation-aware pause for a new server message
const serverEvent = await forkApi.pause(pollForEvent())
// Process the message. In this case, just count the times we've seen this message.
if (serverEvent.type in receivedMessages) {
receivedMessages[
serverEvent.type as keyof typeof receivedMessages
]++
}
}
} catch (err) {
if (err instanceof TaskAbortError) {
pollingTaskCanceled = true
}
}
return 0
})
// Wait for the "stop polling" action
await listenerApi.condition(eventPollingStopped.match)
pollingTask.cancel()
},
})
store.dispatch(eventPollingStarted())
await delay(5)
expect(pollingTaskStarted).toBe(true)
await delay(5)
emitter.emit('serverEvent', 'a')
// Promise resolution
await delay(1)
emitter.emit('serverEvent', 'b')
// Promise resolution
await delay(1)
store.dispatch(eventPollingStopped())
// Have to break out of the event loop to let the cancelation promise
// kick in - emitting before this would still resolve pollForEvent()
await delay(1)
emitter.emit('serverEvent', 'c')
// A and B were processed earlier. The first C was processed because the
// emitter synchronously resolved the `pollForEvents` promise before
// the cancelation took effect, but after another pause, the
// cancelation kicked in and the second C is ignored.
expect(receivedMessages).toEqual({ a: 1, b: 1, c: 0 })
expect(pollingTaskCanceled).toBe(true)
})
})

View File

@@ -0,0 +1,878 @@
import type {
Action,
Dispatch,
Middleware,
MiddlewareAPI,
UnknownAction,
} from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import type { BaseActionCreator, PayloadAction } from '../createAction'
import type { TypedActionCreator } from '../mapBuilders'
import type { TaskAbortError } from './exceptions'
/**
* @internal
* At the time of writing `lib.dom.ts` does not provide `abortSignal.reason`.
*/
export type AbortSignalWithReason<T> = AbortSignal & { reason?: T }
/**
* Types copied from RTK
*/
/** @internal */
type TypedActionCreatorWithMatchFunction<Type extends string> =
TypedActionCreator<Type> & {
match: MatchFunction<any>
}
/** @internal */
export type AnyListenerPredicate<State> = (
action: UnknownAction,
currentState: State,
originalState: State,
) => boolean
/** @public */
export type ListenerPredicate<ActionType extends Action, State> = (
action: UnknownAction,
currentState: State,
originalState: State,
) => action is ActionType
/** @public */
export interface ConditionFunction<State> {
(predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>
(predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>
(predicate: () => boolean, timeout?: number): Promise<boolean>
}
/** @internal */
export type MatchFunction<T> = (v: any) => v is T
/** @public */
export interface ForkedTaskAPI {
/**
* Returns a promise that resolves when `waitFor` resolves or
* rejects if the task or the parent listener has been cancelled or is completed.
*/
pause<W>(waitFor: Promise<W>): Promise<W>
/**
* Returns a promise that resolves after `timeoutMs` or
* rejects if the task or the parent listener has been cancelled or is completed.
* @param timeoutMs
*/
delay(timeoutMs: number): Promise<void>
/**
* An abort signal whose `aborted` property is set to `true`
* if the task execution is either aborted or completed.
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
signal: AbortSignal
}
/** @public */
export interface AsyncTaskExecutor<T> {
(forkApi: ForkedTaskAPI): Promise<T>
}
/** @public */
export interface SyncTaskExecutor<T> {
(forkApi: ForkedTaskAPI): T
}
/** @public */
export type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>
/** @public */
export type TaskResolved<T> = {
readonly status: 'ok'
readonly value: T
}
/** @public */
export type TaskRejected = {
readonly status: 'rejected'
readonly error: unknown
}
/** @public */
export type TaskCancelled = {
readonly status: 'cancelled'
readonly error: TaskAbortError
}
/** @public */
export type TaskResult<Value> =
| TaskResolved<Value>
| TaskRejected
| TaskCancelled
/** @public */
export interface ForkedTask<T> {
/**
* A promise that resolves when the task is either completed or cancelled or rejects
* if parent listener execution is cancelled or completed.
*
* ### Example
* ```ts
* const result = await fork(async (forkApi) => Promise.resolve(4)).result
*
* if(result.status === 'ok') {
* console.log(result.value) // logs 4
* }}
* ```
*/
result: Promise<TaskResult<T>>
/**
* Cancel task if it is in progress or not yet started,
* it is noop otherwise.
*/
cancel(): void
}
/** @public */
export interface ForkOptions {
/**
* If true, causes the parent task to not be marked as complete until
* all autoJoined forks have completed or failed.
*/
autoJoin: boolean
}
/** @public */
export interface ListenerEffectAPI<
State,
DispatchType extends Dispatch,
ExtraArgument = unknown,
> extends MiddlewareAPI<DispatchType, State> {
/**
* Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
*
* ### Synchronous invocation
*
* This function can **only** be invoked **synchronously**, it throws error otherwise.
*
* @example
*
* ```ts
* middleware.startListening({
* predicate: () => true,
* async effect(_, { getOriginalState }) {
* getOriginalState(); // sync: OK!
*
* setTimeout(getOriginalState, 0); // async: throws Error
*
* await Promise().resolve();
*
* getOriginalState() // async: throws Error
* }
* })
* ```
*/
getOriginalState: () => State
/**
* Removes the listener entry from the middleware and prevent future instances of the listener from running.
*
* It does **not** cancel any active instances.
*/
unsubscribe(): void
/**
* It will subscribe a listener if it was previously removed, noop otherwise.
*/
subscribe(): void
/**
* Returns a promise that resolves when the input predicate returns `true` or
* rejects if the listener has been cancelled or is completed.
*
* The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
*
* ### Example
*
* ```ts
* const updateBy = createAction<number>('counter/updateBy');
*
* middleware.startListening({
* actionCreator: updateBy,
* async effect(_, { condition }) {
* // wait at most 3s for `updateBy` actions.
* if(await condition(updateBy.match, 3_000)) {
* // `updateBy` has been dispatched twice in less than 3s.
* }
* }
* })
* ```
*/
condition: ConditionFunction<State>
/**
* Returns a promise that resolves when the input predicate returns `true` or
* rejects if the listener has been cancelled or is completed.
*
* The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
*
* The promise resolves to null if a timeout is provided and expires first,
*
* ### Example
*
* ```ts
* const updateBy = createAction<number>('counter/updateBy');
*
* middleware.startListening({
* actionCreator: updateBy,
* async effect(_, { take }) {
* const [{ payload }] = await take(updateBy.match);
* console.log(payload); // logs 5;
* }
* })
*
* store.dispatch(updateBy(5));
* ```
*/
take: TakePattern<State>
/**
* Cancels all other running instances of this same listener except for the one that made this call.
*/
cancelActiveListeners: () => void
/**
* Cancels the instance of this listener that made this call.
*/
cancel: () => void
/**
* Throws a `TaskAbortError` if this listener has been cancelled
*/
throwIfCancelled: () => void
/**
* An abort signal whose `aborted` property is set to `true`
* if the listener execution is either aborted or completed.
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
signal: AbortSignal
/**
* Returns a promise that resolves after `timeoutMs` or
* rejects if the listener has been cancelled or is completed.
*/
delay(timeoutMs: number): Promise<void>
/**
* Queues in the next microtask the execution of a task.
* @param executor
* @param options
*/
fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>
/**
* Returns a promise that resolves when `waitFor` resolves or
* rejects if the listener has been cancelled or is completed.
* @param promise
*/
pause<M>(promise: Promise<M>): Promise<M>
extra: ExtraArgument
}
/** @public */
export type ListenerEffect<
ActionType extends Action,
State,
DispatchType extends Dispatch,
ExtraArgument = unknown,
> = (
action: ActionType,
api: ListenerEffectAPI<State, DispatchType, ExtraArgument>,
) => void | Promise<void>
/**
* @public
* Additional infos regarding the error raised.
*/
export interface ListenerErrorInfo {
/**
* Which function has generated the exception.
*/
raisedBy: 'effect' | 'predicate'
}
/**
* @public
* Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
* @param error The thrown error.
* @param errorInfo Additional information regarding the thrown error.
*/
export interface ListenerErrorHandler {
(error: unknown, errorInfo: ListenerErrorInfo): void
}
/** @public */
export interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
extra?: ExtraArgument
/**
* Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
*/
onError?: ListenerErrorHandler
}
/** @public */
export type ListenerMiddleware<
State = unknown,
DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<
State,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
> = Middleware<
{
(action: Action<'listenerMiddleware/add'>): UnsubscribeListener
},
State,
DispatchType
>
/** @public */
export interface ListenerMiddlewareInstance<
StateType = unknown,
DispatchType extends ThunkDispatch<
StateType,
unknown,
Action
> = ThunkDispatch<StateType, unknown, UnknownAction>,
ExtraArgument = unknown,
> {
middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>
startListening: AddListenerOverloads<
UnsubscribeListener,
StateType,
DispatchType,
ExtraArgument
> &
TypedStartListening<StateType, DispatchType, ExtraArgument>
stopListening: RemoveListenerOverloads<StateType, DispatchType> &
TypedStopListening<StateType, DispatchType>
/**
* Unsubscribes all listeners, cancels running listeners and tasks.
*/
clearListeners: () => void
}
/**
* API Function Overloads
*/
/** @public */
export type TakePatternOutputWithoutTimeout<
State,
Predicate extends AnyListenerPredicate<State>,
> =
Predicate extends MatchFunction<infer ActionType>
? Promise<[ActionType, State, State]>
: Promise<[UnknownAction, State, State]>
/** @public */
export type TakePatternOutputWithTimeout<
State,
Predicate extends AnyListenerPredicate<State>,
> =
Predicate extends MatchFunction<infer ActionType>
? Promise<[ActionType, State, State] | null>
: Promise<[UnknownAction, State, State] | null>
/** @public */
export interface TakePattern<State> {
<Predicate extends AnyListenerPredicate<State>>(
predicate: Predicate,
): TakePatternOutputWithoutTimeout<State, Predicate>
<Predicate extends AnyListenerPredicate<State>>(
predicate: Predicate,
timeout: number,
): TakePatternOutputWithTimeout<State, Predicate>
<Predicate extends AnyListenerPredicate<State>>(
predicate: Predicate,
timeout?: number | undefined,
): TakePatternOutputWithTimeout<State, Predicate>
}
/** @public */
export interface UnsubscribeListenerOptions {
cancelActive?: true
}
/** @public */
export type UnsubscribeListener = (
unsubscribeOptions?: UnsubscribeListenerOptions,
) => void
/**
* @public
* The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
*/
export type AddListenerOverloads<
Return,
StateType = unknown,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
AdditionalOptions = unknown,
> = {
/** Accepts a "listener predicate" that is also a TS type predicate for the action*/
<
MiddlewareActionType extends UnknownAction,
ListenerPredicateType extends ListenerPredicate<
MiddlewareActionType,
StateType
>,
>(
options: {
actionCreator?: never
type?: never
matcher?: never
predicate: ListenerPredicateType
effect: ListenerEffect<
ListenerPredicateGuardedActionType<ListenerPredicateType>,
StateType,
DispatchType,
ExtraArgument
>
} & AdditionalOptions,
): Return
/** Accepts an RTK action creator, like `incrementByAmount` */
<ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(
options: {
actionCreator: ActionCreatorType
type?: never
matcher?: never
predicate?: never
effect: ListenerEffect<
ReturnType<ActionCreatorType>,
StateType,
DispatchType,
ExtraArgument
>
} & AdditionalOptions,
): Return
/** Accepts a specific action type string */
<T extends string>(
options: {
actionCreator?: never
type: T
matcher?: never
predicate?: never
effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>
} & AdditionalOptions,
): Return
/** Accepts an RTK matcher function, such as `incrementByAmount.match` */
<MatchFunctionType extends MatchFunction<UnknownAction>>(
options: {
actionCreator?: never
type?: never
matcher: MatchFunctionType
predicate?: never
effect: ListenerEffect<
GuardedType<MatchFunctionType>,
StateType,
DispatchType,
ExtraArgument
>
} & AdditionalOptions,
): Return
/** Accepts a "listener predicate" that just returns a boolean, no type assertion */
<ListenerPredicateType extends AnyListenerPredicate<StateType>>(
options: {
actionCreator?: never
type?: never
matcher?: never
predicate: ListenerPredicateType
effect: ListenerEffect<
UnknownAction,
StateType,
DispatchType,
ExtraArgument
>
} & AdditionalOptions,
): Return
}
/** @public */
export type RemoveListenerOverloads<
StateType = unknown,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
> = AddListenerOverloads<
boolean,
StateType,
DispatchType,
ExtraArgument,
UnsubscribeListenerOptions
>
/** @public */
export interface RemoveListenerAction<
ActionType extends UnknownAction,
State,
DispatchType extends Dispatch,
> {
type: 'listenerMiddleware/remove'
payload: {
type: string
listener: ListenerEffect<ActionType, State, DispatchType>
}
}
/**
* A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
*
* @public
*/
export type TypedAddListener<
StateType,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
Payload = ListenerEntry<StateType, DispatchType>,
T extends string = 'listenerMiddleware/add',
> = BaseActionCreator<Payload, T> &
AddListenerOverloads<
PayloadAction<Payload, T>,
StateType,
DispatchType,
ExtraArgument
> & {
/**
* Creates a "pre-typed" version of `addListener`
* where the `state`, `dispatch` and `extra` types are predefined.
*
* This allows you to set the `state`, `dispatch` and `extra` types once,
* eliminating the need to specify them with every `addListener` call.
*
* @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
*
* @example
* ```ts
* import { addListener } from '@reduxjs/toolkit'
*
* export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
* ```
*
* @template OverrideStateType - The specific type of state the middleware listener operates on.
* @template OverrideDispatchType - The specific type of the dispatch function.
* @template OverrideExtraArgument - The specific type of the extra object.
*
* @since 2.1.0
*/
withTypes: <
OverrideStateType extends StateType,
OverrideDispatchType extends Dispatch = ThunkDispatch<
OverrideStateType,
unknown,
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedAddListener<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}
/**
* A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
*
* @public
*/
export type TypedRemoveListener<
StateType,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
Payload = ListenerEntry<StateType, DispatchType>,
T extends string = 'listenerMiddleware/remove',
> = BaseActionCreator<Payload, T> &
AddListenerOverloads<
PayloadAction<Payload, T>,
StateType,
DispatchType,
ExtraArgument,
UnsubscribeListenerOptions
> & {
/**
* Creates a "pre-typed" version of `removeListener`
* where the `state`, `dispatch` and `extra` types are predefined.
*
* This allows you to set the `state`, `dispatch` and `extra` types once,
* eliminating the need to specify them with every `removeListener` call.
*
* @returns A pre-typed `removeListener` with the state, dispatch and extra
* types already defined.
*
* @example
* ```ts
* import { removeListener } from '@reduxjs/toolkit'
*
* export const removeAppListener = removeListener.withTypes<
* RootState,
* AppDispatch,
* ExtraArguments
* >()
* ```
*
* @template OverrideStateType - The specific type of state the middleware listener operates on.
* @template OverrideDispatchType - The specific type of the dispatch function.
* @template OverrideExtraArgument - The specific type of the extra object.
*
* @since 2.1.0
*/
withTypes: <
OverrideStateType extends StateType,
OverrideDispatchType extends Dispatch = ThunkDispatch<
OverrideStateType,
unknown,
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedRemoveListener<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}
/**
* A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
*
* @public
*/
export type TypedStartListening<
StateType,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
> = AddListenerOverloads<
UnsubscribeListener,
StateType,
DispatchType,
ExtraArgument
> & {
/**
* Creates a "pre-typed" version of
* {@linkcode ListenerMiddlewareInstance.startListening startListening}
* where the `state`, `dispatch` and `extra` types are predefined.
*
* This allows you to set the `state`, `dispatch` and `extra` types once,
* eliminating the need to specify them with every
* {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
*
* @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
*
* @example
* ```ts
* import { createListenerMiddleware } from '@reduxjs/toolkit'
*
* const listenerMiddleware = createListenerMiddleware()
*
* export const startAppListening = listenerMiddleware.startListening.withTypes<
* RootState,
* AppDispatch,
* ExtraArguments
* >()
* ```
*
* @template OverrideStateType - The specific type of state the middleware listener operates on.
* @template OverrideDispatchType - The specific type of the dispatch function.
* @template OverrideExtraArgument - The specific type of the extra object.
*
* @since 2.1.0
*/
withTypes: <
OverrideStateType extends StateType,
OverrideDispatchType extends Dispatch = ThunkDispatch<
OverrideStateType,
unknown,
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedStartListening<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}
/**
* A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
*
* @public
*/
export type TypedStopListening<
StateType,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
/**
* Creates a "pre-typed" version of
* {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
* where the `state`, `dispatch` and `extra` types are predefined.
*
* This allows you to set the `state`, `dispatch` and `extra` types once,
* eliminating the need to specify them with every
* {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
*
* @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
*
* @example
* ```ts
* import { createListenerMiddleware } from '@reduxjs/toolkit'
*
* const listenerMiddleware = createListenerMiddleware()
*
* export const stopAppListening = listenerMiddleware.stopListening.withTypes<
* RootState,
* AppDispatch,
* ExtraArguments
* >()
* ```
*
* @template OverrideStateType - The specific type of state the middleware listener operates on.
* @template OverrideDispatchType - The specific type of the dispatch function.
* @template OverrideExtraArgument - The specific type of the extra object.
*
* @since 2.1.0
*/
withTypes: <
OverrideStateType extends StateType,
OverrideDispatchType extends Dispatch = ThunkDispatch<
OverrideStateType,
unknown,
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedStopListening<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}
/**
* A "pre-typed" version of `createListenerEntry`, so the listener args are well-typed
*
* @public
*/
export type TypedCreateListenerEntry<
StateType,
DispatchType extends Dispatch = ThunkDispatch<
StateType,
unknown,
UnknownAction
>,
ExtraArgument = unknown,
> = AddListenerOverloads<
ListenerEntry<StateType, DispatchType>,
StateType,
DispatchType,
ExtraArgument
> & {
/**
* Creates a "pre-typed" version of `createListenerEntry`
* where the `state`, `dispatch` and `extra` types are predefined.
*
* This allows you to set the `state`, `dispatch` and `extra` types once, eliminating
* the need to specify them with every `createListenerEntry` call.
*
* @returns A pre-typed `createListenerEntry` with the state, dispatch and extra
* types already defined.
*
* @example
* ```ts
* import { createListenerEntry } from '@reduxjs/toolkit'
*
* export const createAppListenerEntry = createListenerEntry.withTypes<
* RootState,
* AppDispatch,
* ExtraArguments
* >()
* ```
*
* @template OverrideStateType - The specific type of state the middleware listener operates on.
* @template OverrideDispatchType - The specific type of the dispatch function.
* @template OverrideExtraArgument - The specific type of the extra object.
*
* @since 2.1.0
*/
withTypes: <
OverrideStateType extends StateType,
OverrideDispatchType extends Dispatch = ThunkDispatch<
OverrideStateType,
unknown,
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedStopListening<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}
/**
* Internal Types
*/
/** @internal An single listener entry */
export type ListenerEntry<
State = unknown,
DispatchType extends Dispatch = Dispatch,
> = {
id: string
effect: ListenerEffect<any, State, DispatchType>
unsubscribe: () => void
pending: Set<AbortController>
type?: string
predicate: ListenerPredicate<UnknownAction, State>
}
/**
* @internal
* A shorthand form of the accepted args, solely so that `createListenerEntry` has validly-typed conditional logic when checking the options contents
*/
export type FallbackAddListenerOptions = {
actionCreator?: TypedActionCreatorWithMatchFunction<string>
type?: string
matcher?: MatchFunction<any>
predicate?: ListenerPredicate<any, any>
} & { effect: ListenerEffect<any, any, any> }
/**
* Utility Types
*/
/** @public */
export type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T
? T
: never
/** @public */
export type ListenerPredicateGuardedActionType<T> =
T extends ListenerPredicate<infer ActionType, any> ? ActionType : never

View File

@@ -0,0 +1,70 @@
import type { AbortSignalWithReason } from './types'
export const assertFunction: (
func: unknown,
expected: string,
) => asserts func is (...args: unknown[]) => unknown = (
func: unknown,
expected: string,
) => {
if (typeof func !== 'function') {
throw new TypeError(`${expected} is not a function`)
}
}
export const noop = () => {}
export const catchRejection = <T>(
promise: Promise<T>,
onError = noop,
): Promise<T> => {
promise.catch(onError)
return promise
}
export const addAbortSignalListener = (
abortSignal: AbortSignal,
callback: (evt: Event) => void,
) => {
abortSignal.addEventListener('abort', callback, { once: true })
return () => abortSignal.removeEventListener('abort', callback)
}
/**
* Calls `abortController.abort(reason)` and patches `signal.reason`.
* if it is not supported.
*
* At the time of writing `signal.reason` is available in FF chrome, edge node 17 and deno.
* @param abortController
* @param reason
* @returns
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason
*/
export const abortControllerWithReason = <T>(
abortController: AbortController,
reason: T,
): void => {
type Consumer<T> = (val: T) => void
const signal = abortController.signal as AbortSignalWithReason<T>
if (signal.aborted) {
return
}
// Patch `reason` if necessary.
// - We use defineProperty here because reason is a getter of `AbortSignal.__proto__`.
// - We need to patch 'reason' before calling `.abort()` because listeners to the 'abort'
// event are are notified immediately.
if (!('reason' in signal)) {
Object.defineProperty(signal, 'reason', {
enumerable: true,
value: reason,
configurable: true,
writable: true,
})
}
;(abortController.abort as Consumer<typeof reason>)(reason)
}

View File

@@ -0,0 +1,299 @@
import type { Action } from 'redux'
import type {
CaseReducer,
CaseReducers,
ActionMatcherDescriptionCollection,
} from './createReducer'
import type { TypeGuard } from './tsHelpers'
import type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk'
export type AsyncThunkReducers<
State,
ThunkArg extends any,
Returned = unknown,
ThunkApiConfig extends AsyncThunkConfig = {},
> = {
pending?: CaseReducer<
State,
ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>
>
rejected?: CaseReducer<
State,
ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>
>
fulfilled?: CaseReducer<
State,
ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>
>
settled?: CaseReducer<
State,
ReturnType<
AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']
>
>
}
export type TypedActionCreator<Type extends string> = {
(...args: any[]): Action<Type>
type: Type
}
/**
* A builder for an action <-> reducer map.
*
* @public
*/
export interface ActionReducerMapBuilder<State> {
/**
* Adds a case reducer to handle a single exact action type.
* @remarks
* All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<ActionCreator extends TypedActionCreator<string>>(
actionCreator: ActionCreator,
reducer: CaseReducer<State, ReturnType<ActionCreator>>,
): ActionReducerMapBuilder<State>
/**
* Adds a case reducer to handle a single exact action type.
* @remarks
* All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<Type extends string, A extends Action<Type>>(
type: Type,
reducer: CaseReducer<State, A>,
): ActionReducerMapBuilder<State>
/**
* Adds case reducers to handle actions based on a `AsyncThunk` action creator.
* @remarks
* All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
* @param asyncThunk - The async thunk action creator itself.
* @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
* @example
```ts no-transpile
import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'
const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
const response = await fetch(`https://reqres.in/api/users/${id}`)
return (await response.json()).data
})
const reducer = createReducer(initialState, (builder) => {
builder.addAsyncThunk(fetchUserById, {
pending: (state, action) => {
state.fetchUserById.loading = 'pending'
},
fulfilled: (state, action) => {
state.fetchUserById.data = action.payload
},
rejected: (state, action) => {
state.fetchUserById.error = action.error
},
settled: (state, action) => {
state.fetchUserById.loading = action.meta.requestStatus
},
})
})
*/
addAsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig = {},
>(
asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,
reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>,
): Omit<ActionReducerMapBuilder<State>, 'addCase'>
/**
* Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
* @remarks
* If multiple matcher reducers match, all of them will be executed in the order
* they were defined in - even if a case reducer already matched.
* All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
* @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
* function
* @param reducer - The actual case reducer function.
*
* @example
```ts
import {
createAction,
createReducer,
AsyncThunk,
UnknownAction,
} from "@reduxjs/toolkit";
type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
const initialState: Record<string, string> = {};
const resetAction = createAction("reset-tracked-loading-state");
function isPendingAction(action: UnknownAction): action is PendingAction {
return typeof action.type === "string" && action.type.endsWith("/pending");
}
const reducer = createReducer(initialState, (builder) => {
builder
.addCase(resetAction, () => initialState)
// matcher can be defined outside as a type predicate function
.addMatcher(isPendingAction, (state, action) => {
state[action.meta.requestId] = "pending";
})
.addMatcher(
// matcher can be defined inline as a type predicate function
(action): action is RejectedAction => action.type.endsWith("/rejected"),
(state, action) => {
state[action.meta.requestId] = "rejected";
}
)
// matcher can just return boolean and the matcher can receive a generic argument
.addMatcher<FulfilledAction>(
(action) => action.type.endsWith("/fulfilled"),
(state, action) => {
state[action.meta.requestId] = "fulfilled";
}
);
});
```
*/
addMatcher<A>(
matcher: TypeGuard<A> | ((action: any) => boolean),
reducer: CaseReducer<State, A extends Action ? A : A & Action>,
): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>
/**
* Adds a "default case" reducer that is executed if no case reducer and no matcher
* reducer was executed for this action.
* @param reducer - The fallback "default case" reducer function.
*
* @example
```ts
import { createReducer } from '@reduxjs/toolkit'
const initialState = { otherActions: 0 }
const reducer = createReducer(initialState, builder => {
builder
// .addCase(...)
// .addMatcher(...)
.addDefaultCase((state, action) => {
state.otherActions++
})
})
```
*/
addDefaultCase(reducer: CaseReducer<State, Action>): {}
}
export function executeReducerBuilderCallback<S>(
builderCallback: (builder: ActionReducerMapBuilder<S>) => void,
): [
CaseReducers<S, any>,
ActionMatcherDescriptionCollection<S>,
CaseReducer<S, Action> | undefined,
] {
const actionsMap: CaseReducers<S, any> = {}
const actionMatchers: ActionMatcherDescriptionCollection<S> = []
let defaultCaseReducer: CaseReducer<S, Action> | undefined
const builder = {
addCase(
typeOrActionCreator: string | TypedActionCreator<any>,
reducer: CaseReducer<S>,
) {
if (process.env.NODE_ENV !== 'production') {
/*
to keep the definition by the user in line with actual behavior,
we enforce `addCase` to always be called before calling `addMatcher`
as matching cases take precedence over matchers
*/
if (actionMatchers.length > 0) {
throw new Error(
'`builder.addCase` should only be called before calling `builder.addMatcher`',
)
}
if (defaultCaseReducer) {
throw new Error(
'`builder.addCase` should only be called before calling `builder.addDefaultCase`',
)
}
}
const type =
typeof typeOrActionCreator === 'string'
? typeOrActionCreator
: typeOrActionCreator.type
if (!type) {
throw new Error(
'`builder.addCase` cannot be called with an empty action type',
)
}
if (type in actionsMap) {
throw new Error(
'`builder.addCase` cannot be called with two reducers for the same action type ' +
`'${type}'`,
)
}
actionsMap[type] = reducer
return builder
},
addAsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig = {},
>(
asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,
reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>,
) {
if (process.env.NODE_ENV !== 'production') {
// since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case
if (defaultCaseReducer) {
throw new Error(
'`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`',
)
}
}
if (reducers.pending)
actionsMap[asyncThunk.pending.type] = reducers.pending
if (reducers.rejected)
actionsMap[asyncThunk.rejected.type] = reducers.rejected
if (reducers.fulfilled)
actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled
if (reducers.settled)
actionMatchers.push({
matcher: asyncThunk.settled,
reducer: reducers.settled,
})
return builder
},
addMatcher<A>(
matcher: TypeGuard<A>,
reducer: CaseReducer<S, A extends Action ? A : A & Action>,
) {
if (process.env.NODE_ENV !== 'production') {
if (defaultCaseReducer) {
throw new Error(
'`builder.addMatcher` should only be called before calling `builder.addDefaultCase`',
)
}
}
actionMatchers.push({ matcher, reducer })
return builder
},
addDefaultCase(reducer: CaseReducer<S, Action>) {
if (process.env.NODE_ENV !== 'production') {
if (defaultCaseReducer) {
throw new Error('`builder.addDefaultCase` can only be called once')
}
}
defaultCaseReducer = reducer
return builder
},
}
builderCallback(builder)
return [actionsMap, actionMatchers, defaultCaseReducer]
}

365
frontend/node_modules/@reduxjs/toolkit/src/matchers.ts generated vendored Normal file
View File

@@ -0,0 +1,365 @@
import type {
ActionFromMatcher,
Matcher,
UnionToIntersection,
} from './tsHelpers'
import { hasMatchFunction } from './tsHelpers'
import type {
AsyncThunk,
AsyncThunkFulfilledActionCreator,
AsyncThunkPendingActionCreator,
AsyncThunkRejectedActionCreator,
} from './createAsyncThunk'
/** @public */
export type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> =
ActionFromMatcher<Matchers[number]>
/** @public */
export type ActionMatchingAllOf<Matchers extends Matcher<any>[]> =
UnionToIntersection<ActionMatchingAnyOf<Matchers>>
const matches = (matcher: Matcher<any>, action: any) => {
if (hasMatchFunction(matcher)) {
return matcher.match(action)
} else {
return matcher(action)
}
}
/**
* A higher-order function that returns a function that may be used to check
* whether an action matches any one of the supplied type guards or action
* creators.
*
* @param matchers The type guards or action creators to match against.
*
* @public
*/
export function isAnyOf<Matchers extends Matcher<any>[]>(
...matchers: Matchers
) {
return (action: any): action is ActionMatchingAnyOf<Matchers> => {
return matchers.some((matcher) => matches(matcher, action))
}
}
/**
* A higher-order function that returns a function that may be used to check
* whether an action matches all of the supplied type guards or action
* creators.
*
* @param matchers The type guards or action creators to match against.
*
* @public
*/
export function isAllOf<Matchers extends Matcher<any>[]>(
...matchers: Matchers
) {
return (action: any): action is ActionMatchingAllOf<Matchers> => {
return matchers.every((matcher) => matches(matcher, action))
}
}
/**
* @param action A redux action
* @param validStatus An array of valid meta.requestStatus values
*
* @internal
*/
export function hasExpectedRequestMetadata(
action: any,
validStatus: readonly string[],
) {
if (!action || !action.meta) return false
const hasValidRequestId = typeof action.meta.requestId === 'string'
const hasValidRequestStatus =
validStatus.indexOf(action.meta.requestStatus) > -1
return hasValidRequestId && hasValidRequestStatus
}
function isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {
return (
typeof a[0] === 'function' &&
'pending' in a[0] &&
'fulfilled' in a[0] &&
'rejected' in a[0]
)
}
export type UnknownAsyncThunkPendingAction = ReturnType<
AsyncThunkPendingActionCreator<unknown>
>
export type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> =
ActionFromMatcher<T['pending']>
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is pending.
*
* @public
*/
export function isPending(): (
action: any,
) => action is UnknownAsyncThunkPendingAction
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is pending.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export function isPending<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(
...asyncThunks: AsyncThunks
): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>
/**
* Tests if `action` is a pending thunk action
* @public
*/
export function isPending(action: any): action is UnknownAsyncThunkPendingAction
export function isPending<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(...asyncThunks: AsyncThunks | [any]) {
if (asyncThunks.length === 0) {
return (action: any) => hasExpectedRequestMetadata(action, ['pending'])
}
if (!isAsyncThunkArray(asyncThunks)) {
return isPending()(asyncThunks[0])
}
return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending))
}
export type UnknownAsyncThunkRejectedAction = ReturnType<
AsyncThunkRejectedActionCreator<unknown, unknown>
>
export type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> =
ActionFromMatcher<T['rejected']>
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is rejected.
*
* @public
*/
export function isRejected(): (
action: any,
) => action is UnknownAsyncThunkRejectedAction
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is rejected.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export function isRejected<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(
...asyncThunks: AsyncThunks
): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>
/**
* Tests if `action` is a rejected thunk action
* @public
*/
export function isRejected(
action: any,
): action is UnknownAsyncThunkRejectedAction
export function isRejected<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(...asyncThunks: AsyncThunks | [any]) {
if (asyncThunks.length === 0) {
return (action: any) => hasExpectedRequestMetadata(action, ['rejected'])
}
if (!isAsyncThunkArray(asyncThunks)) {
return isRejected()(asyncThunks[0])
}
return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected))
}
export type UnknownAsyncThunkRejectedWithValueAction = ReturnType<
AsyncThunkRejectedActionCreator<unknown, unknown>
>
export type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> =
ActionFromMatcher<T['rejected']> &
(T extends AsyncThunk<any, any, { rejectValue: infer RejectedValue }>
? { payload: RejectedValue }
: unknown)
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is rejected with value.
*
* @public
*/
export function isRejectedWithValue(): (
action: any,
) => action is UnknownAsyncThunkRejectedAction
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is rejected with value.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export function isRejectedWithValue<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(
...asyncThunks: AsyncThunks
): (
action: any,
) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>
/**
* Tests if `action` is a rejected thunk action with value
* @public
*/
export function isRejectedWithValue(
action: any,
): action is UnknownAsyncThunkRejectedAction
export function isRejectedWithValue<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(...asyncThunks: AsyncThunks | [any]) {
const hasFlag = (action: any): action is any => {
return action && action.meta && action.meta.rejectedWithValue
}
if (asyncThunks.length === 0) {
return isAllOf(isRejected(...asyncThunks), hasFlag)
}
if (!isAsyncThunkArray(asyncThunks)) {
return isRejectedWithValue()(asyncThunks[0])
}
return isAllOf(isRejected(...asyncThunks), hasFlag)
}
export type UnknownAsyncThunkFulfilledAction = ReturnType<
AsyncThunkFulfilledActionCreator<unknown, unknown>
>
export type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> =
ActionFromMatcher<T['fulfilled']>
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is fulfilled.
*
* @public
*/
export function isFulfilled(): (
action: any,
) => action is UnknownAsyncThunkFulfilledAction
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is fulfilled.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export function isFulfilled<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(
...asyncThunks: AsyncThunks
): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>
/**
* Tests if `action` is a fulfilled thunk action
* @public
*/
export function isFulfilled(
action: any,
): action is UnknownAsyncThunkFulfilledAction
export function isFulfilled<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(...asyncThunks: AsyncThunks | [any]) {
if (asyncThunks.length === 0) {
return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled'])
}
if (!isAsyncThunkArray(asyncThunks)) {
return isFulfilled()(asyncThunks[0])
}
return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled))
}
export type UnknownAsyncThunkAction =
| UnknownAsyncThunkPendingAction
| UnknownAsyncThunkRejectedAction
| UnknownAsyncThunkFulfilledAction
export type AnyAsyncThunk = {
pending: { match: (action: any) => action is any }
fulfilled: { match: (action: any) => action is any }
rejected: { match: (action: any) => action is any }
}
export type ActionsFromAsyncThunk<T extends AnyAsyncThunk> =
| ActionFromMatcher<T['pending']>
| ActionFromMatcher<T['fulfilled']>
| ActionFromMatcher<T['rejected']>
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator.
*
* @public
*/
export function isAsyncThunkAction(): (
action: any,
) => action is UnknownAsyncThunkAction
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export function isAsyncThunkAction<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(
...asyncThunks: AsyncThunks
): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>
/**
* Tests if `action` is a thunk action
* @public
*/
export function isAsyncThunkAction(
action: any,
): action is UnknownAsyncThunkAction
export function isAsyncThunkAction<
AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
>(...asyncThunks: AsyncThunks | [any]) {
if (asyncThunks.length === 0) {
return (action: any) =>
hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected'])
}
if (!isAsyncThunkArray(asyncThunks)) {
return isAsyncThunkAction()(asyncThunks[0])
}
return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]))
}

20
frontend/node_modules/@reduxjs/toolkit/src/nanoid.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js
// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped
// optimize the gzip compression for this alphabet.
let urlAlphabet =
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
/**
*
* @public
*/
export let nanoid = (size = 21) => {
let id = ''
// A compact alternative for `for (var i = 0; i < step; i++)`.
let i = size
while (i--) {
// `| 0` is more compact and faster than `Math.floor()`.
id += urlAlphabet[(Math.random() * 64) | 0]
}
return id
}

View File

@@ -0,0 +1,6 @@
export class HandledError {
constructor(
public readonly value: any,
public readonly meta: any = undefined,
) {}
}

View File

@@ -0,0 +1,124 @@
import type { UnknownAction } from '@reduxjs/toolkit'
import type { BaseQueryFn } from './baseQueryTypes'
import type { CombinedState, CoreModule, QueryKeys } from './core'
import type { ApiModules } from './core/module'
import type { CreateApiOptions } from './createApi'
import type {
EndpointBuilder,
EndpointDefinition,
EndpointDefinitions,
UpdateDefinitions,
} from './endpointDefinitions'
import type {
NoInfer,
UnionToIntersection,
WithRequiredProp,
} from './tsHelpers'
export type ModuleName = keyof ApiModules<any, any, any, any>
export type Module<Name extends ModuleName> = {
name: Name
init<
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
ReducerPath extends string,
TagTypes extends string,
>(
api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>,
options: WithRequiredProp<
CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
| 'reducerPath'
| 'serializeQueryArgs'
| 'keepUnusedDataFor'
| 'refetchOnMountOrArgChange'
| 'refetchOnFocus'
| 'refetchOnReconnect'
| 'invalidationBehavior'
| 'tagTypes'
>,
context: ApiContext<Definitions>,
): {
injectEndpoint(
endpointName: string,
definition: EndpointDefinition<any, any, any, any>,
): void
}
}
export interface ApiContext<Definitions extends EndpointDefinitions> {
apiUid: string
endpointDefinitions: Definitions
batch(cb: () => void): void
extractRehydrationInfo: (
action: UnknownAction,
) => CombinedState<any, any, any> | undefined
hasRehydrationInfo: (action: UnknownAction) => boolean
}
export const getEndpointDefinition = <
Definitions extends EndpointDefinitions,
EndpointName extends keyof Definitions,
>(
context: ApiContext<Definitions>,
endpointName: EndpointName,
) => context.endpointDefinitions[endpointName]
export type Api<
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
ReducerPath extends string,
TagTypes extends string,
Enhancers extends ModuleName = CoreModule,
> = UnionToIntersection<
ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]
> & {
/**
* A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.
*/
injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {
endpoints: (
build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
) => NewDefinitions
/**
* Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.
*
* If set to `true`, will override existing endpoints with the new definition.
* If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.
* If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.
*/
overrideExisting?: boolean | 'throw'
}): Api<
BaseQuery,
Definitions & NewDefinitions,
ReducerPath,
TagTypes,
Enhancers
>
/**
*A function to enhance a generated API with additional information. Useful with code-generation.
*/
enhanceEndpoints<
NewTagTypes extends string = never,
NewDefinitions extends EndpointDefinitions = never,
>(_: {
addTagTypes?: readonly NewTagTypes[]
endpoints?: UpdateDefinitions<
Definitions,
TagTypes | NoInfer<NewTagTypes>,
NewDefinitions
> extends infer NewDefinitions
? {
[K in keyof NewDefinitions]?:
| Partial<NewDefinitions[K]>
| ((definition: NewDefinitions[K]) => void)
}
: never
}): Api<
BaseQuery,
UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>,
ReducerPath,
TagTypes | NewTagTypes,
Enhancers
>
}

View File

@@ -0,0 +1,101 @@
import type { ThunkDispatch } from '@reduxjs/toolkit'
import type { MaybePromise, UnwrapPromise } from './tsHelpers'
export interface BaseQueryApi {
signal: AbortSignal
abort: (reason?: string) => void
dispatch: ThunkDispatch<any, any, any>
getState: () => unknown
extra: unknown
endpoint: string
type: 'query' | 'mutation'
/**
* Only available for queries: indicates if a query has been forced,
* i.e. it would have been fetched even if there would already be a cache entry
* (this does not mean that there is already a cache entry though!)
*
* This can be used to for example add a `Cache-Control: no-cache` header for
* invalidated queries.
*/
forced?: boolean
/**
* Only available for queries: the cache key that was used to store the query result
*/
queryCacheKey?: string
}
export type QueryReturnValue<T = unknown, E = unknown, M = unknown> =
| {
error: E
data?: undefined
meta?: M
}
| {
error?: undefined
data: T
meta?: M
}
export type BaseQueryFn<
Args = any,
Result = unknown,
Error = unknown,
DefinitionExtraOptions = {},
Meta = {},
> = (
args: Args,
api: BaseQueryApi,
extraOptions: DefinitionExtraOptions,
) => MaybePromise<QueryReturnValue<Result, Error, Meta>>
export type BaseQueryEnhancer<
AdditionalArgs = unknown,
AdditionalDefinitionExtraOptions = unknown,
Config = void,
> = <BaseQuery extends BaseQueryFn>(
baseQuery: BaseQuery,
config: Config,
) => BaseQueryFn<
BaseQueryArg<BaseQuery> & AdditionalArgs,
BaseQueryResult<BaseQuery>,
BaseQueryError<BaseQuery>,
BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions,
NonNullable<BaseQueryMeta<BaseQuery>>
>
/**
* @public
*/
export type BaseQueryResult<BaseQuery extends BaseQueryFn> =
UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped
? Unwrapped extends { data: any }
? Unwrapped['data']
: never
: never
/**
* @public
*/
export type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<
ReturnType<BaseQuery>
>['meta']
/**
* @public
*/
export type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<
UnwrapPromise<ReturnType<BaseQuery>>,
{ error?: undefined }
>['error']
/**
* @public
*/
export type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> =
T extends (arg: infer A, ...args: any[]) => any ? A : any
/**
* @public
*/
export type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> =
Parameters<BaseQuery>[2]

View File

@@ -0,0 +1,370 @@
import type { SerializedError } from '@reduxjs/toolkit'
import type { BaseQueryError } from '../baseQueryTypes'
import type {
BaseEndpointDefinition,
EndpointDefinitions,
FullTagDescription,
InfiniteQueryDefinition,
MutationDefinition,
PageParamFrom,
QueryArgFromAnyQuery,
QueryDefinition,
ResultTypeFrom,
} from '../endpointDefinitions'
import type { Id, WithRequiredProp } from '../tsHelpers'
export type QueryCacheKey = string & { _type: 'queryCacheKey' }
export type QuerySubstateIdentifier = { queryCacheKey: QueryCacheKey }
export type MutationSubstateIdentifier =
| { requestId: string; fixedCacheKey?: string }
| { requestId?: string; fixedCacheKey: string }
export type RefetchConfigOptions = {
refetchOnMountOrArgChange: boolean | number
refetchOnReconnect: boolean
refetchOnFocus: boolean
}
export type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {
/**
* The initial page parameter to use for the first page fetch.
*/
initialPageParam: PageParam
/**
* This function is required to automatically get the next cursor for infinite queries.
* The result will also be used to determine the value of `hasNextPage`.
*/
getNextPageParam: (
lastPage: DataType,
allPages: Array<DataType>,
lastPageParam: PageParam,
allPageParams: Array<PageParam>,
queryArg: QueryArg,
) => PageParam | undefined | null
/**
* This function can be set to automatically get the previous cursor for infinite queries.
* The result will also be used to determine the value of `hasPreviousPage`.
*/
getPreviousPageParam?: (
firstPage: DataType,
allPages: Array<DataType>,
firstPageParam: PageParam,
allPageParams: Array<PageParam>,
queryArg: QueryArg,
) => PageParam | undefined | null
/**
* If specified, only keep this many pages in cache at once.
* If additional pages are fetched, older pages in the other
* direction will be dropped from the cache.
*/
maxPages?: number
}
export type InfiniteData<DataType, PageParam> = {
pages: Array<DataType>
pageParams: Array<PageParam>
}
// NOTE: DO NOT import and use this for runtime comparisons internally,
// except in the RTKQ React package. Use the string versions just below this.
// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated
// constants like "initialized":
// https://github.com/evanw/esbuild/releases/tag/v0.14.7
// We still have to use this in the React package since we don't publicly export
// the string constants below.
/**
* Strings describing the query state at any given time.
*/
export enum QueryStatus {
uninitialized = 'uninitialized',
pending = 'pending',
fulfilled = 'fulfilled',
rejected = 'rejected',
}
// Use these string constants for runtime comparisons internally
export const STATUS_UNINITIALIZED = QueryStatus.uninitialized
export const STATUS_PENDING = QueryStatus.pending
export const STATUS_FULFILLED = QueryStatus.fulfilled
export const STATUS_REJECTED = QueryStatus.rejected
export type RequestStatusFlags =
| {
status: QueryStatus.uninitialized
isUninitialized: true
isLoading: false
isSuccess: false
isError: false
}
| {
status: QueryStatus.pending
isUninitialized: false
isLoading: true
isSuccess: false
isError: false
}
| {
status: QueryStatus.fulfilled
isUninitialized: false
isLoading: false
isSuccess: true
isError: false
}
| {
status: QueryStatus.rejected
isUninitialized: false
isLoading: false
isSuccess: false
isError: true
}
export function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {
return {
status,
isUninitialized: status === STATUS_UNINITIALIZED,
isLoading: status === STATUS_PENDING,
isSuccess: status === STATUS_FULFILLED,
isError: status === STATUS_REJECTED,
} as any
}
/**
* @public
*/
export type SubscriptionOptions = {
/**
* How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).
*/
pollingInterval?: number
/**
* Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.
*
* If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
skipPollingIfUnfocused?: boolean
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnReconnect?: boolean
/**
* 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.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnFocus?: boolean
}
export type SubscribersInternal = Map<string, SubscriptionOptions>
export type Subscribers = { [requestId: string]: SubscriptionOptions }
export type QueryKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<
any,
any,
any,
any
>
? K
: never
}[keyof Definitions]
export type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<
any,
any,
any,
any,
any
>
? K
: never
}[keyof Definitions]
export type MutationKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends MutationDefinition<
any,
any,
any,
any
>
? K
: never
}[keyof Definitions]
type BaseQuerySubState<
D extends BaseEndpointDefinition<any, any, any, any>,
DataType = ResultTypeFrom<D>,
> = {
/**
* The argument originally passed into the hook or `initiate` action call
*/
originalArgs: QueryArgFromAnyQuery<D>
/**
* A unique ID associated with the request
*/
requestId: string
/**
* The received data from the query
*/
data?: DataType
/**
* The received error if applicable
*/
error?:
| SerializedError
| (D extends QueryDefinition<any, infer BaseQuery, any, any>
? BaseQueryError<BaseQuery>
: never)
/**
* The name of the endpoint associated with the query
*/
endpointName: string
/**
* Time that the latest query started
*/
startedTimeStamp: number
/**
* Time that the latest query was fulfilled
*/
fulfilledTimeStamp?: number
}
export type QuerySubState<
D extends BaseEndpointDefinition<any, any, any, any>,
DataType = ResultTypeFrom<D>,
> = Id<
| ({ status: QueryStatus.fulfilled } & WithRequiredProp<
BaseQuerySubState<D, DataType>,
'data' | 'fulfilledTimeStamp'
> & { error: undefined })
| ({ status: QueryStatus.pending } & BaseQuerySubState<D, DataType>)
| ({ status: QueryStatus.rejected } & WithRequiredProp<
BaseQuerySubState<D, DataType>,
'error'
>)
| {
status: QueryStatus.uninitialized
originalArgs?: undefined
data?: undefined
error?: undefined
requestId?: undefined
endpointName?: string
startedTimeStamp?: undefined
fulfilledTimeStamp?: undefined
}
>
export type InfiniteQueryDirection = 'forward' | 'backward'
export type InfiniteQuerySubState<
D extends BaseEndpointDefinition<any, any, any, any>,
> =
D extends InfiniteQueryDefinition<any, any, any, any, any>
? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {
direction?: InfiniteQueryDirection
}
: never
type BaseMutationSubState<
D extends BaseEndpointDefinition<any, any, any, any>,
> = {
requestId: string
data?: ResultTypeFrom<D>
error?:
| SerializedError
| (D extends MutationDefinition<any, infer BaseQuery, any, any>
? BaseQueryError<BaseQuery>
: never)
endpointName: string
startedTimeStamp: number
fulfilledTimeStamp?: number
}
export type MutationSubState<
D extends BaseEndpointDefinition<any, any, any, any>,
> =
| (({
status: QueryStatus.fulfilled
} & WithRequiredProp<
BaseMutationSubState<D>,
'data' | 'fulfilledTimeStamp'
>) & { error: undefined })
| (({ status: QueryStatus.pending } & BaseMutationSubState<D>) & {
data?: undefined
})
| ({ status: QueryStatus.rejected } & WithRequiredProp<
BaseMutationSubState<D>,
'error'
>)
| {
requestId?: undefined
status: QueryStatus.uninitialized
data?: undefined
error?: undefined
endpointName?: string
startedTimeStamp?: undefined
fulfilledTimeStamp?: undefined
}
export type CombinedState<
D extends EndpointDefinitions,
E extends string,
ReducerPath extends string,
> = {
queries: QueryState<D>
mutations: MutationState<D>
provided: InvalidationState<E>
subscriptions: SubscriptionState
config: ConfigState<ReducerPath>
}
export type InvalidationState<TagTypes extends string> = {
tags: {
[_ in TagTypes]: {
[id: string]: Array<QueryCacheKey>
[id: number]: Array<QueryCacheKey>
}
}
keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>
}
export type QueryState<D extends EndpointDefinitions> = {
[queryCacheKey: string]:
| QuerySubState<D[string]>
| InfiniteQuerySubState<D[string]>
| undefined
}
export type SubscriptionInternalState = Map<string, SubscribersInternal>
export type SubscriptionState = {
[queryCacheKey: string]: Subscribers | undefined
}
export type ConfigState<ReducerPath> = RefetchConfigOptions & {
reducerPath: ReducerPath
online: boolean
focused: boolean
middlewareRegistered: boolean | 'conflict'
} & ModifiableConfigState
export type ModifiableConfigState = {
keepUnusedDataFor: number
invalidationBehavior: 'delayed' | 'immediately'
} & RefetchConfigOptions
export type MutationState<D extends EndpointDefinitions> = {
[requestId: string]: MutationSubState<D[string]> | undefined
}
export type RootState<
Definitions extends EndpointDefinitions,
TagTypes extends string,
ReducerPath extends string,
> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> }

View File

@@ -0,0 +1,581 @@
import type {
AsyncThunkAction,
SafePromise,
SerializedError,
ThunkAction,
UnknownAction,
} from '@reduxjs/toolkit'
import type { Dispatch } from 'redux'
import { asSafePromise } from '../../tsHelpers'
import { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes'
import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import {
ENDPOINT_QUERY,
isQueryDefinition,
type EndpointDefinition,
type EndpointDefinitions,
type InfiniteQueryArgFrom,
type InfiniteQueryDefinition,
type MutationDefinition,
type PageParamFrom,
type QueryArgFrom,
type QueryDefinition,
type ResultTypeFrom,
} from '../endpointDefinitions'
import { filterNullishValues } from '../utils'
import type {
InfiniteData,
InfiniteQueryConfigOptions,
InfiniteQueryDirection,
SubscriptionOptions,
} from './apiState'
import type {
InfiniteQueryResultSelectorResult,
QueryResultSelectorResult,
} from './buildSelectors'
import type {
InfiniteQueryThunk,
InfiniteQueryThunkArg,
MutationThunk,
QueryThunk,
QueryThunkArg,
ThunkApiMetaConfig,
} from './buildThunks'
import type { ApiEndpointQuery } from './module'
import type { InternalMiddlewareState } from './buildMiddleware/types'
export type BuildInitiateApiEndpointQuery<
Definition extends QueryDefinition<any, any, any, any, any>,
> = {
initiate: StartQueryActionCreator<Definition>
}
export type BuildInitiateApiEndpointInfiniteQuery<
Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
> = {
initiate: StartInfiniteQueryActionCreator<Definition>
}
export type BuildInitiateApiEndpointMutation<
Definition extends MutationDefinition<any, any, any, any, any>,
> = {
initiate: StartMutationActionCreator<Definition>
}
export const forceQueryFnSymbol = Symbol('forceQueryFn')
export const isUpsertQuery = (arg: QueryThunkArg) =>
typeof arg[forceQueryFnSymbol] === 'function'
export type StartQueryActionCreatorOptions = {
subscribe?: boolean
forceRefetch?: boolean | number
subscriptionOptions?: SubscriptionOptions
[forceQueryFnSymbol]?: () => QueryReturnValue
}
export type StartInfiniteQueryActionCreatorOptions<
D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = StartQueryActionCreatorOptions & {
direction?: InfiniteQueryDirection
param?: unknown
} & Partial<
Pick<
Partial<
InfiniteQueryConfigOptions<
ResultTypeFrom<D>,
PageParamFrom<D>,
InfiniteQueryArgFrom<D>
>
>,
'initialPageParam'
>
>
type AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (
arg: any,
options?: StartQueryActionCreatorOptions,
) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>
type StartQueryActionCreator<
D extends QueryDefinition<any, any, any, any, any>,
> = (
arg: QueryArgFrom<D>,
options?: StartQueryActionCreatorOptions,
) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>
export type StartInfiniteQueryActionCreator<
D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = (
arg: InfiniteQueryArgFrom<D>,
options?: StartInfiniteQueryActionCreatorOptions<D>,
) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>
type QueryActionCreatorFields = {
requestId: string
subscriptionOptions: SubscriptionOptions | undefined
abort(): void
unsubscribe(): void
updateSubscriptionOptions(options: SubscriptionOptions): void
queryCacheKey: string
}
type AnyActionCreatorResult = SafePromise<any> &
QueryActionCreatorFields & {
arg: any
unwrap(): Promise<any>
refetch(): AnyActionCreatorResult
}
export type QueryActionCreatorResult<
D extends QueryDefinition<any, any, any, any>,
> = SafePromise<QueryResultSelectorResult<D>> &
QueryActionCreatorFields & {
arg: QueryArgFrom<D>
unwrap(): Promise<ResultTypeFrom<D>>
refetch(): QueryActionCreatorResult<D>
}
export type InfiniteQueryActionCreatorResult<
D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = SafePromise<InfiniteQueryResultSelectorResult<D>> &
QueryActionCreatorFields & {
arg: InfiniteQueryArgFrom<D>
unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>
refetch(): InfiniteQueryActionCreatorResult<D>
}
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>,
> = SafePromise<
| {
data: ResultTypeFrom<D>
error?: undefined
}
| {
data?: undefined
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,
infiniteQueryThunk,
mutationThunk,
api,
context,
getInternalState,
}: {
serializeQueryArgs: InternalSerializeQueryArgs
queryThunk: QueryThunk
infiniteQueryThunk: InfiniteQueryThunk<any>
mutationThunk: MutationThunk
api: Api<any, EndpointDefinitions, any, any>
context: ApiContext<EndpointDefinitions>
getInternalState: (dispatch: Dispatch) => InternalMiddlewareState
}) {
const getRunningQueries = (dispatch: Dispatch) =>
getInternalState(dispatch)?.runningQueries
const getRunningMutations = (dispatch: Dispatch) =>
getInternalState(dispatch)?.runningMutations
const {
unsubscribeQueryResult,
removeMutationResult,
updateSubscriptionOptions,
} = api.internalActions
return {
buildInitiateQuery,
buildInitiateInfiniteQuery,
buildInitiateMutation,
getRunningQueryThunk,
getRunningMutationThunk,
getRunningQueriesThunk,
getRunningMutationsThunk,
}
function getRunningQueryThunk(endpointName: string, queryArgs: any) {
return (dispatch: Dispatch) => {
const endpointDefinition = getEndpointDefinition(context, endpointName)
const queryCacheKey = serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName,
})
return getRunningQueries(dispatch)?.get(queryCacheKey) as
| QueryActionCreatorResult<never>
| InfiniteQueryActionCreatorResult<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 getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as
| MutationActionCreatorResult<never>
| undefined
}
}
function getRunningQueriesThunk() {
return (dispatch: Dispatch) =>
filterNullishValues(getRunningQueries(dispatch))
}
function getRunningMutationsThunk() {
return (dispatch: Dispatch) =>
filterNullishValues(getRunningMutations(dispatch))
}
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 buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(
endpointName: string,
endpointDefinition:
| QueryDefinition<any, any, any, any>
| InfiniteQueryDefinition<any, any, any, any, any>,
) {
const queryAction: AnyQueryActionCreator<any> =
(
arg,
{
subscribe = true,
forceRefetch,
subscriptionOptions,
[forceQueryFnSymbol]: forceQueryFn,
...rest
} = {},
) =>
(dispatch, getState) => {
const queryCacheKey = serializeQueryArgs({
queryArgs: arg,
endpointDefinition,
endpointName,
})
let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>
const commonThunkArgs = {
...rest,
type: ENDPOINT_QUERY as 'query',
subscribe,
forceRefetch: forceRefetch,
subscriptionOptions,
endpointName,
originalArgs: arg,
queryCacheKey,
[forceQueryFnSymbol]: forceQueryFn,
}
if (isQueryDefinition(endpointDefinition)) {
thunk = queryThunk(commonThunkArgs)
} else {
const { direction, initialPageParam } = rest as Pick<
InfiniteQueryThunkArg<any>,
'direction' | 'initialPageParam'
>
thunk = infiniteQueryThunk({
...(commonThunkArgs as InfiniteQueryThunkArg<any>),
// Supply these even if undefined. This helps with a field existence
// check over in `buildSlice.ts`
direction,
initialPageParam,
})
}
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 = getRunningQueries(dispatch)?.get(queryCacheKey)
const selectFromState = () => selector(getState())
const statePromise: AnyActionCreatorResult = 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,
)) as SafePromise<any>,
{
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 runningQueries = getRunningQueries(dispatch)!
runningQueries.set(queryCacheKey, statePromise)
statePromise.then(() => {
runningQueries.delete(queryCacheKey)
})
}
return statePromise
}
return queryAction
}
function buildInitiateQuery(
endpointName: string,
endpointDefinition: QueryDefinition<any, any, any, any>,
) {
const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(
endpointName,
endpointDefinition,
)
return queryAction
}
function buildInitiateInfiniteQuery(
endpointName: string,
endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,
) {
const infiniteQueryAction: StartInfiniteQueryActionCreator<any> =
buildInitiateAnyQuery(endpointName, endpointDefinition)
return infiniteQueryAction
}
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 = asSafePromise(
thunkResult.unwrap().then((data) => ({ data })),
(error) => ({ error }),
)
const reset = () => {
dispatch(removeMutationResult({ requestId, fixedCacheKey }))
}
const ret = Object.assign(returnValuePromise, {
arg: thunkResult.arg,
requestId,
abort,
unwrap,
reset,
})
const runningMutations = getRunningMutations(dispatch)!
runningMutations.set(requestId, ret)
ret.then(() => {
runningMutations.delete(requestId)
})
if (fixedCacheKey) {
runningMutations.set(fixedCacheKey, ret)
ret.then(() => {
if (runningMutations.get(fixedCacheKey) === ret) {
runningMutations.delete(fixedCacheKey)
}
})
}
return ret
}
}
}

View File

@@ -0,0 +1,207 @@
import type { InternalHandlerBuilder, SubscriptionSelectors } from './types'
import type { SubscriptionInternalState, SubscriptionState } from '../apiState'
import { produceWithPatches } from '../../utils/immerImports'
import type { Action } from '@reduxjs/toolkit'
import { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'
export const buildBatchedActionsHandler: InternalHandlerBuilder<
[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]
> = ({ api, queryThunk, internalState, mwApi }) => {
const subscriptionsPrefix = `${api.reducerPath}/subscriptions`
let previousSubscriptions: SubscriptionState =
null as unknown as SubscriptionState
let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null
const { updateSubscriptionOptions, unsubscribeQueryResult } =
api.internalActions
// Actually intentionally mutate the subscriptions state used in the middleware
// This is done to speed up perf when loading many components
const actuallyMutateSubscriptions = (
currentSubscriptions: SubscriptionInternalState,
action: Action,
) => {
if (updateSubscriptionOptions.match(action)) {
const { queryCacheKey, requestId, options } = action.payload
const sub = currentSubscriptions.get(queryCacheKey)
if (sub?.has(requestId)) {
sub.set(requestId, options)
}
return true
}
if (unsubscribeQueryResult.match(action)) {
const { queryCacheKey, requestId } = action.payload
const sub = currentSubscriptions.get(queryCacheKey)
if (sub) {
sub.delete(requestId)
}
return true
}
if (api.internalActions.removeQueryResult.match(action)) {
currentSubscriptions.delete(action.payload.queryCacheKey)
return true
}
if (queryThunk.pending.match(action)) {
const {
meta: { arg, requestId },
} = action
const substate = getOrInsertComputed(
currentSubscriptions,
arg.queryCacheKey,
createNewMap,
)
if (arg.subscribe) {
substate.set(
requestId,
arg.subscriptionOptions ?? substate.get(requestId) ?? {},
)
}
return true
}
let mutated = false
if (queryThunk.rejected.match(action)) {
const {
meta: { condition, arg, requestId },
} = action
if (condition && arg.subscribe) {
const substate = getOrInsertComputed(
currentSubscriptions,
arg.queryCacheKey,
createNewMap,
)
substate.set(
requestId,
arg.subscriptionOptions ?? substate.get(requestId) ?? {},
)
mutated = true
}
}
return mutated
}
const getSubscriptions = () => internalState.currentSubscriptions
const getSubscriptionCount = (queryCacheKey: string) => {
const subscriptions = getSubscriptions()
const subscriptionsForQueryArg = subscriptions.get(queryCacheKey)
return subscriptionsForQueryArg?.size ?? 0
}
const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {
const subscriptions = getSubscriptions()
return !!subscriptions?.get(queryCacheKey)?.get(requestId)
}
const subscriptionSelectors: SubscriptionSelectors = {
getSubscriptions,
getSubscriptionCount,
isRequestSubscribed,
}
function serializeSubscriptions(
currentSubscriptions: SubscriptionInternalState,
): SubscriptionState {
// We now use nested Maps for subscriptions, instead of
// plain Records. Stringify this accordingly so we can
// convert it to the shape we need for the store.
return JSON.parse(
JSON.stringify(
Object.fromEntries(
[...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]),
),
),
)
}
return (
action,
mwApi,
): [
actionShouldContinue: boolean,
result: SubscriptionSelectors | boolean,
] => {
if (!previousSubscriptions) {
// Initialize it the first time this handler runs
previousSubscriptions = serializeSubscriptions(
internalState.currentSubscriptions,
)
}
if (api.util.resetApiState.match(action)) {
previousSubscriptions = {}
internalState.currentSubscriptions.clear()
updateSyncTimer = null
return [true, false]
}
// Intercept requests by hooks to see if they're subscribed
// We return the internal state reference so that hooks
// can do their own checks to see if they're still active.
// It's stupid and hacky, but it does cut down on some dispatch calls.
if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
return [false, subscriptionSelectors]
}
// Update subscription data based on this action
const didMutate = actuallyMutateSubscriptions(
internalState.currentSubscriptions,
action,
)
let actionShouldContinue = true
// HACK Sneak the test-only polling state back out
if (
process.env.NODE_ENV === 'test' &&
typeof action.type === 'string' &&
action.type === `${api.reducerPath}/getPolling`
) {
return [false, internalState.currentPolls] as any
}
if (didMutate) {
if (!updateSyncTimer) {
// We only use the subscription state for the Redux DevTools at this point,
// as the real data is kept here in the middleware.
// Given that, we can throttle synchronizing this state significantly to
// save on overall perf.
// In 1.9, it was updated in a microtask, but now we do it at most every 500ms.
updateSyncTimer = setTimeout(() => {
// Deep clone the current subscription data
const newSubscriptions: SubscriptionState = serializeSubscriptions(
internalState.currentSubscriptions,
)
// Figure out a smaller diff between original and current
const [, patches] = produceWithPatches(
previousSubscriptions,
() => newSubscriptions,
)
// Sync the store state for visibility
mwApi.next(api.internalActions.subscriptionsUpdated(patches))
// Save the cloned state for later reference
previousSubscriptions = newSubscriptions
updateSyncTimer = null
}, 500)
}
const isSubscriptionSliceAction =
typeof action.type == 'string' &&
!!action.type.startsWith(subscriptionsPrefix)
const isAdditionalSubscriptionAction =
queryThunk.rejected.match(action) &&
action.meta.condition &&
!!action.meta.arg.subscribe
actionShouldContinue =
!isSubscriptionSliceAction && !isAdditionalSubscriptionAction
}
return [actionShouldContinue, false]
}
}

View File

@@ -0,0 +1,204 @@
import { getEndpointDefinition } from '@internal/query/apiTypes'
import type { QueryDefinition } from '../../endpointDefinitions'
import type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState'
import { isAnyOf } from '../rtkImports'
import type {
ApiMiddlewareInternalHandler,
InternalHandlerBuilder,
QueryStateMeta,
SubMiddlewareApi,
TimeoutId,
} from './types'
export type ReferenceCacheCollection = never
/**
* @example
* ```ts
* // codeblock-meta title="keepUnusedDataFor example"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* // highlight-start
* keepUnusedDataFor: 5
* // highlight-end
* })
* })
* })
* ```
*/
export type CacheCollectionQueryExtraOptions = {
/**
* Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(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.
*/
keepUnusedDataFor?: number
}
// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store
// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,
// it wraps and ends up executing immediately.
// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.
export const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647
export const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1
export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
reducerPath,
api,
queryThunk,
context,
internalState,
selectors: { selectQueryEntry, selectConfig },
getRunningQueryThunk,
mwApi,
}) => {
const { removeQueryResult, unsubscribeQueryResult, cacheEntriesUpserted } =
api.internalActions
const canTriggerUnsubscribe = isAnyOf(
unsubscribeQueryResult.match,
queryThunk.fulfilled,
queryThunk.rejected,
cacheEntriesUpserted.match,
)
function anySubscriptionsRemainingForKey(queryCacheKey: string) {
const subscriptions = internalState.currentSubscriptions.get(queryCacheKey)
if (!subscriptions) {
return false
}
const hasSubscriptions = subscriptions.size > 0
return hasSubscriptions
}
const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}
function abortAllPromises<T extends { abort?: () => void }>(
promiseMap: Map<string, T | undefined>,
): void {
for (const promise of promiseMap.values()) {
promise?.abort?.()
}
}
const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
const state = mwApi.getState()
const config = selectConfig(state)
if (canTriggerUnsubscribe(action)) {
let queryCacheKeys: QueryCacheKey[]
if (cacheEntriesUpserted.match(action)) {
queryCacheKeys = action.payload.map(
(entry) => entry.queryDescription.queryCacheKey,
)
} else {
const { queryCacheKey } = unsubscribeQueryResult.match(action)
? action.payload
: action.meta.arg
queryCacheKeys = [queryCacheKey]
}
handleUnsubscribeMany(queryCacheKeys, mwApi, config)
}
if (api.util.resetApiState.match(action)) {
for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
if (timeout) clearTimeout(timeout)
delete currentRemovalTimeouts[key]
}
abortAllPromises(internalState.runningQueries)
abortAllPromises(internalState.runningMutations)
}
if (context.hasRehydrationInfo(action)) {
const { queries } = context.extractRehydrationInfo(action)!
// Gotcha:
// If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`
// will be used instead of the endpoint-specific one.
handleUnsubscribeMany(
Object.keys(queries) as QueryCacheKey[],
mwApi,
config,
)
}
}
function handleUnsubscribeMany(
cacheKeys: QueryCacheKey[],
api: SubMiddlewareApi,
config: ConfigState<string>,
) {
const state = api.getState()
for (const queryCacheKey of cacheKeys) {
const entry = selectQueryEntry(state, queryCacheKey)
if (entry?.endpointName) {
handleUnsubscribe(queryCacheKey, entry.endpointName, api, config)
}
}
}
function handleUnsubscribe(
queryCacheKey: QueryCacheKey,
endpointName: string,
api: SubMiddlewareApi,
config: ConfigState<string>,
) {
const endpointDefinition = getEndpointDefinition(
context,
endpointName,
) as QueryDefinition<any, any, any, any>
const keepUnusedDataFor =
endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor
if (keepUnusedDataFor === Infinity) {
// Hey, user said keep this forever!
return
}
// Prevent `setTimeout` timers from overflowing a 32-bit internal int, by
// clamping the max value to be at most 1000ms less than the 32-bit max.
// Look, a 24.8-day keepalive ought to be enough for anybody, right? :)
// Also avoid negative values too.
const finalKeepUnusedDataFor = Math.max(
0,
Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS),
)
if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
const currentTimeout = currentRemovalTimeouts[queryCacheKey]
if (currentTimeout) {
clearTimeout(currentTimeout)
}
currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
// Try to abort any running query for this cache key
const entry = selectQueryEntry(api.getState(), queryCacheKey)
if (entry?.endpointName) {
const runningQuery = api.dispatch(
getRunningQueryThunk(entry.endpointName, entry.originalArgs),
)
runningQuery?.abort()
}
api.dispatch(removeQueryResult({ queryCacheKey }))
}
delete currentRemovalTimeouts![queryCacheKey]
}, finalKeepUnusedDataFor * 1000)
}
}
return handler
}

View File

@@ -0,0 +1,379 @@
import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
import type {
BaseQueryFn,
BaseQueryMeta,
BaseQueryResult,
} from '../../baseQueryTypes'
import type {
BaseEndpointDefinition,
DefinitionType,
} from '../../endpointDefinitions'
import { isAnyQueryDefinition } from '../../endpointDefinitions'
import type { QueryCacheKey, RootState } from '../apiState'
import type {
MutationResultSelectorResult,
QueryResultSelectorResult,
} from '../buildSelectors'
import { getMutationCacheKey } from '../buildSlice'
import type { PatchCollection, Recipe } from '../buildThunks'
import { isAsyncThunkAction, isFulfilled } from '../rtkImports'
import type {
ApiMiddlewareInternalHandler,
InternalHandlerBuilder,
PromiseWithKnownReason,
SubMiddlewareApi,
} from './types'
import { getEndpointDefinition } from '@internal/query/apiTypes'
export type ReferenceCacheLifecycle = never
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,
BaseQueryResult<BaseQuery>
>
>
/**
* Updates the current cache entry value.
* For documentation see `api.util.updateQueryData`.
*/
updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection
}
export type MutationBaseLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> = LifecycleApi<ReducerPath> & {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): MutationResultSelectorResult<
{ type: DefinitionType.mutation } & BaseEndpointDefinition<
QueryArg,
BaseQuery,
ResultType,
BaseQueryResult<BaseQuery>
>
>
}
type 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
}
type 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 type MutationCacheLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &
CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>
export type CacheLifecycleQueryExtraOptions<
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> = {
onCacheEntryAdded?(
arg: QueryArg,
api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
): Promise<void> | void
}
export type CacheLifecycleInfiniteQueryExtraOptions<
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> = CacheLifecycleQueryExtraOptions<
ResultType,
QueryArg,
BaseQuery,
ReducerPath
>
export type CacheLifecycleMutationExtraOptions<
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,
selectors: { selectQueryEntry, selectApiState },
}) => {
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 { removeQueryResult, removeMutationResult, cacheEntriesUpserted } =
api.internalActions
function resolveLifecycleEntry(
cacheKey: string,
data: unknown,
meta: unknown,
) {
const lifecycle = lifecycleMap[cacheKey]
if (lifecycle?.valueResolved) {
lifecycle.valueResolved({
data,
meta,
})
delete lifecycle.valueResolved
}
}
function removeLifecycleEntry(cacheKey: string) {
const lifecycle = lifecycleMap[cacheKey]
if (lifecycle) {
delete lifecycleMap[cacheKey]
lifecycle.cacheEntryRemoved()
}
}
function getActionMetaFields(
action:
| ReturnType<typeof queryThunk.pending>
| ReturnType<typeof mutationThunk.pending>,
) {
const { arg, requestId } = action.meta
const { endpointName, originalArgs } = arg
return [endpointName, originalArgs, requestId] as const
}
const handler: ApiMiddlewareInternalHandler = (
action,
mwApi,
stateBefore,
) => {
const cacheKey = getCacheKey(action) as QueryCacheKey
function checkForNewCacheKey(
endpointName: string,
cacheKey: QueryCacheKey,
requestId: string,
originalArgs: unknown,
) {
const oldEntry = selectQueryEntry(stateBefore, cacheKey)
const newEntry = selectQueryEntry(mwApi.getState(), cacheKey)
if (!oldEntry && newEntry) {
handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
}
}
if (queryThunk.pending.match(action)) {
const [endpointName, originalArgs, requestId] =
getActionMetaFields(action)
checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs)
} else if (cacheEntriesUpserted.match(action)) {
for (const { queryDescription, value } of action.payload) {
const { endpointName, originalArgs, queryCacheKey } = queryDescription
checkForNewCacheKey(
endpointName,
queryCacheKey,
action.meta.requestId,
originalArgs,
)
resolveLifecycleEntry(queryCacheKey, value, {})
}
} else if (mutationThunk.pending.match(action)) {
const state = mwApi.getState()[reducerPath].mutations[cacheKey]
if (state) {
const [endpointName, originalArgs, requestId] =
getActionMetaFields(action)
handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
}
} else if (isFulfilledThunk(action)) {
resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta)
} else if (
removeQueryResult.match(action) ||
removeMutationResult.match(action)
) {
removeLifecycleEntry(cacheKey)
} else if (api.util.resetApiState.match(action)) {
for (const cacheKey of Object.keys(lifecycleMap)) {
removeLifecycleEntry(cacheKey)
}
}
}
function getCacheKey(action: any) {
if (isQueryThunk(action)) return action.meta.arg.queryCacheKey
if (isMutationThunk(action)) {
return action.meta.arg.fixedCacheKey ?? action.meta.requestId
}
if (removeQueryResult.match(action)) return action.payload.queryCacheKey
if (removeMutationResult.match(action))
return getMutationCacheKey(action.payload)
return ''
}
function handleNewKey(
endpointName: string,
originalArgs: any,
queryCacheKey: string,
mwApi: SubMiddlewareApi,
requestId: string,
) {
const endpointDefinition = getEndpointDefinition(context, endpointName)
const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded
if (!onCacheEntryAdded) return
const 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(
isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey,
)
const extra = mwApi.dispatch((_, __, extra) => extra)
const lifecycleApi = {
...mwApi,
getCacheEntry: () => selector(mwApi.getState()),
requestId,
extra,
updateCachedData: (isAnyQueryDefinition(endpointDefinition)
? (updateRecipe: Recipe<any>) =>
mwApi.dispatch(
api.util.updateQueryData(
endpointName as never,
originalArgs as never,
updateRecipe,
),
)
: undefined) as any,
cacheDataLoaded,
cacheEntryRemoved,
}
const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any)
// 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
}

View File

@@ -0,0 +1,34 @@
import type { InternalHandlerBuilder } from './types'
export const buildDevCheckHandler: InternalHandlerBuilder = ({
api,
context: { apiUid },
reducerPath,
}) => {
return (action, mwApi) => {
if (api.util.resetApiState.match(action)) {
// dispatch after api reset
mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))
}
if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
if (
api.internalActions.middlewareRegistered.match(action) &&
action.payload === apiUid &&
mwApi.getState()[reducerPath]?.config?.middlewareRegistered ===
'conflict'
) {
console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
You can only have one api per reducer path, this will lead to crashes in various situations!${
reducerPath === 'api'
? `
If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`
: ''
}`)
}
}
}
}

View File

@@ -0,0 +1,162 @@
import type {
Action,
Middleware,
ThunkDispatch,
UnknownAction,
} from '@reduxjs/toolkit'
import type {
EndpointDefinitions,
FullTagDescription,
} from '../../endpointDefinitions'
import type { QueryStatus, QuerySubState, RootState } from '../apiState'
import type { QueryThunkArg } from '../buildThunks'
import { createAction, isAction } from '../rtkImports'
import { buildBatchedActionsHandler } from './batchActions'
import { buildCacheCollectionHandler } from './cacheCollection'
import { buildCacheLifecycleHandler } from './cacheLifecycle'
import { buildDevCheckHandler } from './devMiddleware'
import { buildInvalidationByTagsHandler } from './invalidationByTags'
import { buildPollingHandler } from './polling'
import { buildQueryLifecycleHandler } from './queryLifecycle'
import type {
BuildMiddlewareInput,
InternalHandlerBuilder,
InternalMiddlewareState,
} from './types'
import { buildWindowEventHandler } from './windowEventHandling'
import type { ApiEndpointQuery } from '../module'
export type { ReferenceCacheCollection } from './cacheCollection'
export type {
MutationCacheLifecycleApi,
QueryCacheLifecycleApi,
ReferenceCacheLifecycle,
} from './cacheLifecycle'
export type {
MutationLifecycleApi,
QueryLifecycleApi,
ReferenceQueryLifecycle,
TypedMutationOnQueryStarted,
TypedQueryOnQueryStarted,
} from './queryLifecycle'
export type { SubscriptionSelectors } from './types'
export function buildMiddleware<
Definitions extends EndpointDefinitions,
ReducerPath extends string,
TagTypes extends string,
>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {
const { reducerPath, queryThunk, api, context, getInternalState } = input
const { apiUid } = context
const actions = {
invalidateTags: createAction<
Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>
>(`${reducerPath}/invalidateTags`),
}
const isThisApiSliceAction = (action: Action) =>
action.type.startsWith(`${reducerPath}/`)
const handlerBuilders: InternalHandlerBuilder[] = [
buildDevCheckHandler,
buildCacheCollectionHandler,
buildInvalidationByTagsHandler,
buildPollingHandler,
buildCacheLifecycleHandler,
buildQueryLifecycleHandler,
]
const middleware: Middleware<
{},
RootState<Definitions, string, ReducerPath>,
ThunkDispatch<any, any, UnknownAction>
> = (mwApi) => {
let initialized = false
const internalState = getInternalState(mwApi.dispatch)
const builderArgs = {
...(input as any as BuildMiddlewareInput<
EndpointDefinitions,
string,
string
>),
internalState,
refetchQuery,
isThisApiSliceAction,
mwApi,
}
const handlers = handlerBuilders.map((build) => build(builderArgs))
const batchedActionsHandler = buildBatchedActionsHandler(builderArgs)
const windowEventsHandler = buildWindowEventHandler(builderArgs)
return (next) => {
return (action) => {
if (!isAction(action)) {
return next(action)
}
if (!initialized) {
initialized = true
// dispatch before any other action
mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))
}
const mwApiWithNext = { ...mwApi, next }
const stateBefore = mwApi.getState()
const [actionShouldContinue, internalProbeResult] =
batchedActionsHandler(action, mwApiWithNext, stateBefore)
let res: any
if (actionShouldContinue) {
res = next(action)
} else {
res = internalProbeResult
}
if (!!mwApi.getState()[reducerPath]) {
// Only run these checks if the middleware is registered okay
// This looks for actions that aren't specific to the API slice
windowEventsHandler(action, mwApiWithNext, stateBefore)
if (
isThisApiSliceAction(action) ||
context.hasRehydrationInfo(action)
) {
// Only run these additional checks if the actions are part of the API slice,
// or the action has hydration-related data
for (const handler of handlers) {
handler(action, mwApiWithNext, stateBefore)
}
}
}
return res
}
}
}
return { middleware, actions }
function refetchQuery(
querySubState: Exclude<
QuerySubState<any>,
{ status: QueryStatus.uninitialized }
>,
) {
return (
input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<
any,
any
>
).initiate(querySubState.originalArgs as any, {
subscribe: false,
forceRefetch: true,
})
}
}

View File

@@ -0,0 +1,139 @@
import {
isAnyOf,
isFulfilled,
isRejected,
isRejectedWithValue,
} from '../rtkImports'
import type {
EndpointDefinitions,
FullTagDescription,
} from '../../endpointDefinitions'
import { calculateProvidedBy } from '../../endpointDefinitions'
import type { CombinedState, QueryCacheKey } from '../apiState'
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
import { calculateProvidedByThunk } from '../buildThunks'
import type {
SubMiddlewareApi,
InternalHandlerBuilder,
ApiMiddlewareInternalHandler,
} from './types'
import { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'
export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({
reducerPath,
context,
context: { endpointDefinitions },
mutationThunk,
queryThunk,
api,
assertTagType,
refetchQuery,
internalState,
}) => {
const { removeQueryResult } = api.internalActions
const isThunkActionWithTags = isAnyOf(
isFulfilled(mutationThunk),
isRejectedWithValue(mutationThunk),
)
const isQueryEnd = isAnyOf(
isFulfilled(queryThunk, mutationThunk),
isRejected(queryThunk, mutationThunk),
)
let pendingTagInvalidations: FullTagDescription<string>[] = []
// Track via counter so we can avoid iterating over state every time
let pendingRequestCount = 0
const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
if (
queryThunk.pending.match(action) ||
mutationThunk.pending.match(action)
) {
pendingRequestCount++
}
if (isQueryEnd(action)) {
pendingRequestCount = Math.max(0, pendingRequestCount - 1)
}
if (isThunkActionWithTags(action)) {
invalidateTags(
calculateProvidedByThunk(
action,
'invalidatesTags',
endpointDefinitions,
assertTagType,
),
mwApi,
)
} else if (isQueryEnd(action)) {
invalidateTags([], mwApi)
} else if (api.util.invalidateTags.match(action)) {
invalidateTags(
calculateProvidedBy(
action.payload,
undefined,
undefined,
undefined,
undefined,
assertTagType,
),
mwApi,
)
}
}
function hasPendingRequests() {
return pendingRequestCount > 0
}
function invalidateTags(
newTags: readonly FullTagDescription<string>[],
mwApi: SubMiddlewareApi,
) {
const rootState = mwApi.getState()
const state = rootState[reducerPath]
pendingTagInvalidations.push(...newTags)
if (
state.config.invalidationBehavior === 'delayed' &&
hasPendingRequests()
) {
return
}
const tags = pendingTagInvalidations
pendingTagInvalidations = []
if (tags.length === 0) return
const toInvalidate = api.util.selectInvalidatedBy(rootState, tags)
context.batch(() => {
const valuesArray = Array.from(toInvalidate.values())
for (const { queryCacheKey } of valuesArray) {
const querySubState = state.queries[queryCacheKey]
const subscriptionSubState = getOrInsertComputed(
internalState.currentSubscriptions,
queryCacheKey,
createNewMap,
)
if (querySubState) {
if (subscriptionSubState.size === 0) {
mwApi.dispatch(
removeQueryResult({
queryCacheKey: queryCacheKey as QueryCacheKey,
}),
)
} else if (querySubState.status !== STATUS_UNINITIALIZED) {
mwApi.dispatch(refetchQuery(querySubState))
}
}
}
})
}
return handler
}

View File

@@ -0,0 +1,187 @@
import type {
QueryCacheKey,
QuerySubstateIdentifier,
Subscribers,
SubscribersInternal,
} from '../apiState'
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
import type {
QueryStateMeta,
SubMiddlewareApi,
TimeoutId,
InternalHandlerBuilder,
ApiMiddlewareInternalHandler,
InternalMiddlewareState,
} from './types'
export const buildPollingHandler: InternalHandlerBuilder = ({
reducerPath,
queryThunk,
api,
refetchQuery,
internalState,
}) => {
const { currentPolls, currentSubscriptions } = internalState
// Batching state for polling updates
const pendingPollingUpdates = new Set<string>()
let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null
const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
if (
api.internalActions.updateSubscriptionOptions.match(action) ||
api.internalActions.unsubscribeQueryResult.match(action)
) {
schedulePollingUpdate(action.payload.queryCacheKey, mwApi)
}
if (
queryThunk.pending.match(action) ||
(queryThunk.rejected.match(action) && action.meta.condition)
) {
schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi)
}
if (
queryThunk.fulfilled.match(action) ||
(queryThunk.rejected.match(action) && !action.meta.condition)
) {
startNextPoll(action.meta.arg, mwApi)
}
if (api.util.resetApiState.match(action)) {
clearPolls()
// Clear any pending updates
if (pollingUpdateTimer) {
clearTimeout(pollingUpdateTimer)
pollingUpdateTimer = null
}
pendingPollingUpdates.clear()
}
}
function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {
pendingPollingUpdates.add(queryCacheKey)
if (!pollingUpdateTimer) {
pollingUpdateTimer = setTimeout(() => {
// Process all pending updates in a single batch
for (const key of pendingPollingUpdates) {
updatePollingInterval({ queryCacheKey: key as any }, api)
}
pendingPollingUpdates.clear()
pollingUpdateTimer = null
}, 0)
}
}
function startNextPoll(
{ queryCacheKey }: QuerySubstateIdentifier,
api: SubMiddlewareApi,
) {
const state = api.getState()[reducerPath]
const querySubState = state.queries[queryCacheKey]
const subscriptions = currentSubscriptions.get(queryCacheKey)
if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return
const { lowestPollingInterval, skipPollingIfUnfocused } =
findLowestPollingInterval(subscriptions)
if (!Number.isFinite(lowestPollingInterval)) return
const currentPoll = currentPolls.get(queryCacheKey)
if (currentPoll?.timeout) {
clearTimeout(currentPoll.timeout)
currentPoll.timeout = undefined
}
const nextPollTimestamp = Date.now() + lowestPollingInterval
currentPolls.set(queryCacheKey, {
nextPollTimestamp,
pollingInterval: lowestPollingInterval,
timeout: setTimeout(() => {
if (state.config.focused || !skipPollingIfUnfocused) {
api.dispatch(refetchQuery(querySubState))
}
startNextPoll({ queryCacheKey }, api)
}, lowestPollingInterval),
})
}
function updatePollingInterval(
{ queryCacheKey }: QuerySubstateIdentifier,
api: SubMiddlewareApi,
) {
const state = api.getState()[reducerPath]
const querySubState = state.queries[queryCacheKey]
const subscriptions = currentSubscriptions.get(queryCacheKey)
if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
return
}
const { lowestPollingInterval } = findLowestPollingInterval(subscriptions)
// HACK add extra data to track how many times this has been called in tests
// yes we're mutating a nonexistent field on a Map here
if (process.env.NODE_ENV === 'test') {
const updateCounters = ((currentPolls as any).pollUpdateCounters ??= {})
updateCounters[queryCacheKey] ??= 0
updateCounters[queryCacheKey]++
}
if (!Number.isFinite(lowestPollingInterval)) {
cleanupPollForKey(queryCacheKey)
return
}
const currentPoll = currentPolls.get(queryCacheKey)
const nextPollTimestamp = Date.now() + lowestPollingInterval
if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
startNextPoll({ queryCacheKey }, api)
}
}
function cleanupPollForKey(key: string) {
const existingPoll = currentPolls.get(key)
if (existingPoll?.timeout) {
clearTimeout(existingPoll.timeout)
}
currentPolls.delete(key)
}
function clearPolls() {
for (const key of currentPolls.keys()) {
cleanupPollForKey(key)
}
}
function findLowestPollingInterval(
subscribers: SubscribersInternal = new Map(),
) {
let skipPollingIfUnfocused: boolean | undefined = false
let lowestPollingInterval = Number.POSITIVE_INFINITY
for (const entry of subscribers.values()) {
if (!!entry.pollingInterval) {
lowestPollingInterval = Math.min(
entry.pollingInterval!,
lowestPollingInterval,
)
skipPollingIfUnfocused =
entry.skipPollingIfUnfocused || skipPollingIfUnfocused
}
}
return {
lowestPollingInterval,
skipPollingIfUnfocused,
}
}
return handler
}

View File

@@ -0,0 +1,505 @@
import { getEndpointDefinition } from '@internal/query/apiTypes'
import type {
BaseQueryError,
BaseQueryFn,
BaseQueryMeta,
} from '../../baseQueryTypes'
import { isAnyQueryDefinition } from '../../endpointDefinitions'
import type { Recipe } from '../buildThunks'
import { isFulfilled, isPending, isRejected } from '../rtkImports'
import type {
MutationBaseLifecycleApi,
QueryBaseLifecycleApi,
} from './cacheLifecycle'
import type {
ApiMiddlewareInternalHandler,
InternalHandlerBuilder,
PromiseConstructorWithKnownReason,
PromiseWithKnownReason,
} from './types'
export type ReferenceQueryLifecycle = never
type QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {
/**
* Promise that will resolve with the (transformed) query result.
*
* If the query fails, this promise will reject with the error.
*
* This allows you to `await` for the query to finish.
*
* If you don't interact with this promise, it will not throw.
*/
queryFulfilled: PromiseWithKnownReason<
{
/**
* The (transformed) query result.
*/
data: ResultType
/**
* The `meta` returned by the `baseQuery`
*/
meta: BaseQueryMeta<BaseQuery>
},
QueryFulfilledRejectionReason<BaseQuery>
>
}
type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> =
| {
error: BaseQueryError<BaseQuery>
/**
* If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.
*/
isUnhandledError: false
/**
* The `meta` returned by the `baseQuery`
*/
meta: BaseQueryMeta<BaseQuery>
}
| {
error: unknown
meta?: undefined
/**
* If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.
* There can not be made any assumption about the shape of `error`.
*/
isUnhandledError: true
}
export type QueryLifecycleQueryExtraOptions<
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> = {
/**
* A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
*
* Can be used to perform side-effects throughout the lifecycle of the query.
*
* @example
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
* import { messageCreated } from './notificationsSlice
* export interface Post {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({
* baseUrl: '/',
* }),
* endpoints: (build) => ({
* getPost: build.query<Post, number>({
* query: (id) => `post/${id}`,
* async onQueryStarted(id, { dispatch, queryFulfilled }) {
* // `onStart` side-effect
* dispatch(messageCreated('Fetching posts...'))
* try {
* const { data } = await queryFulfilled
* // `onSuccess` side-effect
* dispatch(messageCreated('Posts received!'))
* } catch (err) {
* // `onError` side-effect
* dispatch(messageCreated('Error fetching posts!'))
* }
* }
* }),
* }),
* })
* ```
*/
onQueryStarted?(
queryArgument: QueryArg,
queryLifeCycleApi: QueryLifecycleApi<
QueryArg,
BaseQuery,
ResultType,
ReducerPath
>,
): Promise<void> | void
}
export type QueryLifecycleInfiniteQueryExtraOptions<
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> = QueryLifecycleQueryExtraOptions<
ResultType,
QueryArg,
BaseQuery,
ReducerPath
>
export type QueryLifecycleMutationExtraOptions<
ResultType,
QueryArg,
BaseQuery extends BaseQueryFn,
ReducerPath extends string = string,
> = {
/**
* A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
*
* Can be used for `optimistic updates`.
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
* export interface Post {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({
* baseUrl: '/',
* }),
* tagTypes: ['Post'],
* endpoints: (build) => ({
* getPost: build.query<Post, number>({
* query: (id) => `post/${id}`,
* providesTags: ['Post'],
* }),
* updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
* query: ({ id, ...patch }) => ({
* url: `post/${id}`,
* method: 'PATCH',
* body: patch,
* }),
* invalidatesTags: ['Post'],
* async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
* const patchResult = dispatch(
* api.util.updateQueryData('getPost', id, (draft) => {
* Object.assign(draft, patch)
* })
* )
* try {
* await queryFulfilled
* } catch {
* patchResult.undo()
* }
* },
* }),
* }),
* })
* ```
*/
onQueryStarted?(
queryArgument: QueryArg,
mutationLifeCycleApi: MutationLifecycleApi<
QueryArg,
BaseQuery,
ResultType,
ReducerPath
>,
): Promise<void> | void
}
export interface QueryLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
QueryLifecyclePromises<ResultType, BaseQuery> {}
export type MutationLifecycleApi<
QueryArg,
BaseQuery extends BaseQueryFn,
ResultType,
ReducerPath extends string = string,
> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &
QueryLifecyclePromises<ResultType, BaseQuery>
/**
* Provides a way to define a strongly-typed version of
* {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}
* for a specific query.
*
* @example
* <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
*
* ```ts
* import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* type Post = {
* id: number
* title: string
* userId: number
* }
*
* type PostsApiResponse = {
* posts: Post[]
* total: number
* skip: number
* limit: number
* }
*
* type QueryArgument = number | undefined
*
* type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
*
* const baseApiSlice = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
* reducerPath: 'postsApi',
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsApiResponse, void>({
* query: () => `/posts`,
* }),
*
* getPostById: build.query<Post, QueryArgument>({
* query: (postId) => `/posts/${postId}`,
* }),
* }),
* })
*
* const updatePostOnFulfilled: TypedQueryOnQueryStarted<
* PostsApiResponse,
* QueryArgument,
* BaseQueryFunction,
* 'postsApi'
* > = async (queryArgument, { dispatch, queryFulfilled }) => {
* const result = await queryFulfilled
*
* const { posts } = result.data
*
* // Pre-fill the individual post entries with the results
* // from the list endpoint query
* dispatch(
* baseApiSlice.util.upsertQueryEntries(
* posts.map((post) => ({
* endpointName: 'getPostById',
* arg: post.id,
* value: post,
* })),
* ),
* )
* }
*
* export const extendedApiSlice = baseApiSlice.injectEndpoints({
* endpoints: (build) => ({
* getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({
* query: (userId) => `/posts/user/${userId}`,
*
* onQueryStarted: updatePostOnFulfilled,
* }),
* }),
* })
* ```
*
* @template ResultType - The type of the result `data` returned by the query.
* @template QueryArgumentType - The type of the argument passed into the query.
* @template BaseQueryFunctionType - The type of the base query function being used.
* @template ReducerPath - The type representing the `reducerPath` for the API slice.
*
* @since 2.4.0
* @public
*/
export type TypedQueryOnQueryStarted<
ResultType,
QueryArgumentType,
BaseQueryFunctionType extends BaseQueryFn,
ReducerPath extends string = string,
> = QueryLifecycleQueryExtraOptions<
ResultType,
QueryArgumentType,
BaseQueryFunctionType,
ReducerPath
>['onQueryStarted']
/**
* Provides a way to define a strongly-typed version of
* {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}
* for a specific mutation.
*
* @example
* <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
*
* ```ts
* import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* type Post = {
* id: number
* title: string
* userId: number
* }
*
* type PostsApiResponse = {
* posts: Post[]
* total: number
* skip: number
* limit: number
* }
*
* type QueryArgument = Pick<Post, 'id'> & Partial<Post>
*
* type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
*
* const baseApiSlice = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
* reducerPath: 'postsApi',
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsApiResponse, void>({
* query: () => `/posts`,
* }),
*
* getPostById: build.query<Post, number>({
* query: (postId) => `/posts/${postId}`,
* }),
* }),
* })
*
* const updatePostOnFulfilled: TypedMutationOnQueryStarted<
* Post,
* QueryArgument,
* BaseQueryFunction,
* 'postsApi'
* > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {
* const patchCollection = dispatch(
* baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {
* Object.assign(draftPost, patch)
* }),
* )
*
* try {
* await queryFulfilled
* } catch {
* patchCollection.undo()
* }
* }
*
* export const extendedApiSlice = baseApiSlice.injectEndpoints({
* endpoints: (build) => ({
* addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({
* query: (body) => ({
* url: `posts/add`,
* method: 'POST',
* body,
* }),
*
* onQueryStarted: updatePostOnFulfilled,
* }),
*
* updatePost: build.mutation<Post, QueryArgument>({
* query: ({ id, ...patch }) => ({
* url: `post/${id}`,
* method: 'PATCH',
* body: patch,
* }),
*
* onQueryStarted: updatePostOnFulfilled,
* }),
* }),
* })
* ```
*
* @template ResultType - The type of the result `data` returned by the query.
* @template QueryArgumentType - The type of the argument passed into the query.
* @template BaseQueryFunctionType - The type of the base query function being used.
* @template ReducerPath - The type representing the `reducerPath` for the API slice.
*
* @since 2.4.0
* @public
*/
export type TypedMutationOnQueryStarted<
ResultType,
QueryArgumentType,
BaseQueryFunctionType extends BaseQueryFn,
ReducerPath extends string = string,
> = QueryLifecycleMutationExtraOptions<
ResultType,
QueryArgumentType,
BaseQueryFunctionType,
ReducerPath
>['onQueryStarted']
export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({
api,
context,
queryThunk,
mutationThunk,
}) => {
const isPendingThunk = isPending(queryThunk, mutationThunk)
const isRejectedThunk = isRejected(queryThunk, mutationThunk)
const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)
type CacheLifecycle = {
resolve(value: { data: unknown; meta: unknown }): unknown
reject(value: QueryFulfilledRejectionReason<any>): unknown
}
const lifecycleMap: Record<string, CacheLifecycle> = {}
const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
if (isPendingThunk(action)) {
const {
requestId,
arg: { endpointName, originalArgs },
} = action.meta
const endpointDefinition = getEndpointDefinition(context, endpointName)
const onQueryStarted = endpointDefinition?.onQueryStarted
if (onQueryStarted) {
const lifecycle = {} as CacheLifecycle
const queryFulfilled =
new (Promise as PromiseConstructorWithKnownReason)<
{ data: unknown; meta: unknown },
QueryFulfilledRejectionReason<any>
>((resolve, reject) => {
lifecycle.resolve = resolve
lifecycle.reject = reject
})
// 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
queryFulfilled.catch(() => {})
lifecycleMap[requestId] = lifecycle
const selector = (api.endpoints[endpointName] as any).select(
isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId,
)
const extra = mwApi.dispatch((_, __, extra) => extra)
const lifecycleApi = {
...mwApi,
getCacheEntry: () => selector(mwApi.getState()),
requestId,
extra,
updateCachedData: (isAnyQueryDefinition(endpointDefinition)
? (updateRecipe: Recipe<any>) =>
mwApi.dispatch(
api.util.updateQueryData(
endpointName as never,
originalArgs as never,
updateRecipe,
),
)
: undefined) as any,
queryFulfilled,
}
onQueryStarted(originalArgs, lifecycleApi as any)
}
} else if (isFullfilledThunk(action)) {
const { requestId, baseQueryMeta } = action.meta
lifecycleMap[requestId]?.resolve({
data: action.payload,
meta: baseQueryMeta,
})
delete lifecycleMap[requestId]
} else if (isRejectedThunk(action)) {
const { requestId, rejectedWithValue, baseQueryMeta } = action.meta
lifecycleMap[requestId]?.reject({
error: action.payload ?? action.error,
isUnhandledError: !rejectedWithValue,
meta: baseQueryMeta as any,
})
delete lifecycleMap[requestId]
}
}
return handler
}

View File

@@ -0,0 +1,173 @@
import type {
Action,
AsyncThunkAction,
Dispatch,
Middleware,
MiddlewareAPI,
ThunkAction,
ThunkDispatch,
UnknownAction,
} from '@reduxjs/toolkit'
import type { Api, ApiContext } from '../../apiTypes'
import type {
AssertTagTypes,
EndpointDefinitions,
} from '../../endpointDefinitions'
import type {
QueryStatus,
QuerySubState,
RootState,
SubscriptionInternalState,
SubscriptionState,
} from '../apiState'
import type {
InfiniteQueryThunk,
MutationThunk,
QueryThunk,
QueryThunkArg,
ThunkResult,
} from '../buildThunks'
import type {
InfiniteQueryActionCreatorResult,
MutationActionCreatorResult,
QueryActionCreatorResult,
} from '../buildInitiate'
import type { AllSelectors } from '../buildSelectors'
export type QueryStateMeta<T> = Record<string, undefined | T>
export type TimeoutId = ReturnType<typeof setTimeout>
type QueryPollState = {
nextPollTimestamp: number
timeout?: TimeoutId
pollingInterval: number
}
export interface InternalMiddlewareState {
currentSubscriptions: SubscriptionInternalState
currentPolls: Map<string, QueryPollState>
runningQueries: Map<
string,
| QueryActionCreatorResult<any>
| InfiniteQueryActionCreatorResult<any>
| undefined
>
runningMutations: Map<string, MutationActionCreatorResult<any> | undefined>
}
export interface SubscriptionSelectors {
getSubscriptions: () => SubscriptionInternalState
getSubscriptionCount: (queryCacheKey: string) => number
isRequestSubscribed: (queryCacheKey: string, requestId: string) => boolean
}
export interface BuildMiddlewareInput<
Definitions extends EndpointDefinitions,
ReducerPath extends string,
TagTypes extends string,
> {
reducerPath: ReducerPath
context: ApiContext<Definitions>
queryThunk: QueryThunk
mutationThunk: MutationThunk
infiniteQueryThunk: InfiniteQueryThunk<any>
api: Api<any, Definitions, ReducerPath, TagTypes>
assertTagType: AssertTagTypes
selectors: AllSelectors
getRunningQueryThunk: (
endpointName: string,
queryArgs: any,
) => (dispatch: Dispatch) => QueryActionCreatorResult<any> | undefined
getInternalState: (dispatch: Dispatch) => InternalMiddlewareState
}
export type SubMiddlewareApi = MiddlewareAPI<
ThunkDispatch<any, any, UnknownAction>,
RootState<EndpointDefinitions, string, string>
>
export interface BuildSubMiddlewareInput
extends BuildMiddlewareInput<EndpointDefinitions, string, string> {
internalState: InternalMiddlewareState
refetchQuery(
querySubState: Exclude<
QuerySubState<any>,
{ status: QueryStatus.uninitialized }
>,
): ThunkAction<QueryActionCreatorResult<any>, any, any, UnknownAction>
isThisApiSliceAction: (action: Action) => boolean
selectors: AllSelectors
mwApi: MiddlewareAPI<
ThunkDispatch<any, any, UnknownAction>,
RootState<EndpointDefinitions, string, string>
>
}
export type SubMiddlewareBuilder = (
input: BuildSubMiddlewareInput,
) => Middleware<
{},
RootState<EndpointDefinitions, string, string>,
ThunkDispatch<any, any, UnknownAction>
>
type MwNext = Parameters<ReturnType<Middleware>>[0]
export type ApiMiddlewareInternalHandler<Return = void> = (
action: Action,
mwApi: SubMiddlewareApi & { next: MwNext },
prevState: RootState<EndpointDefinitions, string, string>,
) => Return
export type InternalHandlerBuilder<ReturnType = void> = (
input: BuildSubMiddlewareInput,
) => ApiMiddlewareInternalHandler<ReturnType>
export interface PromiseConstructorWithKnownReason {
/**
* Creates a new Promise with a known rejection reason.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T, R>(
executor: (
resolve: (value: T | PromiseLike<T>) => void,
reject: (reason?: R) => void,
) => void,
): PromiseWithKnownReason<T, R>
}
export type PromiseWithKnownReason<T, R> = Omit<
Promise<T>,
'then' | 'catch'
> & {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(
onfulfilled?:
| ((value: T) => TResult1 | PromiseLike<TResult1>)
| undefined
| null,
onrejected?:
| ((reason: R) => TResult2 | PromiseLike<TResult2>)
| undefined
| null,
): Promise<TResult1 | TResult2>
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(
onrejected?:
| ((reason: R) => TResult | PromiseLike<TResult>)
| undefined
| null,
): Promise<T | TResult>
}

View File

@@ -0,0 +1,64 @@
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
import type { QueryCacheKey } from '../apiState'
import { onFocus, onOnline } from '../setupListeners'
import type {
ApiMiddlewareInternalHandler,
InternalHandlerBuilder,
SubMiddlewareApi,
} from './types'
export const buildWindowEventHandler: InternalHandlerBuilder = ({
reducerPath,
context,
api,
refetchQuery,
internalState,
}) => {
const { removeQueryResult } = api.internalActions
const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
if (onFocus.match(action)) {
refetchValidQueries(mwApi, 'refetchOnFocus')
}
if (onOnline.match(action)) {
refetchValidQueries(mwApi, 'refetchOnReconnect')
}
}
function refetchValidQueries(
api: SubMiddlewareApi,
type: 'refetchOnFocus' | 'refetchOnReconnect',
) {
const state = api.getState()[reducerPath]
const queries = state.queries
const subscriptions = internalState.currentSubscriptions
context.batch(() => {
for (const queryCacheKey of subscriptions.keys()) {
const querySubState = queries[queryCacheKey]
const subscriptionSubState = subscriptions.get(queryCacheKey)
if (!subscriptionSubState || !querySubState) continue
const values = [...subscriptionSubState.values()]
const shouldRefetch =
values.some((sub) => sub[type] === true) ||
(values.every((sub) => sub[type] === undefined) && state.config[type])
if (shouldRefetch) {
if (subscriptionSubState.size === 0) {
api.dispatch(
removeQueryResult({
queryCacheKey: queryCacheKey as QueryCacheKey,
}),
)
} else if (querySubState.status !== STATUS_UNINITIALIZED) {
api.dispatch(refetchQuery(querySubState))
}
}
}
})
}
return handler
}

View File

@@ -0,0 +1,413 @@
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import type {
EndpointDefinition,
EndpointDefinitions,
InfiniteQueryArgFrom,
InfiniteQueryDefinition,
MutationDefinition,
QueryArgFrom,
QueryArgFromAnyQuery,
QueryDefinition,
ReducerPathFrom,
TagDescription,
TagTypesFrom,
} from '../endpointDefinitions'
import { expandTagDescription } from '../endpointDefinitions'
import { filterMap, isNotNullish } from '../utils'
import type {
InfiniteData,
InfiniteQueryConfigOptions,
InfiniteQuerySubState,
MutationSubState,
QueryCacheKey,
QueryState,
QuerySubState,
RequestStatusFlags,
RootState as _RootState,
QueryStatus,
} from './apiState'
import { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState'
import { getMutationCacheKey } from './buildSlice'
import type { createSelector as _createSelector } from './rtkImports'
import { createNextState } from './rtkImports'
import {
type AllQueryKeys,
getNextPageParam,
getPreviousPageParam,
} from './buildThunks'
export type SkipToken = typeof skipToken
/**
* Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`
* instead of the query argument to get the same effect as if setting
* `skip: true` in the query options.
*
* Useful for scenarios where a query should be skipped when `arg` is `undefined`
* and TypeScript complains about it because `arg` is not allowed to be passed
* in as `undefined`, such as
*
* ```ts
* // codeblock-meta title="will error if the query argument is not allowed to be undefined" no-transpile
* useSomeQuery(arg, { skip: !!arg })
* ```
*
* ```ts
* // codeblock-meta title="using skipToken instead" no-transpile
* useSomeQuery(arg ?? skipToken)
* ```
*
* If passed directly into a query or mutation selector, that selector will always
* return an uninitialized state.
*/
export const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken')
export type BuildSelectorsApiEndpointQuery<
Definition extends QueryDefinition<any, any, any, any, any>,
Definitions extends EndpointDefinitions,
> = {
select: QueryResultSelectorFactory<
Definition,
_RootState<
Definitions,
TagTypesFrom<Definition>,
ReducerPathFrom<Definition>
>
>
}
export type BuildSelectorsApiEndpointInfiniteQuery<
Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
Definitions extends EndpointDefinitions,
> = {
select: InfiniteQueryResultSelectorFactory<
Definition,
_RootState<
Definitions,
TagTypesFrom<Definition>,
ReducerPathFrom<Definition>
>
>
}
export type BuildSelectorsApiEndpointMutation<
Definition extends MutationDefinition<any, any, any, any, any>,
Definitions extends EndpointDefinitions,
> = {
select: MutationResultSelectorFactory<
Definition,
_RootState<
Definitions,
TagTypesFrom<Definition>,
ReducerPathFrom<Definition>
>
>
}
type QueryResultSelectorFactory<
Definition extends QueryDefinition<any, any, any, any>,
RootState,
> = (
queryArg: QueryArgFrom<Definition> | SkipToken,
) => (state: RootState) => QueryResultSelectorResult<Definition>
export type QueryResultSelectorResult<
Definition extends QueryDefinition<any, any, any, any>,
> = QuerySubState<Definition> & RequestStatusFlags
type InfiniteQueryResultSelectorFactory<
Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
RootState,
> = (
queryArg: InfiniteQueryArgFrom<Definition> | SkipToken,
) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>
export type InfiniteQueryResultFlags = {
hasNextPage: boolean
hasPreviousPage: boolean
isFetchingNextPage: boolean
isFetchingPreviousPage: boolean
isFetchNextPageError: boolean
isFetchPreviousPageError: boolean
}
export type InfiniteQueryResultSelectorResult<
Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
> = InfiniteQuerySubState<Definition> &
RequestStatusFlags &
InfiniteQueryResultFlags
type MutationResultSelectorFactory<
Definition extends MutationDefinition<any, any, any, any>,
RootState,
> = (
requestId:
| string
| { requestId: string | undefined; fixedCacheKey: string | undefined }
| SkipToken,
) => (state: RootState) => MutationResultSelectorResult<Definition>
export type MutationResultSelectorResult<
Definition extends MutationDefinition<any, any, any, any>,
> = MutationSubState<Definition> & RequestStatusFlags
const initialSubState: QuerySubState<any> = {
status: STATUS_UNINITIALIZED,
}
// abuse immer to freeze default states
const defaultQuerySubState = /* @__PURE__ */ createNextState(
initialSubState,
() => {},
)
const defaultMutationSubState = /* @__PURE__ */ createNextState(
initialSubState as MutationSubState<any>,
() => {},
)
export type AllSelectors = ReturnType<typeof buildSelectors>
export function buildSelectors<
Definitions extends EndpointDefinitions,
ReducerPath extends string,
>({
serializeQueryArgs,
reducerPath,
createSelector,
}: {
serializeQueryArgs: InternalSerializeQueryArgs
reducerPath: ReducerPath
createSelector: typeof _createSelector
}) {
type RootState = _RootState<Definitions, string, string>
const selectSkippedQuery = (state: RootState) => defaultQuerySubState
const selectSkippedMutation = (state: RootState) => defaultMutationSubState
return {
buildQuerySelector,
buildInfiniteQuerySelector,
buildMutationSelector,
selectInvalidatedBy,
selectCachedArgsForQuery,
selectApiState,
selectQueries,
selectMutations,
selectQueryEntry,
selectConfig,
}
function withRequestFlags<T extends { status: QueryStatus }>(
substate: T,
): T & RequestStatusFlags {
return { ...substate, ...getRequestStatusFlags(substate.status) }
}
function selectApiState(rootState: RootState) {
const state = rootState[reducerPath]
if (process.env.NODE_ENV !== 'production') {
if (!state) {
if ((selectApiState as any).triggered) return state
;(selectApiState as any).triggered = true
console.error(
`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`,
)
}
}
return state
}
function selectQueries(rootState: RootState) {
return selectApiState(rootState)?.queries
}
function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {
return selectQueries(rootState)?.[cacheKey]
}
function selectMutations(rootState: RootState) {
return selectApiState(rootState)?.mutations
}
function selectConfig(rootState: RootState) {
return selectApiState(rootState)?.config
}
function buildAnyQuerySelector(
endpointName: string,
endpointDefinition: EndpointDefinition<any, any, any, any>,
combiner: <T extends { status: QueryStatus }>(
substate: T,
) => T & RequestStatusFlags,
) {
return (queryArgs: any) => {
// Avoid calling serializeQueryArgs if the arg is skipToken
if (queryArgs === skipToken) {
return createSelector(selectSkippedQuery, combiner)
}
const serializedArgs = serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName,
})
const selectQuerySubstate = (state: RootState) =>
selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState
return createSelector(selectQuerySubstate, combiner)
}
}
function buildQuerySelector(
endpointName: string,
endpointDefinition: QueryDefinition<any, any, any, any>,
) {
return buildAnyQuerySelector(
endpointName,
endpointDefinition,
withRequestFlags,
) as QueryResultSelectorFactory<any, RootState>
}
function buildInfiniteQuerySelector(
endpointName: string,
endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,
) {
const { infiniteQueryOptions } = endpointDefinition
function withInfiniteQueryResultFlags<T extends { status: QueryStatus }>(
substate: T,
): T & RequestStatusFlags & InfiniteQueryResultFlags {
const stateWithRequestFlags = {
...(substate as InfiniteQuerySubState<any>),
...getRequestStatusFlags(substate.status),
}
const { isLoading, isError, direction } = stateWithRequestFlags
const isForward = direction === 'forward'
const isBackward = direction === 'backward'
return {
...stateWithRequestFlags,
hasNextPage: getHasNextPage(
infiniteQueryOptions,
stateWithRequestFlags.data,
stateWithRequestFlags.originalArgs,
),
hasPreviousPage: getHasPreviousPage(
infiniteQueryOptions,
stateWithRequestFlags.data,
stateWithRequestFlags.originalArgs,
),
isFetchingNextPage: isLoading && isForward,
isFetchingPreviousPage: isLoading && isBackward,
isFetchNextPageError: isError && isForward,
isFetchPreviousPageError: isError && isBackward,
}
}
return buildAnyQuerySelector(
endpointName,
endpointDefinition,
withInfiniteQueryResultFlags,
) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>
}
function buildMutationSelector() {
return ((id) => {
let mutationId: string | typeof skipToken
if (typeof id === 'object') {
mutationId = getMutationCacheKey(id) ?? skipToken
} else {
mutationId = id
}
const selectMutationSubstate = (state: RootState) =>
selectApiState(state)?.mutations?.[mutationId as string] ??
defaultMutationSubState
const finalSelectMutationSubstate =
mutationId === skipToken
? selectSkippedMutation
: selectMutationSubstate
return createSelector(finalSelectMutationSubstate, withRequestFlags)
}) as MutationResultSelectorFactory<any, RootState>
}
function selectInvalidatedBy(
state: RootState,
tags: ReadonlyArray<TagDescription<string> | null | undefined>,
): Array<{
endpointName: string
originalArgs: any
queryCacheKey: QueryCacheKey
}> {
const apiState = state[reducerPath]
const toInvalidate = new Set<QueryCacheKey>()
const finalTags = filterMap(tags, isNotNullish, expandTagDescription)
for (const tag of finalTags) {
const provided = apiState.provided.tags[tag.type]
if (!provided) {
continue
}
let invalidateSubscriptions =
(tag.id !== undefined
? // id given: invalidate all queries that provide this type & id
provided[tag.id]
: // no id: invalidate all queries that provide this type
Object.values(provided).flat()) ?? []
for (const invalidate of invalidateSubscriptions) {
toInvalidate.add(invalidate)
}
}
return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
const querySubState = apiState.queries[queryCacheKey]
return querySubState
? {
queryCacheKey,
endpointName: querySubState.endpointName!,
originalArgs: querySubState.originalArgs,
}
: []
})
}
function selectCachedArgsForQuery<
QueryName extends AllQueryKeys<Definitions>,
>(
state: RootState,
queryName: QueryName,
): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {
return filterMap(
Object.values(selectQueries(state) as QueryState<any>),
(
entry,
): entry is Exclude<
QuerySubState<Definitions[QueryName]>,
{ status: QueryStatus.uninitialized }
> =>
entry?.endpointName === queryName &&
entry.status !== STATUS_UNINITIALIZED,
(entry) => entry.originalArgs,
)
}
function getHasNextPage(
options: InfiniteQueryConfigOptions<any, any, any>,
data?: InfiniteData<unknown, unknown>,
queryArg?: unknown,
): boolean {
if (!data) return false
return getNextPageParam(options, data, queryArg) != null
}
function getHasPreviousPage(
options: InfiniteQueryConfigOptions<any, any, any>,
data?: InfiniteData<unknown, unknown>,
queryArg?: unknown,
): boolean {
if (!data || !options.getPreviousPageParam) return false
return getPreviousPageParam(options, data, queryArg) != null
}
}

View File

@@ -0,0 +1,735 @@
import type { PayloadAction } from '@reduxjs/toolkit'
import {
combineReducers,
createAction,
createSlice,
isAnyOf,
isFulfilled,
isRejectedWithValue,
createNextState,
prepareAutoBatched,
SHOULD_AUTOBATCH,
nanoid,
} from './rtkImports'
import type {
QuerySubstateIdentifier,
QuerySubState,
MutationSubstateIdentifier,
MutationSubState,
MutationState,
QueryState,
InvalidationState,
Subscribers,
QueryCacheKey,
SubscriptionState,
ConfigState,
InfiniteQuerySubState,
InfiniteQueryDirection,
} from './apiState'
import {
STATUS_FULFILLED,
STATUS_PENDING,
QueryStatus,
STATUS_REJECTED,
STATUS_UNINITIALIZED,
} from './apiState'
import type {
AllQueryKeys,
QueryArgFromAnyQueryDefinition,
DataFromAnyQueryDefinition,
InfiniteQueryThunk,
MutationThunk,
QueryThunk,
QueryThunkArg,
} from './buildThunks'
import { calculateProvidedByThunk } from './buildThunks'
import {
ENDPOINT_QUERY,
isInfiniteQueryDefinition,
type AssertTagTypes,
type EndpointDefinitions,
type FullTagDescription,
type QueryDefinition,
} from '../endpointDefinitions'
import type { Patch } from 'immer'
import { applyPatches, original, isDraft } from '../utils/immerImports'
import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
import {
isDocumentVisible,
isOnline,
copyWithStructuralSharing,
} from '../utils'
import type { ApiContext } from '../apiTypes'
import { isUpsertQuery } from './buildInitiate'
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import type { UnwrapPromise } from '../tsHelpers'
import { getCurrent } from '../utils/getCurrent'
/**
* A typesafe single entry to be upserted into the cache
*/
export type NormalizedQueryUpsertEntry<
Definitions extends EndpointDefinitions,
EndpointName extends AllQueryKeys<Definitions>,
> = {
endpointName: EndpointName
arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>
value: DataFromAnyQueryDefinition<Definitions, EndpointName>
}
/**
* The internal version that is not typesafe since we can't carry the generics through `createSlice`
*/
type NormalizedQueryUpsertEntryPayload = {
endpointName: string
arg: unknown
value: unknown
}
export type ProcessedQueryUpsertEntry = {
queryDescription: QueryThunkArg
value: unknown
}
/**
* A typesafe representation of a util action creator that accepts cache entry descriptions to upsert
*/
export type UpsertEntries<Definitions extends EndpointDefinitions> = (<
EndpointNames extends Array<AllQueryKeys<Definitions>>,
>(
entries: [
...{
[I in keyof EndpointNames]: NormalizedQueryUpsertEntry<
Definitions,
EndpointNames[I]
>
},
],
) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {
match: (
action: unknown,
) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>
}
function updateQuerySubstateIfExists(
state: QueryState<any>,
queryCacheKey: QueryCacheKey,
update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void,
) {
const substate = state[queryCacheKey]
if (substate) {
update(substate)
}
}
export function getMutationCacheKey(
id:
| MutationSubstateIdentifier
| { requestId: string; arg: { fixedCacheKey?: string | undefined } },
): string
export function getMutationCacheKey(id: {
fixedCacheKey?: string
requestId?: string
}): string | undefined
export function getMutationCacheKey(
id:
| { fixedCacheKey?: string; requestId?: string }
| MutationSubstateIdentifier
| { requestId: string; arg: { fixedCacheKey?: string | undefined } },
): string | undefined {
return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId
}
function updateMutationSubstateIfExists(
state: MutationState<any>,
id:
| MutationSubstateIdentifier
| { requestId: string; arg: { fixedCacheKey?: string | undefined } },
update: (substate: MutationSubState<any>) => void,
) {
const substate = state[getMutationCacheKey(id)]
if (substate) {
update(substate)
}
}
const initialState = {} as any
export function buildSlice({
reducerPath,
queryThunk,
mutationThunk,
serializeQueryArgs,
context: {
endpointDefinitions: definitions,
apiUid,
extractRehydrationInfo,
hasRehydrationInfo,
},
assertTagType,
config,
}: {
reducerPath: string
queryThunk: QueryThunk
infiniteQueryThunk: InfiniteQueryThunk<any>
mutationThunk: MutationThunk
serializeQueryArgs: InternalSerializeQueryArgs
context: ApiContext<EndpointDefinitions>
assertTagType: AssertTagTypes
config: Omit<
ConfigState<string>,
'online' | 'focused' | 'middlewareRegistered'
>
}) {
const resetApiState = createAction(`${reducerPath}/resetApiState`)
function writePendingCacheEntry(
draft: QueryState<any>,
arg: QueryThunkArg,
upserting: boolean,
meta: {
arg: QueryThunkArg
requestId: string
// requestStatus: 'pending'
} & { startedTimeStamp: number },
) {
draft[arg.queryCacheKey] ??= {
status: STATUS_UNINITIALIZED,
endpointName: arg.endpointName,
}
updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
substate.status = STATUS_PENDING
substate.requestId =
upserting && substate.requestId
? // for `upsertQuery` **updates**, keep the current `requestId`
substate.requestId
: // for normal queries or `upsertQuery` **inserts** always update the `requestId`
meta.requestId
if (arg.originalArgs !== undefined) {
substate.originalArgs = arg.originalArgs
}
substate.startedTimeStamp = meta.startedTimeStamp
const endpointDefinition = definitions[meta.arg.endpointName]
if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {
;(substate as InfiniteQuerySubState<any>).direction =
arg.direction as InfiniteQueryDirection
}
})
}
function writeFulfilledCacheEntry(
draft: QueryState<any>,
meta: { arg: QueryThunkArg; requestId: string } & {
fulfilledTimeStamp: number
baseQueryMeta: unknown
},
payload: unknown,
upserting: boolean,
) {
updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
if (substate.requestId !== meta.requestId && !upserting) return
const { merge } = definitions[meta.arg.endpointName] as QueryDefinition<
any,
any,
any,
any
>
substate.status = STATUS_FULFILLED
if (merge) {
if (substate.data !== undefined) {
const { fulfilledTimeStamp, arg, baseQueryMeta, requestId } = meta
// There's existing cache data. Let the user merge it in themselves.
// We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`
// themselves inside of `merge()`. But, they might also want to return a new value.
// Try to let Immer figure that part out, save the result, and assign it to `substate.data`.
let newData = createNextState(substate.data, (draftSubstateData) => {
// As usual with Immer, you can mutate _or_ return inside here, but not both
return merge(draftSubstateData, payload, {
arg: arg.originalArgs,
baseQueryMeta,
fulfilledTimeStamp,
requestId,
})
})
substate.data = newData
} else {
// Presumably a fresh request. Just cache the response data.
substate.data = payload
}
} else {
// Assign or safely update the cache data.
substate.data =
(definitions[meta.arg.endpointName].structuralSharing ?? true)
? copyWithStructuralSharing(
isDraft(substate.data)
? original(substate.data)
: substate.data,
payload,
)
: payload
}
delete substate.error
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
})
}
const querySlice = createSlice({
name: `${reducerPath}/queries`,
initialState: initialState as QueryState<any>,
reducers: {
removeQueryResult: {
reducer(
draft,
{
payload: { queryCacheKey },
}: PayloadAction<QuerySubstateIdentifier>,
) {
delete draft[queryCacheKey]
},
prepare: prepareAutoBatched<QuerySubstateIdentifier>(),
},
cacheEntriesUpserted: {
reducer(
draft,
action: PayloadAction<
ProcessedQueryUpsertEntry[],
string,
{ RTK_autoBatch: boolean; requestId: string; timestamp: number }
>,
) {
for (const entry of action.payload) {
const { queryDescription: arg, value } = entry
writePendingCacheEntry(draft, arg, true, {
arg,
requestId: action.meta.requestId,
startedTimeStamp: action.meta.timestamp,
})
writeFulfilledCacheEntry(
draft,
{
arg,
requestId: action.meta.requestId,
fulfilledTimeStamp: action.meta.timestamp,
baseQueryMeta: {},
},
value,
// We know we're upserting here
true,
)
}
},
prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {
const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(
(entry) => {
const { endpointName, arg, value } = entry
const endpointDefinition = definitions[endpointName]
const queryDescription: QueryThunkArg = {
type: ENDPOINT_QUERY as 'query',
endpointName,
originalArgs: entry.arg,
queryCacheKey: serializeQueryArgs({
queryArgs: arg,
endpointDefinition,
endpointName,
}),
}
return { queryDescription, value }
},
)
const result = {
payload: queryDescriptions,
meta: {
[SHOULD_AUTOBATCH]: true,
requestId: nanoid(),
timestamp: Date.now(),
},
}
return result
},
},
queryResultPatched: {
reducer(
draft,
{
payload: { queryCacheKey, patches },
}: PayloadAction<
QuerySubstateIdentifier & { patches: readonly Patch[] }
>,
) {
updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
substate.data = applyPatches(substate.data as any, patches.concat())
})
},
prepare: prepareAutoBatched<
QuerySubstateIdentifier & { patches: readonly Patch[] }
>(),
},
},
extraReducers(builder) {
builder
.addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
const upserting = isUpsertQuery(arg)
writePendingCacheEntry(draft, arg, upserting, meta)
})
.addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {
const upserting = isUpsertQuery(meta.arg)
writeFulfilledCacheEntry(draft, meta, payload, upserting)
})
.addCase(
queryThunk.rejected,
(draft, { meta: { condition, arg, requestId }, error, payload }) => {
updateQuerySubstateIfExists(
draft,
arg.queryCacheKey,
(substate) => {
if (condition) {
// request was aborted due to condition (another query already running)
} else {
// request failed
if (substate.requestId !== requestId) return
substate.status = STATUS_REJECTED
substate.error = (payload ?? error) as any
}
},
)
},
)
.addMatcher(hasRehydrationInfo, (draft, action) => {
const { queries } = extractRehydrationInfo(action)!
for (const [key, entry] of Object.entries(queries)) {
if (
// do not rehydrate entries that were currently in flight.
entry?.status === STATUS_FULFILLED ||
entry?.status === STATUS_REJECTED
) {
draft[key] = entry
}
}
})
},
})
const mutationSlice = createSlice({
name: `${reducerPath}/mutations`,
initialState: initialState as MutationState<any>,
reducers: {
removeMutationResult: {
reducer(draft, { payload }: PayloadAction<MutationSubstateIdentifier>) {
const cacheKey = getMutationCacheKey(payload)
if (cacheKey in draft) {
delete draft[cacheKey]
}
},
prepare: prepareAutoBatched<MutationSubstateIdentifier>(),
},
},
extraReducers(builder) {
builder
.addCase(
mutationThunk.pending,
(draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {
if (!arg.track) return
draft[getMutationCacheKey(meta)] = {
requestId,
status: STATUS_PENDING,
endpointName: arg.endpointName,
startedTimeStamp,
}
},
)
.addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {
if (!meta.arg.track) return
updateMutationSubstateIfExists(draft, meta, (substate) => {
if (substate.requestId !== meta.requestId) return
substate.status = STATUS_FULFILLED
substate.data = payload
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
})
})
.addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {
if (!meta.arg.track) return
updateMutationSubstateIfExists(draft, meta, (substate) => {
if (substate.requestId !== meta.requestId) return
substate.status = STATUS_REJECTED
substate.error = (payload ?? error) as any
})
})
.addMatcher(hasRehydrationInfo, (draft, action) => {
const { mutations } = extractRehydrationInfo(action)!
for (const [key, entry] of Object.entries(mutations)) {
if (
// do not rehydrate entries that were currently in flight.
(entry?.status === STATUS_FULFILLED ||
entry?.status === STATUS_REJECTED) &&
// only rehydrate endpoints that were persisted using a `fixedCacheKey`
key !== entry?.requestId
) {
draft[key] = entry
}
}
})
},
})
type CalculateProvidedByAction = UnwrapPromise<
| ReturnType<ReturnType<QueryThunk>>
| ReturnType<ReturnType<InfiniteQueryThunk<any>>>
>
const initialInvalidationState: InvalidationState<string> = {
tags: {},
keys: {},
}
const invalidationSlice = createSlice({
name: `${reducerPath}/invalidation`,
initialState: initialInvalidationState,
reducers: {
updateProvidedBy: {
reducer(
draft,
action: PayloadAction<
Array<{
queryCacheKey: QueryCacheKey
providedTags: readonly FullTagDescription<string>[]
}>
>,
) {
for (const { queryCacheKey, providedTags } of action.payload) {
removeCacheKeyFromTags(draft, queryCacheKey)
for (const { type, id } of providedTags) {
const subscribedQueries = ((draft.tags[type] ??= {})[
id || '__internal_without_id'
] ??= [])
const alreadySubscribed =
subscribedQueries.includes(queryCacheKey)
if (!alreadySubscribed) {
subscribedQueries.push(queryCacheKey)
}
}
// Remove readonly from the providedTags array
draft.keys[queryCacheKey] =
providedTags as FullTagDescription<string>[]
}
},
prepare: prepareAutoBatched<
Array<{
queryCacheKey: QueryCacheKey
providedTags: readonly FullTagDescription<string>[]
}>
>(),
},
},
extraReducers(builder) {
builder
.addCase(
querySlice.actions.removeQueryResult,
(draft, { payload: { queryCacheKey } }) => {
removeCacheKeyFromTags(draft, queryCacheKey)
},
)
.addMatcher(hasRehydrationInfo, (draft, action) => {
const { provided } = extractRehydrationInfo(action)!
for (const [type, incomingTags] of Object.entries(
provided.tags ?? {},
)) {
for (const [id, cacheKeys] of Object.entries(incomingTags)) {
const subscribedQueries = ((draft.tags[type] ??= {})[
id || '__internal_without_id'
] ??= [])
for (const queryCacheKey of cacheKeys) {
const alreadySubscribed =
subscribedQueries.includes(queryCacheKey)
if (!alreadySubscribed) {
subscribedQueries.push(queryCacheKey)
}
draft.keys[queryCacheKey] = provided.keys[queryCacheKey]
}
}
}
})
.addMatcher(
isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)),
(draft, action) => {
writeProvidedTagsForQueries(draft, [action])
},
)
.addMatcher(
querySlice.actions.cacheEntriesUpserted.match,
(draft, action) => {
const mockActions: CalculateProvidedByAction[] = action.payload.map(
({ queryDescription, value }) => {
return {
type: 'UNKNOWN',
payload: value,
meta: {
requestStatus: 'fulfilled',
requestId: 'UNKNOWN',
arg: queryDescription,
},
}
},
)
writeProvidedTagsForQueries(draft, mockActions)
},
)
},
})
function removeCacheKeyFromTags(
draft: InvalidationState<any>,
queryCacheKey: QueryCacheKey,
) {
const existingTags = getCurrent(draft.keys[queryCacheKey] ?? [])
// Delete this cache key from any existing tags that may have provided it
for (const tag of existingTags) {
const tagType = tag.type
const tagId = tag.id ?? '__internal_without_id'
const tagSubscriptions = draft.tags[tagType]?.[tagId]
if (tagSubscriptions) {
draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(
(qc) => qc !== queryCacheKey,
)
}
}
delete draft.keys[queryCacheKey]
}
function writeProvidedTagsForQueries(
draft: InvalidationState<string>,
actions: CalculateProvidedByAction[],
) {
const providedByEntries = actions.map((action) => {
const providedTags = calculateProvidedByThunk(
action,
'providesTags',
definitions,
assertTagType,
)
const { queryCacheKey } = action.meta.arg
return { queryCacheKey, providedTags }
})
invalidationSlice.caseReducers.updateProvidedBy(
draft,
invalidationSlice.actions.updateProvidedBy(providedByEntries),
)
}
// Dummy slice to generate actions
const subscriptionSlice = createSlice({
name: `${reducerPath}/subscriptions`,
initialState: initialState as SubscriptionState,
reducers: {
updateSubscriptionOptions(
d,
a: PayloadAction<
{
endpointName: string
requestId: string
options: Subscribers[number]
} & QuerySubstateIdentifier
>,
) {
// Dummy
},
unsubscribeQueryResult(
d,
a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>,
) {
// Dummy
},
internal_getRTKQSubscriptions() {},
},
})
const internalSubscriptionsSlice = createSlice({
name: `${reducerPath}/internalSubscriptions`,
initialState: initialState as SubscriptionState,
reducers: {
subscriptionsUpdated: {
reducer(state, action: PayloadAction<Patch[]>) {
return applyPatches(state, action.payload)
},
prepare: prepareAutoBatched<Patch[]>(),
},
},
})
const configSlice = createSlice({
name: `${reducerPath}/config`,
initialState: {
online: isOnline(),
focused: isDocumentVisible(),
middlewareRegistered: false,
...config,
} as ConfigState<string>,
reducers: {
middlewareRegistered(state, { payload }: PayloadAction<string>) {
state.middlewareRegistered =
state.middlewareRegistered === 'conflict' || apiUid !== payload
? 'conflict'
: true
},
},
extraReducers: (builder) => {
builder
.addCase(onOnline, (state) => {
state.online = true
})
.addCase(onOffline, (state) => {
state.online = false
})
.addCase(onFocus, (state) => {
state.focused = true
})
.addCase(onFocusLost, (state) => {
state.focused = false
})
// update the state to be a new object to be picked up as a "state change"
// by redux-persist's `autoMergeLevel2`
.addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))
},
})
const combinedReducer = combineReducers({
queries: querySlice.reducer,
mutations: mutationSlice.reducer,
provided: invalidationSlice.reducer,
subscriptions: internalSubscriptionsSlice.reducer,
config: configSlice.reducer,
})
const reducer: typeof combinedReducer = (state, action) =>
combinedReducer(resetApiState.match(action) ? undefined : state, action)
const actions = {
...configSlice.actions,
...querySlice.actions,
...subscriptionSlice.actions,
...internalSubscriptionsSlice.actions,
...mutationSlice.actions,
...invalidationSlice.actions,
resetApiState,
}
return { reducer, actions }
}
export type SliceActions = ReturnType<typeof buildSlice>['actions']

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
import { buildCreateApi } from '../createApi'
import { coreModule } from './module'
export const createApi = /* @__PURE__ */ buildCreateApi(coreModule())
export { QueryStatus } from './apiState'
export type {
CombinedState,
InfiniteData,
InfiniteQueryConfigOptions,
InfiniteQuerySubState,
MutationKeys,
QueryCacheKey,
QueryKeys,
QuerySubState,
RootState,
SubscriptionOptions,
} from './apiState'
export type {
InfiniteQueryActionCreatorResult,
MutationActionCreatorResult,
QueryActionCreatorResult,
StartQueryActionCreatorOptions,
} from './buildInitiate'
export type {
MutationCacheLifecycleApi,
MutationLifecycleApi,
QueryCacheLifecycleApi,
QueryLifecycleApi,
SubscriptionSelectors,
TypedMutationOnQueryStarted,
TypedQueryOnQueryStarted,
} from './buildMiddleware/index'
export { skipToken } from './buildSelectors'
export type {
InfiniteQueryResultSelectorResult,
MutationResultSelectorResult,
QueryResultSelectorResult,
SkipToken,
} from './buildSelectors'
export type { SliceActions } from './buildSlice'
export type {
PatchQueryDataThunk,
UpdateQueryDataThunk,
UpsertQueryDataThunk,
} from './buildThunks'
export { coreModuleName } from './module'
export type {
ApiEndpointInfiniteQuery,
ApiEndpointMutation,
ApiEndpointQuery,
CoreModule,
InternalActions,
PrefetchOptions,
ThunkWithReturnValue,
} from './module'
export { setupListeners } from './setupListeners'
export { buildCreateApi, coreModule }

View File

@@ -0,0 +1,726 @@
/**
* Note: this file should import all other files for type discovery and declaration merging
*/
import type {
ActionCreatorWithPayload,
Dispatch,
Middleware,
Reducer,
ThunkAction,
ThunkDispatch,
UnknownAction,
} from '@reduxjs/toolkit'
import { enablePatches } from '../utils/immerImports'
import type { Api, Module } from '../apiTypes'
import type { BaseQueryFn } from '../baseQueryTypes'
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import type {
AssertTagTypes,
EndpointDefinitions,
InfiniteQueryDefinition,
MutationDefinition,
QueryArgFrom,
QueryArgFromAnyQuery,
QueryDefinition,
TagDescription,
} from '../endpointDefinitions'
import {
isInfiniteQueryDefinition,
isMutationDefinition,
isQueryDefinition,
} from '../endpointDefinitions'
import { assertCast, safeAssign } from '../tsHelpers'
import type {
CombinedState,
MutationKeys,
QueryKeys,
RootState,
} from './apiState'
import type {
BuildInitiateApiEndpointMutation,
BuildInitiateApiEndpointQuery,
MutationActionCreatorResult,
QueryActionCreatorResult,
InfiniteQueryActionCreatorResult,
BuildInitiateApiEndpointInfiniteQuery,
} from './buildInitiate'
import { buildInitiate } from './buildInitiate'
import type {
ReferenceCacheCollection,
ReferenceCacheLifecycle,
ReferenceQueryLifecycle,
} from './buildMiddleware'
import { buildMiddleware } from './buildMiddleware'
import type {
BuildSelectorsApiEndpointInfiniteQuery,
BuildSelectorsApiEndpointMutation,
BuildSelectorsApiEndpointQuery,
} from './buildSelectors'
import { buildSelectors } from './buildSelectors'
import type { SliceActions, UpsertEntries } from './buildSlice'
import { buildSlice } from './buildSlice'
import type {
AllQueryKeys,
BuildThunksApiEndpointInfiniteQuery,
BuildThunksApiEndpointMutation,
BuildThunksApiEndpointQuery,
PatchQueryDataThunk,
QueryArgFromAnyQueryDefinition,
UpdateQueryDataThunk,
UpsertQueryDataThunk,
} from './buildThunks'
import { buildThunks } from './buildThunks'
import { createSelector as _createSelector } from './rtkImports'
import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
import type { InternalMiddlewareState } from './buildMiddleware/types'
import { getOrInsertComputed } from '../utils'
/**
* `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
* - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
*
* @overloadSummary
* `force`
* - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
*/
export type PrefetchOptions =
| {
ifOlderThan?: false | number
}
| { force?: boolean }
export const coreModuleName = /* @__PURE__ */ Symbol()
export type CoreModule =
| typeof coreModuleName
| ReferenceCacheLifecycle
| ReferenceQueryLifecycle
| ReferenceCacheCollection
export type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>
export interface ApiModules<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
ReducerPath extends string,
TagTypes extends string,
> {
[coreModuleName]: {
/**
* This api's reducer should be mounted at `store[api.reducerPath]`.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
reducerPath: ReducerPath
/**
* Internal actions not part of the public API. Note: These are subject to change at any given time.
*/
internalActions: InternalActions
/**
* A standard redux reducer that enables core functionality. Make sure it's included in your store.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
reducer: Reducer<
CombinedState<Definitions, TagTypes, ReducerPath>,
UnknownAction
>
/**
* 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.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
middleware: Middleware<
{},
RootState<Definitions, string, ReducerPath>,
ThunkDispatch<any, any, UnknownAction>
>
/**
* A collection of utility thunks for various situations.
*/
util: {
/**
* A thunk that (if dispatched) will return a specific running query, identified
* by `endpointName` and `arg`.
* If that query is not running, dispatching the thunk will result in `undefined`.
*
* Can be used to await a specific query triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(
endpointName: EndpointName,
arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
): ThunkWithReturnValue<
| QueryActionCreatorResult<
Definitions[EndpointName] & { type: 'query' }
>
| InfiniteQueryActionCreatorResult<
Definitions[EndpointName] & { type: 'infinitequery' }
>
| undefined
>
/**
* A thunk that (if dispatched) will return a specific running mutation, identified
* by `endpointName` and `fixedCacheKey` or `requestId`.
* If that mutation is not running, dispatching the thunk will result in `undefined`.
*
* Can be used to await a specific mutation triggered in any way,
* including via hook trigger functions or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
endpointName: EndpointName,
fixedCacheKeyOrRequestId: string,
): ThunkWithReturnValue<
| MutationActionCreatorResult<
Definitions[EndpointName] & { type: 'mutation' }
>
| undefined
>
/**
* A thunk that (if dispatched) will return all running queries.
*
* Useful for SSR scenarios to await all running queries triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningQueriesThunk(): ThunkWithReturnValue<
Array<
QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>
>
>
/**
* A thunk that (if dispatched) will return all running mutations.
*
* Useful for SSR scenarios to await all running mutations triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningMutationsThunk(): ThunkWithReturnValue<
Array<MutationActionCreatorResult<any>>
>
/**
* A Redux thunk that can be used to manually trigger pre-fetching of data.
*
* 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.
*
* 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.
*
* @example
*
* ```ts no-transpile
* dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
* ```
*/
prefetch<EndpointName extends QueryKeys<Definitions>>(
endpointName: EndpointName,
arg: QueryArgFrom<Definitions[EndpointName]>,
options?: PrefetchOptions,
): ThunkAction<void, any, any, UnknownAction>
/**
* 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.
*
* 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.
*
* 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).
*
* 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, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
*
* Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
*
* @example
*
* ```ts
* const patchCollection = dispatch(
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
* draftPosts.push({ id: 1, name: 'Teddy' })
* })
* )
* ```
*/
updateQueryData: UpdateQueryDataThunk<
Definitions,
RootState<Definitions, string, ReducerPath>
>
/**
* A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
*
* 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.
*
* 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.
*
* The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
*
* 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.
*
* @example
*
* ```ts
* await dispatch(
* api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
* )
* ```
*/
upsertQueryData: UpsertQueryDataThunk<
Definitions,
RootState<Definitions, string, ReducerPath>
>
/**
* 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.
*
* 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`.
*
* 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.
*
* 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.
*
* @example
* ```ts
* const patchCollection = dispatch(
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
* draftPosts.push({ id: 1, name: 'Teddy' })
* })
* )
*
* // later
* dispatch(
* api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
* )
*
* // or
* patchCollection.undo()
* ```
*/
patchQueryData: PatchQueryDataThunk<
Definitions,
RootState<Definitions, string, ReducerPath>
>
/**
* 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'.
*
* @example
*
* ```ts
* dispatch(api.util.resetApiState())
* ```
*/
resetApiState: SliceActions['resetApiState']
upsertQueryEntries: UpsertEntries<Definitions>
/**
* A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
*
* 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.
*
* 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.
*
* 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:
*
* - `[TagType]`
* - `[{ type: TagType }]`
* - `[{ type: TagType, id: number | string }]`
*
* @example
*
* ```ts
* dispatch(api.util.invalidateTags(['Post']))
* dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
* dispatch(
* api.util.invalidateTags([
* { type: 'Post', id: 1 },
* { type: 'Post', id: 'LIST' },
* ])
* )
* ```
*/
invalidateTags: ActionCreatorWithPayload<
Array<TagDescription<TagTypes> | null | undefined>,
string
>
/**
* A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
*
* 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.
*/
selectInvalidatedBy: (
state: RootState<Definitions, string, ReducerPath>,
tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>,
) => Array<{
endpointName: string
originalArgs: any
queryCacheKey: string
}>
/**
* A function to select all arguments currently cached for a given endpoint.
*
* 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.
*/
selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(
state: RootState<Definitions, string, ReducerPath>,
queryName: QueryName,
) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>
}
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<
any,
any,
any,
any,
any
>
? ApiEndpointQuery<Definitions[K], Definitions>
: Definitions[K] extends MutationDefinition<any, any, any, any, any>
? ApiEndpointMutation<Definitions[K], Definitions>
: Definitions[K] extends InfiniteQueryDefinition<
any,
any,
any,
any,
any
>
? ApiEndpointInfiniteQuery<Definitions[K], Definitions>
: never
}
}
}
export interface ApiEndpointQuery<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definition extends QueryDefinition<any, any, any, any, any>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definitions extends EndpointDefinitions,
> extends BuildThunksApiEndpointQuery<Definition>,
BuildInitiateApiEndpointQuery<Definition>,
BuildSelectorsApiEndpointQuery<Definition, Definitions> {
name: string
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>
}
export interface ApiEndpointInfiniteQuery<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definitions extends EndpointDefinitions,
> extends BuildThunksApiEndpointInfiniteQuery<Definition>,
BuildInitiateApiEndpointInfiniteQuery<Definition>,
BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {
name: string
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export interface ApiEndpointMutation<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definition extends MutationDefinition<any, any, any, any, any>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Definitions extends EndpointDefinitions,
> extends BuildThunksApiEndpointMutation<Definition>,
BuildInitiateApiEndpointMutation<Definition>,
BuildSelectorsApiEndpointMutation<Definition, Definitions> {
name: string
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>
}
export type ListenerActions = {
/**
* Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
* @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
*/
onOnline: typeof onOnline
onOffline: typeof onOffline
/**
* Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
* @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
*/
onFocus: typeof onFocus
onFocusLost: typeof onFocusLost
}
export type InternalActions = SliceActions & ListenerActions
export interface CoreModuleOptions {
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof _createSelector
}
/**
* Creates a module containing the basic redux logic for use with `buildCreateApi`.
*
* @example
* ```ts
* const createBaseApi = buildCreateApi(coreModule());
* ```
*/
export const coreModule = ({
createSelector = _createSelector,
}: CoreModuleOptions = {}): Module<CoreModule> => ({
name: coreModuleName,
init(
api,
{
baseQuery,
tagTypes,
reducerPath,
serializeQueryArgs,
keepUnusedDataFor,
refetchOnMountOrArgChange,
refetchOnFocus,
refetchOnReconnect,
invalidationBehavior,
onSchemaFailure,
catchSchemaFailure,
skipSchemaValidation,
},
context,
) {
enablePatches()
assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)
const assertTagType: AssertTagTypes = (tag) => {
if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
if (!tagTypes.includes(tag.type as any)) {
console.error(
`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`,
)
}
}
return tag
}
Object.assign(api, {
reducerPath,
endpoints: {},
internalActions: {
onOnline,
onOffline,
onFocus,
onFocusLost,
},
util: {},
})
const selectors = buildSelectors({
serializeQueryArgs: serializeQueryArgs as any,
reducerPath,
createSelector,
})
const {
selectInvalidatedBy,
selectCachedArgsForQuery,
buildQuerySelector,
buildInfiniteQuerySelector,
buildMutationSelector,
} = selectors
safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })
const {
queryThunk,
infiniteQueryThunk,
mutationThunk,
patchQueryData,
updateQueryData,
upsertQueryData,
prefetch,
buildMatchThunkActions,
} = buildThunks({
baseQuery,
reducerPath,
context,
api,
serializeQueryArgs,
assertTagType,
selectors,
onSchemaFailure,
catchSchemaFailure,
skipSchemaValidation,
})
const { reducer, actions: sliceActions } = buildSlice({
context,
queryThunk,
infiniteQueryThunk,
mutationThunk,
serializeQueryArgs,
reducerPath,
assertTagType,
config: {
refetchOnFocus,
refetchOnReconnect,
refetchOnMountOrArgChange,
keepUnusedDataFor,
reducerPath,
invalidationBehavior,
},
})
safeAssign(api.util, {
patchQueryData,
updateQueryData,
upsertQueryData,
prefetch,
resetApiState: sliceActions.resetApiState,
upsertQueryEntries: sliceActions.cacheEntriesUpserted as any,
})
safeAssign(api.internalActions, sliceActions)
const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>()
const getInternalState = (dispatch: Dispatch) => {
const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
currentSubscriptions: new Map(),
currentPolls: new Map(),
runningQueries: new Map(),
runningMutations: new Map(),
}))
return state
}
const {
buildInitiateQuery,
buildInitiateInfiniteQuery,
buildInitiateMutation,
getRunningMutationThunk,
getRunningMutationsThunk,
getRunningQueriesThunk,
getRunningQueryThunk,
} = buildInitiate({
queryThunk,
mutationThunk,
infiniteQueryThunk,
api,
serializeQueryArgs: serializeQueryArgs as any,
context,
getInternalState,
})
safeAssign(api.util, {
getRunningMutationThunk,
getRunningMutationsThunk,
getRunningQueryThunk,
getRunningQueriesThunk,
})
const { middleware, actions: middlewareActions } = buildMiddleware({
reducerPath,
context,
queryThunk,
mutationThunk,
infiniteQueryThunk,
api,
assertTagType,
selectors,
getRunningQueryThunk,
getInternalState,
})
safeAssign(api.util, middlewareActions)
safeAssign(api, { reducer: reducer as any, middleware })
return {
name: coreModuleName,
injectEndpoint(endpointName, definition) {
const anyApi = api as any as Api<
any,
Record<string, any>,
string,
string,
CoreModule
>
const endpoint = (anyApi.endpoints[endpointName] ??= {} as any)
if (isQueryDefinition(definition)) {
safeAssign(
endpoint,
{
name: endpointName,
select: buildQuerySelector(endpointName, definition),
initiate: buildInitiateQuery(endpointName, definition),
},
buildMatchThunkActions(queryThunk, endpointName),
)
}
if (isMutationDefinition(definition)) {
safeAssign(
endpoint,
{
name: endpointName,
select: buildMutationSelector(),
initiate: buildInitiateMutation(endpointName),
},
buildMatchThunkActions(mutationThunk, endpointName),
)
}
if (isInfiniteQueryDefinition(definition)) {
safeAssign(
endpoint,
{
name: endpointName,
select: buildInfiniteQuerySelector(endpointName, definition),
initiate: buildInitiateInfiniteQuery(endpointName, definition),
},
buildMatchThunkActions(queryThunk, endpointName),
)
}
},
}
},
})

View File

@@ -0,0 +1,24 @@
// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.
// ESBuild does not de-duplicate imports, so this file is used to ensure that each method
// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.
export {
createAction,
createSlice,
createSelector,
createAsyncThunk,
combineReducers,
createNextState,
isAnyOf,
isAllOf,
isAction,
isPending,
isRejected,
isFulfilled,
isRejectedWithValue,
isAsyncThunkAction,
prepareAutoBatched,
SHOULD_AUTOBATCH,
isPlainObject,
nanoid,
} from '@reduxjs/toolkit'

View File

@@ -0,0 +1,118 @@
import type {
ThunkDispatch,
ActionCreatorWithoutPayload, // Workaround for API-Extractor
} from '@reduxjs/toolkit'
import { createAction } from './rtkImports'
export const INTERNAL_PREFIX = '__rtkq/'
const ONLINE = 'online'
const OFFLINE = 'offline'
const FOCUS = 'focus'
const FOCUSED = 'focused'
const VISIBILITYCHANGE = 'visibilitychange'
export const onFocus = /* @__PURE__ */ createAction(
`${INTERNAL_PREFIX}${FOCUSED}`,
)
export const onFocusLost = /* @__PURE__ */ createAction(
`${INTERNAL_PREFIX}un${FOCUSED}`,
)
export const onOnline = /* @__PURE__ */ createAction(
`${INTERNAL_PREFIX}${ONLINE}`,
)
export const onOffline = /* @__PURE__ */ createAction(
`${INTERNAL_PREFIX}${OFFLINE}`,
)
const actions = {
onFocus,
onFocusLost,
onOnline,
onOffline,
}
let initialized = false
/**
* A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
* It requires the dispatch method from your store.
* Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
* but you have the option of providing a callback for more granular control.
*
* @example
* ```ts
* setupListeners(store.dispatch)
* ```
*
* @param dispatch - The dispatch method from your store
* @param customHandler - An optional callback for more granular control over listener behavior
* @returns Return value of the handler.
* The default handler returns an `unsubscribe` method that can be called to remove the listeners.
*/
export function setupListeners(
dispatch: ThunkDispatch<any, any, any>,
customHandler?: (
dispatch: ThunkDispatch<any, any, any>,
actions: {
onFocus: typeof onFocus
onFocusLost: typeof onFocusLost
onOnline: typeof onOnline
onOffline: typeof onOffline
},
) => () => void,
) {
function defaultHandler() {
const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [
onFocus,
onFocusLost,
onOnline,
onOffline,
].map((action) => () => dispatch(action()))
const handleVisibilityChange = () => {
if (window.document.visibilityState === 'visible') {
handleFocus()
} else {
handleFocusLost()
}
}
let unsubscribe = () => {
initialized = false
}
if (!initialized) {
if (typeof window !== 'undefined' && window.addEventListener) {
const handlers = {
[FOCUS]: handleFocus,
[VISIBILITYCHANGE]: handleVisibilityChange,
[ONLINE]: handleOnline,
[OFFLINE]: handleOffline,
}
function updateListeners(add: boolean) {
Object.entries(handlers).forEach(([event, handler]) => {
if (add) {
window.addEventListener(event, handler, false)
} else {
window.removeEventListener(event, handler)
}
})
}
// Handle focus events
updateListeners(true)
initialized = true
unsubscribe = () => {
updateListeners(false)
initialized = false
}
}
}
return unsubscribe
}
return customHandler ? customHandler(dispatch, actions) : defaultHandler()
}

View File

@@ -0,0 +1,514 @@
import {
getEndpointDefinition,
type Api,
type ApiContext,
type Module,
type ModuleName,
} from './apiTypes'
import type { CombinedState } from './core/apiState'
import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'
import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
import { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
import type {
EndpointBuilder,
EndpointDefinitions,
SchemaFailureConverter,
SchemaFailureHandler,
SchemaType,
} from './endpointDefinitions'
import {
DefinitionType,
ENDPOINT_INFINITEQUERY,
ENDPOINT_MUTATION,
ENDPOINT_QUERY,
isInfiniteQueryDefinition,
isQueryDefinition,
} from './endpointDefinitions'
import { nanoid } from './core/rtkImports'
import type { UnknownAction } from '@reduxjs/toolkit'
import type { NoInfer } from './tsHelpers'
import { weakMapMemoize } from 'reselect'
export interface CreateApiOptions<
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
ReducerPath extends string = 'api',
TagTypes extends string = never,
> {
/**
* 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.
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* const api = createApi({
* // highlight-start
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-end
* endpoints: (build) => ({
* // ...endpoints
* }),
* })
* ```
*/
baseQuery: BaseQuery
/**
* 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).
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* tagTypes: ['Post', 'User'],
* // highlight-end
* endpoints: (build) => ({
* // ...endpoints
* }),
* })
* ```
*/
tagTypes?: readonly TagTypes[]
/**
* 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'`.
*
* @example
*
* ```ts
* // codeblock-meta title="apis.js"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
*
* const apiOne = createApi({
* // highlight-start
* reducerPath: 'apiOne',
* // highlight-end
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (builder) => ({
* // ...endpoints
* }),
* });
*
* const apiTwo = createApi({
* // highlight-start
* reducerPath: 'apiTwo',
* // highlight-end
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (builder) => ({
* // ...endpoints
* }),
* });
* ```
*/
reducerPath?: ReducerPath
/**
* Accepts a custom function if you have a need to change the creation of cache keys for any reason.
*/
serializeQueryArgs?: SerializeQueryArgs<unknown>
/**
* 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).
*/
endpoints(
build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
): Definitions
/**
* 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.
*
* @example
* ```ts
* // codeblock-meta title="keepUnusedDataFor example"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts'
* })
* }),
* // highlight-start
* keepUnusedDataFor: 5
* // highlight-end
* })
* ```
*/
keepUnusedDataFor?: number
/**
* 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.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `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.
* - `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.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number
/**
* 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.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnFocus?: boolean
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnReconnect?: boolean
/**
* Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.
*
* - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.
* If the query provides tags that were invalidated while it ran, it won't be re-fetched.
* - `'delayed'`: Invalidation only happens after all queries and mutations are settled.
* This ensures that queries are always invalidated correctly and automatically "batches" invalidations of concurrent mutations.
* Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.
*/
invalidationBehavior?: 'delayed' | 'immediately'
/**
* A function that is passed every dispatched action. If this returns something other than `undefined`,
* that return value will be used to rehydrate fulfilled & errored queries.
*
* @example
*
* ```ts
* // codeblock-meta title="next-redux-wrapper rehydration example"
* import type { Action, PayloadAction } from '@reduxjs/toolkit'
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* import { HYDRATE } from 'next-redux-wrapper'
*
* type RootState = any; // normally inferred from state
*
* function isHydrateAction(action: Action): action is PayloadAction<RootState> {
* return action.type === HYDRATE
* }
*
* export const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* extractRehydrationInfo(action, { reducerPath }): any {
* if (isHydrateAction(action)) {
* return action.payload[reducerPath]
* }
* },
* // highlight-end
* endpoints: (build) => ({
* // omitted
* }),
* })
* ```
*/
extractRehydrationInfo?: (
action: UnknownAction,
{
reducerPath,
}: {
reducerPath: ReducerPath
},
) =>
| undefined
| CombinedState<
NoInfer<Definitions>,
NoInfer<TagTypes>,
NoInfer<ReducerPath>
>
/**
* A function that is called when a schema validation fails.
*
* Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).
*
* `NamedSchemaError` has the following properties:
* - `issues`: an array of issues that caused the validation to fail
* - `value`: the value that was passed to the schema
* - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)
*
* @example
* ```ts
* // codeblock-meta no-transpile
* import { createApi } from '@reduxjs/toolkit/query/react'
* import * as v from "valibot"
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPost: build.query<Post, { id: number }>({
* query: ({ id }) => `/post/${id}`,
* }),
* }),
* onSchemaFailure: (error, info) => {
* console.error(error, info)
* },
* })
* ```
*/
onSchemaFailure?: SchemaFailureHandler
/**
* Convert a schema validation failure into an error shape matching base query errors.
*
* When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.
*
* @example
* ```ts
* // codeblock-meta no-transpile
* import { createApi } from '@reduxjs/toolkit/query/react'
* import * as v from "valibot"
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPost: build.query<Post, { id: number }>({
* query: ({ id }) => `/post/${id}`,
* responseSchema: v.object({ id: v.number(), name: v.string() }),
* }),
* }),
* catchSchemaFailure: (error, info) => ({
* status: "CUSTOM_ERROR",
* error: error.schemaName + " failed validation",
* data: error.issues,
* }),
* })
* ```
*/
catchSchemaFailure?: SchemaFailureConverter<BaseQuery>
/**
* Defaults to `false`.
*
* If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.
*
* Can be overridden for specific schemas by passing an array of schema types to skip.
*
* @example
* ```ts
* // codeblock-meta no-transpile
* import { createApi } from '@reduxjs/toolkit/query/react'
* import * as v from "valibot"
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* skipSchemaValidation: process.env.NODE_ENV === "test" ? ["response"] : false, // skip schema validation for response in tests, since we'll be mocking the response
* endpoints: (build) => ({
* getPost: build.query<Post, { id: number }>({
* query: ({ id }) => `/post/${id}`,
* responseSchema: v.object({ id: v.number(), name: v.string() }),
* }),
* })
* })
* ```
*/
skipSchemaValidation?: boolean | SchemaType[]
}
export type CreateApi<Modules extends ModuleName> = {
/**
* Creates a service to use in your application. Contains only the basic redux logic (the core module).
*
* @link https://redux-toolkit.js.org/rtk-query/api/createApi
*/
<
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
ReducerPath extends string = 'api',
TagTypes extends string = never,
>(
options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>
}
/**
* Builds a `createApi` method based on the provided `modules`.
*
* @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue | null>(null);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({
* hooks: {
* useDispatch: createDispatchHook(MyContext),
* useSelector: createSelectorHook(MyContext),
* useStore: createStoreHook(MyContext)
* }
* })
* );
* ```
*
* @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
* @returns A `createApi` method using the provided `modules`.
*/
export function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(
...modules: Modules
): CreateApi<Modules[number]['name']> {
return function baseCreateApi(options) {
const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) =>
options.extractRehydrationInfo?.(action, {
reducerPath: (options.reducerPath ?? 'api') as any,
}),
)
const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {
reducerPath: 'api',
keepUnusedDataFor: 60,
refetchOnMountOrArgChange: false,
refetchOnFocus: false,
refetchOnReconnect: false,
invalidationBehavior: 'delayed',
...options,
extractRehydrationInfo,
serializeQueryArgs(queryArgsApi) {
let finalSerializeQueryArgs = defaultSerializeQueryArgs
if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {
const endpointSQA =
queryArgsApi.endpointDefinition.serializeQueryArgs!
finalSerializeQueryArgs = (queryArgsApi) => {
const initialResult = endpointSQA(queryArgsApi)
if (typeof initialResult === 'string') {
// If the user function returned a string, use it as-is
return initialResult
} else {
// Assume they returned an object (such as a subset of the original
// query args) or a primitive, and serialize it ourselves
return defaultSerializeQueryArgs({
...queryArgsApi,
queryArgs: initialResult,
})
}
}
} else if (options.serializeQueryArgs) {
finalSerializeQueryArgs = options.serializeQueryArgs
}
return finalSerializeQueryArgs(queryArgsApi)
},
tagTypes: [...(options.tagTypes || [])],
}
const context: ApiContext<EndpointDefinitions> = {
endpointDefinitions: {},
batch(fn) {
// placeholder "batch" method to be overridden by plugins, for example with React.unstable_batchedUpdate
fn()
},
apiUid: nanoid(),
extractRehydrationInfo,
hasRehydrationInfo: weakMapMemoize(
(action) => extractRehydrationInfo(action) != null,
),
}
const api = {
injectEndpoints,
enhanceEndpoints({ addTagTypes, endpoints }) {
if (addTagTypes) {
for (const eT of addTagTypes) {
if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {
;(optionsWithDefaults.tagTypes as any[]).push(eT)
}
}
}
if (endpoints) {
for (const [endpointName, partialDefinition] of Object.entries(
endpoints,
)) {
if (typeof partialDefinition === 'function') {
partialDefinition(getEndpointDefinition(context, endpointName))
} else {
Object.assign(
getEndpointDefinition(context, endpointName) || {},
partialDefinition,
)
}
}
}
return api
},
} as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>
const initializedModules = modules.map((m) =>
m.init(api as any, optionsWithDefaults as any, context),
)
function injectEndpoints(
inject: Parameters<typeof api.injectEndpoints>[0],
) {
const evaluatedEndpoints = inject.endpoints({
query: (x) => ({ ...x, type: ENDPOINT_QUERY }) as any,
mutation: (x) => ({ ...x, type: ENDPOINT_MUTATION }) as any,
infiniteQuery: (x) => ({ ...x, type: ENDPOINT_INFINITEQUERY }) as any,
})
for (const [endpointName, definition] of Object.entries(
evaluatedEndpoints,
)) {
if (
inject.overrideExisting !== true &&
endpointName in context.endpointDefinitions
) {
if (inject.overrideExisting === 'throw') {
throw new Error(
`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
)
} else if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
console.error(
`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
)
}
continue
}
if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
if (isInfiniteQueryDefinition(definition)) {
const { infiniteQueryOptions } = definition
const { maxPages, getPreviousPageParam } = infiniteQueryOptions
if (typeof maxPages === 'number') {
if (maxPages < 1) {
throw new Error(
`maxPages for endpoint '${endpointName}' must be a number greater than 0`,
)
}
if (typeof getPreviousPageParam !== 'function') {
throw new Error(
`getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`,
)
}
}
}
}
context.endpointDefinitions[endpointName] = definition
for (const m of initializedModules) {
m.injectEndpoint(endpointName, definition)
}
}
return api as any
}
return api.injectEndpoints({ endpoints: options.endpoints as any })
}
}

View File

@@ -0,0 +1,52 @@
import type { QueryCacheKey } from './core/apiState'
import type { EndpointDefinition } from './endpointDefinitions'
import { isPlainObject } from './core/rtkImports'
const cache: WeakMap<any, string> | undefined = WeakMap
? new WeakMap()
: undefined
export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
endpointName,
queryArgs,
}) => {
let serialized = ''
const cached = cache?.get(queryArgs)
if (typeof cached === 'string') {
serialized = cached
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
// Handle bigints
value = typeof value === 'bigint' ? { $bigint: value.toString() } : value
// Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
value = isPlainObject(value)
? Object.keys(value)
.sort()
.reduce<any>((acc, key) => {
acc[key] = (value as any)[key]
return acc
}, {})
: value
return value
})
if (isPlainObject(queryArgs)) {
cache?.set(queryArgs, stringified)
}
serialized = stringified
}
return `${endpointName}(${serialized})`
}
export type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
queryArgs: QueryArgs
endpointDefinition: EndpointDefinition<any, any, any, any>
endpointName: string
}) => ReturnType
export type InternalSerializeQueryArgs = (_: {
queryArgs: any
endpointDefinition: EndpointDefinition<any, any, any, any>
endpointName: string
}) => QueryCacheKey

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
import type { BaseQueryFn } from './baseQueryTypes'
export const _NEVER = /* @__PURE__ */ Symbol()
export type NEVER = typeof _NEVER
/**
* Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
* This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
*/
export function fakeBaseQuery<ErrorType>(): BaseQueryFn<
void,
NEVER,
ErrorType,
{}
> {
return function () {
throw new Error(
'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
)
}
}

View File

@@ -0,0 +1,397 @@
import { joinUrls } from './utils'
import { isPlainObject } from './core/rtkImports'
import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'
import type { MaybePromise, Override } from './tsHelpers'
export type ResponseHandler =
| 'content-type'
| 'json'
| 'text'
| ((response: Response) => Promise<any>)
type CustomRequestInit = Override<
RequestInit,
{
headers?:
| Headers
| string[][]
| Record<string, string | undefined>
| undefined
}
>
export interface FetchArgs extends CustomRequestInit {
url: string
params?: Record<string, any>
body?: any
responseHandler?: ResponseHandler
validateStatus?: (response: Response, body: any) => boolean
/**
* A number in milliseconds that represents that maximum time a request can take before timing out.
*/
timeout?: number
}
/**
* A mini-wrapper that passes arguments straight through to
* {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.
* Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.
*/
const defaultFetchFn: typeof fetch = (...args) => fetch(...args)
const defaultValidateStatus = (response: Response) =>
response.status >= 200 && response.status <= 299
const defaultIsJsonContentType = (headers: Headers) =>
/*applicat*/ /ion\/(vnd\.api\+)?json/.test(headers.get('content-type') || '')
export type FetchBaseQueryError =
| {
/**
* * `number`:
* HTTP status code
*/
status: number
data: unknown
}
| {
/**
* * `"FETCH_ERROR"`:
* An error that occurred during execution of `fetch` or the `fetchFn` callback option
**/
status: 'FETCH_ERROR'
data?: undefined
error: string
}
| {
/**
* * `"PARSING_ERROR"`:
* An error happened during parsing.
* Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
* or an error occurred while executing a custom `responseHandler`.
**/
status: 'PARSING_ERROR'
originalStatus: number
data: string
error: string
}
| {
/**
* * `"TIMEOUT_ERROR"`:
* Request timed out
**/
status: 'TIMEOUT_ERROR'
data?: undefined
error: string
}
| {
/**
* * `"CUSTOM_ERROR"`:
* A custom error type that you can return from your `queryFn` where another error might not make sense.
**/
status: 'CUSTOM_ERROR'
data?: unknown
error: string
}
function stripUndefined(obj: any) {
if (!isPlainObject(obj)) {
return obj
}
const copy: Record<string, any> = { ...obj }
for (const [k, v] of Object.entries(copy)) {
if (v === undefined) delete copy[k]
}
return copy
}
// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.
const isJsonifiable = (body: any) =>
typeof body === 'object' &&
(isPlainObject(body) ||
Array.isArray(body) ||
typeof body.toJSON === 'function')
export type FetchBaseQueryArgs = {
baseUrl?: string
prepareHeaders?: (
headers: Headers,
api: Pick<
BaseQueryApi,
'getState' | 'extra' | 'endpoint' | 'type' | 'forced'
> & { arg: string | FetchArgs; extraOptions: unknown },
) => MaybePromise<Headers | void>
fetchFn?: (
input: RequestInfo,
init?: RequestInit | undefined,
) => Promise<Response>
paramsSerializer?: (params: Record<string, any>) => string
/**
* By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass
* in a predicate function for your given api to get the same automatic stringifying behavior
* @example
* ```ts
* const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
* ```
*/
isJsonContentType?: (headers: Headers) => boolean
/**
* Defaults to `application/json`;
*/
jsonContentType?: string
/**
* Custom replacer function used when calling `JSON.stringify()`;
*/
jsonReplacer?: (this: any, key: string, value: any) => any
} & RequestInit &
Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>
export type FetchBaseQueryMeta = { request: Request; response?: Response }
/**
* This is a very small wrapper around fetch that aims to simplify requests.
*
* @example
* ```ts
* const baseQuery = fetchBaseQuery({
* baseUrl: 'https://api.your-really-great-app.com/v1/',
* prepareHeaders: (headers, { getState }) => {
* const token = (getState() as RootState).auth.token;
* // If we have a token set in state, let's assume that we should be passing it.
* if (token) {
* headers.set('authorization', `Bearer ${token}`);
* }
* return headers;
* },
* })
* ```
*
* @param {string} baseUrl
* The base URL for an API service.
* Typically in the format of https://example.com/
*
* @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
* An optional function that can be used to inject headers on requests.
* Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.
* Useful for setting authentication or headers that need to be set conditionally.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
*
* @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
* Accepts a custom `fetch` function if you do not want to use the default on the window.
* Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
*
* @param {(params: Record<string, unknown>) => string} paramsSerializer
* An optional function that can be used to stringify querystring parameters.
*
* @param {(headers: Headers) => boolean} isJsonContentType
* An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
*
* @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.
*
* @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
*
* @param {number} timeout
* A number in milliseconds that represents the maximum time a request can take before timing out.
*/
export function fetchBaseQuery({
baseUrl,
prepareHeaders = (x) => x,
fetchFn = defaultFetchFn,
paramsSerializer,
isJsonContentType = defaultIsJsonContentType,
jsonContentType = 'application/json',
jsonReplacer,
timeout: defaultTimeout,
responseHandler: globalResponseHandler,
validateStatus: globalValidateStatus,
...baseFetchOptions
}: FetchBaseQueryArgs = {}): BaseQueryFn<
string | FetchArgs,
unknown,
FetchBaseQueryError,
{},
FetchBaseQueryMeta
> {
if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {
console.warn(
'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.',
)
}
return async (arg, api, extraOptions) => {
const { getState, extra, endpoint, forced, type } = api
let meta: FetchBaseQueryMeta | undefined
let {
url,
headers = new Headers(baseFetchOptions.headers),
params = undefined,
responseHandler = globalResponseHandler ?? ('json' as const),
validateStatus = globalValidateStatus ?? defaultValidateStatus,
timeout = defaultTimeout,
...rest
} = typeof arg == 'string' ? { url: arg } : arg
let abortController: AbortController | undefined,
signal = api.signal
if (timeout) {
abortController = new AbortController()
api.signal.addEventListener('abort', abortController.abort)
signal = abortController.signal
}
let config: RequestInit = {
...baseFetchOptions,
signal,
...rest,
}
headers = new Headers(stripUndefined(headers))
config.headers =
(await prepareHeaders(headers, {
getState,
arg,
extra,
endpoint,
forced,
type,
extraOptions,
})) || headers
const bodyIsJsonifiable = isJsonifiable(config.body)
// Remove content-type for non-jsonifiable bodies to let the browser set it automatically
// Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)
if (
config.body != null &&
!bodyIsJsonifiable &&
typeof config.body !== 'string'
) {
config.headers.delete('content-type')
}
if (!config.headers.has('content-type') && bodyIsJsonifiable) {
config.headers.set('content-type', jsonContentType)
}
if (bodyIsJsonifiable && isJsonContentType(config.headers)) {
config.body = JSON.stringify(config.body, jsonReplacer)
}
// Set Accept header based on responseHandler if not already set
if (!config.headers.has('accept')) {
if (responseHandler === 'json') {
config.headers.set('accept', 'application/json')
} else if (responseHandler === 'text') {
config.headers.set('accept', 'text/plain, text/html, */*')
}
// For 'content-type' responseHandler, don't set Accept (let server decide)
}
if (params) {
const divider = ~url.indexOf('?') ? '&' : '?'
const query = paramsSerializer
? paramsSerializer(params)
: new URLSearchParams(stripUndefined(params))
url += divider + query
}
url = joinUrls(baseUrl, url)
const request = new Request(url, config)
const requestClone = new Request(url, config)
meta = { request: requestClone }
let response,
timedOut = false,
timeoutId =
abortController &&
setTimeout(() => {
timedOut = true
abortController!.abort()
}, timeout)
try {
response = await fetchFn(request)
} catch (e) {
return {
error: {
status: timedOut ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',
error: String(e),
},
meta,
}
} finally {
if (timeoutId) clearTimeout(timeoutId)
abortController?.signal.removeEventListener(
'abort',
abortController.abort,
)
}
const responseClone = response.clone()
meta.response = responseClone
let resultData: any
let responseText: string = ''
try {
let handleResponseError
await Promise.all([
handleResponse(response, responseHandler).then(
(r) => (resultData = r),
(e) => (handleResponseError = e),
),
// see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
// we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
responseClone.text().then(
(r) => (responseText = r),
() => {},
),
])
if (handleResponseError) throw handleResponseError
} catch (e) {
return {
error: {
status: 'PARSING_ERROR',
originalStatus: response.status,
data: responseText,
error: String(e),
},
meta,
}
}
return validateStatus(response, resultData)
? {
data: resultData,
meta,
}
: {
error: {
status: response.status,
data: resultData,
},
meta,
}
}
async function handleResponse(
response: Response,
responseHandler: ResponseHandler,
) {
if (typeof responseHandler === 'function') {
return responseHandler(response)
}
if (responseHandler === 'content-type') {
responseHandler = isJsonContentType(response.headers) ? 'json' : 'text'
}
if (responseHandler === 'json') {
const text = await response.text()
return text.length ? JSON.parse(text) : null
}
return response.text()
}
}

View File

@@ -0,0 +1,106 @@
// This must remain here so that the `mangleErrors.cjs` build script
// does not have to import this into each source file it rewrites.
import { formatProdErrorMessage } from '@reduxjs/toolkit'
export type {
CombinedState,
QueryCacheKey,
QueryKeys,
QuerySubState,
RootState,
SubscriptionOptions,
} from './core/apiState'
export { QueryStatus } from './core/apiState'
export type { Api, ApiContext, Module } from './apiTypes'
export type {
BaseQueryApi,
BaseQueryArg,
BaseQueryEnhancer,
BaseQueryError,
BaseQueryExtraOptions,
BaseQueryFn,
BaseQueryMeta,
BaseQueryResult,
QueryReturnValue,
} from './baseQueryTypes'
export type {
BaseEndpointDefinition,
EndpointDefinitions,
EndpointDefinition,
EndpointBuilder,
QueryDefinition,
MutationDefinition,
MutationExtraOptions,
InfiniteQueryArgFrom,
InfiniteQueryDefinition,
InfiniteQueryExtraOptions,
PageParamFrom,
TagDescription,
QueryArgFrom,
QueryExtraOptions,
ResultTypeFrom,
DefinitionType,
DefinitionsFromApi,
OverrideResultType,
ResultDescription,
TagTypesFromApi,
UpdateDefinitions,
SchemaFailureHandler,
SchemaFailureConverter,
SchemaFailureInfo,
SchemaType,
} from './endpointDefinitions'
export { fetchBaseQuery } from './fetchBaseQuery'
export type {
FetchBaseQueryArgs,
FetchBaseQueryError,
FetchBaseQueryMeta,
FetchArgs,
} from './fetchBaseQuery'
export { retry } from './retry'
export type { RetryOptions } from './retry'
export { setupListeners } from './core/setupListeners'
export { skipToken } from './core/buildSelectors'
export type {
QueryResultSelectorResult,
MutationResultSelectorResult,
SkipToken,
} from './core/buildSelectors'
export type {
QueryActionCreatorResult,
MutationActionCreatorResult,
StartQueryActionCreatorOptions,
} from './core/buildInitiate'
export type { CreateApi, CreateApiOptions } from './createApi'
export { buildCreateApi } from './createApi'
export { _NEVER, fakeBaseQuery } from './fakeBaseQuery'
export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing'
export { createApi, coreModule, coreModuleName } from './core/index'
export type {
InfiniteData,
InfiniteQueryActionCreatorResult,
InfiniteQueryConfigOptions,
InfiniteQueryResultSelectorResult,
InfiniteQuerySubState,
TypedMutationOnQueryStarted,
TypedQueryOnQueryStarted,
} from './core/index'
export type {
ApiEndpointMutation,
ApiEndpointQuery,
ApiEndpointInfiniteQuery,
ApiModules,
CoreModule,
PrefetchOptions,
} from './core/module'
export { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
export type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
export type {
Id as TSHelpersId,
NoInfer as TSHelpersNoInfer,
Override as TSHelpersOverride,
} from './tsHelpers'
export { NamedSchemaError } from './standardSchema'

View File

@@ -0,0 +1,69 @@
import { configureStore } from '@reduxjs/toolkit'
import type { Context } from 'react'
import { useContext, useEffect } from './reactImports'
import * as React from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import { Provider, ReactReduxContext } from './reactReduxImports'
import { setupListeners } from './rtkqImports'
import type { Api } from '@reduxjs/toolkit/query'
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
export function ApiProvider(props: {
children: any
api: Api<any, {}, any, any>
setupListeners?: Parameters<typeof setupListeners>[1] | false
context?: Context<ReactReduxContextValue | null>
}) {
const context = props.context || ReactReduxContext
const existingContext = useContext(context)
if (existingContext) {
throw new Error(
'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.',
)
}
const [store] = React.useState(() =>
configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer,
},
middleware: (gDM) => gDM().concat(props.api.middleware),
}),
)
// Adds the event listeners for online/offline/focus/etc
useEffect(
(): undefined | (() => void) =>
props.setupListeners === false
? undefined
: setupListeners(store.dispatch, props.setupListeners),
[props.setupListeners, store.dispatch],
)
return (
<Provider store={store} context={context}>
{props.children}
</Provider>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
export const UNINITIALIZED_VALUE = Symbol()
export type UninitializedValue = typeof UNINITIALIZED_VALUE

View File

@@ -0,0 +1,43 @@
// This must remain here so that the `mangleErrors.cjs` build script
// does not have to import this into each source file it rewrites.
import { formatProdErrorMessage } from '@reduxjs/toolkit'
import { buildCreateApi, coreModule } from './rtkqImports'
import { reactHooksModule, reactHooksModuleName } from './module'
export * from '@reduxjs/toolkit/query'
export { ApiProvider } from './ApiProvider'
const createApi = /* @__PURE__ */ buildCreateApi(
coreModule(),
reactHooksModule(),
)
export type {
TypedUseMutationResult,
TypedUseQueryHookResult,
TypedUseQueryStateResult,
TypedUseQuerySubscriptionResult,
TypedLazyQueryTrigger,
TypedUseLazyQuery,
TypedUseMutation,
TypedMutationTrigger,
TypedQueryStateSelector,
TypedUseQueryState,
TypedUseQuery,
TypedUseQuerySubscription,
TypedUseLazyQuerySubscription,
TypedUseQueryStateOptions,
TypedUseLazyQueryStateResult,
TypedUseInfiniteQuery,
TypedUseInfiniteQueryHookResult,
TypedUseInfiniteQueryStateResult,
TypedUseInfiniteQuerySubscriptionResult,
TypedUseInfiniteQueryStateOptions,
TypedInfiniteQueryStateSelector,
TypedUseInfiniteQuerySubscription,
TypedUseInfiniteQueryState,
TypedLazyInfiniteQueryTrigger,
} from './buildHooks'
export { UNINITIALIZED_VALUE } from './constants'
export { createApi, reactHooksModule, reactHooksModuleName }

View File

@@ -0,0 +1,274 @@
import type {
Api,
BaseQueryFn,
EndpointDefinitions,
InfiniteQueryDefinition,
Module,
MutationDefinition,
PrefetchOptions,
QueryArgFrom,
QueryDefinition,
QueryKeys,
} from '@reduxjs/toolkit/query'
import {
batch as rrBatch,
useDispatch as rrUseDispatch,
useSelector as rrUseSelector,
useStore as rrUseStore,
} from 'react-redux'
import { createSelector as _createSelector } from 'reselect'
import {
isInfiniteQueryDefinition,
isMutationDefinition,
isQueryDefinition,
} from '../endpointDefinitions'
import { safeAssign } from '../tsHelpers'
import { capitalize, countObjectKeys } from '../utils'
import type {
InfiniteQueryHooks,
MutationHooks,
QueryHooks,
} from './buildHooks'
import { buildHooks } from './buildHooks'
import type { HooksWithUniqueNames } from './namedHooks'
export const reactHooksModuleName = /* @__PURE__ */ Symbol()
export type ReactHooksModule = typeof reactHooksModuleName
declare module '@reduxjs/toolkit/query' {
export interface ApiModules<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
ReducerPath extends string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
TagTypes extends string,
> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<
any,
any,
any,
any,
any
>
? QueryHooks<Definitions[K]>
: Definitions[K] extends MutationDefinition<any, any, any, any, any>
? MutationHooks<Definitions[K]>
: Definitions[K] extends InfiniteQueryDefinition<
any,
any,
any,
any,
any
>
? InfiniteQueryHooks<Definitions[K]>
: never
}
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(
endpointName: EndpointName,
options?: PrefetchOptions,
): (
arg: QueryArgFrom<Definitions[EndpointName]>,
options?: PrefetchOptions,
) => void
} & HooksWithUniqueNames<Definitions>
}
}
type RR = typeof import('react-redux')
export interface ReactHooksModuleOptions {
/**
* The hooks from React Redux to be used
*/
hooks?: {
/**
* The version of the `useDispatch` hook to be used
*/
useDispatch: RR['useDispatch']
/**
* The version of the `useSelector` hook to be used
*/
useSelector: RR['useSelector']
/**
* The version of the `useStore` hook to be used
*/
useStore: RR['useStore']
}
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch']
/**
* Enables performing asynchronous tasks immediately within a render.
*
* @example
*
* ```ts
* import {
* buildCreateApi,
* coreModule,
* reactHooksModule
* } from '@reduxjs/toolkit/query/react'
*
* const createApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ unstable__sideEffectsInRender: true })
* )
* ```
*/
unstable__sideEffectsInRender?: boolean
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof _createSelector
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue | null>(null);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({
* hooks: {
* useDispatch: createDispatchHook(MyContext),
* useSelector: createSelectorHook(MyContext),
* useStore: createStoreHook(MyContext)
* }
* })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
export const reactHooksModule = ({
batch = rrBatch,
hooks = {
useDispatch: rrUseDispatch,
useSelector: rrUseSelector,
useStore: rrUseStore,
},
createSelector = _createSelector,
unstable__sideEffectsInRender = false,
...rest
}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {
if (process.env.NODE_ENV !== 'production') {
const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const
let warned = false
for (const hookName of hookNames) {
// warn for old hook options
if (countObjectKeys(rest) > 0) {
if ((rest as Partial<typeof hooks>)[hookName]) {
if (!warned) {
console.warn(
'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' +
'\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`',
)
warned = true
}
}
// migrate
// @ts-ignore
hooks[hookName] = rest[hookName]
}
// then make sure we have them all
if (typeof hooks[hookName] !== 'function') {
throw new Error(
`When using custom hooks for context, all ${
hookNames.length
} hooks need to be provided: ${hookNames.join(
', ',
)}.\nHook ${hookName} was either not provided or not a function.`,
)
}
}
}
return {
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api as any as Api<
any,
Record<string, any>,
any,
any,
ReactHooksModule
>
const {
buildQueryHooks,
buildInfiniteQueryHooks,
buildMutationHook,
usePrefetch,
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector,
},
serializeQueryArgs,
context,
})
safeAssign(anyApi, { usePrefetch })
safeAssign(context, { batch })
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription,
} = buildQueryHooks(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription,
})
;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery
;(api as any)[`useLazy${capitalize(endpointName)}Query`] =
useLazyQuery
}
if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useMutation,
})
;(api as any)[`use${capitalize(endpointName)}Mutation`] =
useMutation
} else if (isInfiniteQueryDefinition(definition)) {
const {
useInfiniteQuery,
useInfiniteQuerySubscription,
useInfiniteQueryState,
} = buildInfiniteQueryHooks(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useInfiniteQuery,
useInfiniteQuerySubscription,
useInfiniteQueryState,
})
;(api as any)[`use${capitalize(endpointName)}InfiniteQuery`] =
useInfiniteQuery
}
},
}
},
}
}

View File

@@ -0,0 +1,59 @@
import type {
DefinitionType,
EndpointDefinitions,
MutationDefinition,
QueryDefinition,
InfiniteQueryDefinition,
} from '@reduxjs/toolkit/query'
import type {
UseInfiniteQuery,
UseLazyQuery,
UseMutation,
UseQuery,
} from './buildHooks'
type QueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query
}
? `use${Capitalize<K & string>}Query`
: never]: UseQuery<
Extract<Definitions[K], QueryDefinition<any, any, any, any>>
>
}
type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query
}
? `useLazy${Capitalize<K & string>}Query`
: never]: UseLazyQuery<
Extract<Definitions[K], QueryDefinition<any, any, any, any>>
>
}
type InfiniteQueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.infinitequery
}
? `use${Capitalize<K & string>}InfiniteQuery`
: never]: UseInfiniteQuery<
Extract<Definitions[K], InfiniteQueryDefinition<any, any, any, any, any>>
>
}
type MutationHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.mutation
}
? `use${Capitalize<K & string>}Mutation`
: never]: UseMutation<
Extract<Definitions[K], MutationDefinition<any, any, any, any>>
>
}
export type HooksWithUniqueNames<Definitions extends EndpointDefinitions> =
QueryHookNames<Definitions> &
LazyQueryHookNames<Definitions> &
InfiniteQueryHookNames<Definitions> &
MutationHookNames<Definitions>

View File

@@ -0,0 +1,10 @@
export {
useEffect,
useRef,
useMemo,
useContext,
useCallback,
useDebugValue,
useLayoutEffect,
useState,
} from 'react'

View File

@@ -0,0 +1 @@
export { shallowEqual, Provider, ReactReduxContext } from 'react-redux'

View File

@@ -0,0 +1,8 @@
export {
buildCreateApi,
coreModule,
copyWithStructuralSharing,
setupListeners,
QueryStatus,
skipToken,
} from '@reduxjs/toolkit/query'

View File

@@ -0,0 +1,17 @@
import { useEffect, useRef, useMemo } from './reactImports'
import { copyWithStructuralSharing } from './rtkqImports'
export function useStableQueryArgs<T>(queryArgs: T) {
const cache = useRef(queryArgs)
const copy = useMemo(
() => copyWithStructuralSharing(cache.current, queryArgs),
[queryArgs],
)
useEffect(() => {
if (cache.current !== copy) {
cache.current = copy
}
}, [copy])
return copy
}

View File

@@ -0,0 +1,13 @@
import { useEffect, useRef } from './reactImports'
import { shallowEqual } from './reactReduxImports'
export function useShallowStableValue<T>(value: T) {
const cache = useRef(value)
useEffect(() => {
if (!shallowEqual(cache.current, value)) {
cache.current = value
}
}, [value])
return shallowEqual(cache.current, value) ? cache.current : value
}

View File

@@ -0,0 +1,233 @@
import type {
BaseQueryApi,
BaseQueryArg,
BaseQueryEnhancer,
BaseQueryError,
BaseQueryExtraOptions,
BaseQueryFn,
BaseQueryMeta,
} from './baseQueryTypes'
import type { FetchBaseQueryError } from './fetchBaseQuery'
import { HandledError } from './HandledError'
/**
* Exponential backoff based on the attempt number.
*
* @remarks
* 1. 600ms * random(0.4, 1.4)
* 2. 1200ms * random(0.4, 1.4)
* 3. 2400ms * random(0.4, 1.4)
* 4. 4800ms * random(0.4, 1.4)
* 5. 9600ms * random(0.4, 1.4)
*
* @param attempt - Current attempt
* @param maxRetries - Maximum number of retries
*/
async function defaultBackoff(
attempt: number = 0,
maxRetries: number = 5,
signal?: AbortSignal,
) {
const attempts = Math.min(attempt, maxRetries)
const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option
await new Promise<void>((resolve, reject) => {
const timeoutId = setTimeout(() => resolve(), timeout)
// If signal is provided and gets aborted, clear timeout and reject
if (signal) {
const abortHandler = () => {
clearTimeout(timeoutId)
reject(new Error('Aborted'))
}
// Check if already aborted
if (signal.aborted) {
clearTimeout(timeoutId)
reject(new Error('Aborted'))
} else {
signal.addEventListener('abort', abortHandler, { once: true })
}
}
})
}
type RetryConditionFunction = (
error: BaseQueryError<BaseQueryFn>,
args: BaseQueryArg<BaseQueryFn>,
extraArgs: {
attempt: number
baseQueryApi: BaseQueryApi
extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions
},
) => boolean
export type RetryOptions = {
/**
* Function used to determine delay between retries
*/
backoff?: (
attempt: number,
maxRetries: number,
signal?: AbortSignal,
) => Promise<void>
} & (
| {
/**
* How many times the query will be retried (default: 5)
*/
maxRetries?: number
retryCondition?: undefined
}
| {
/**
* Callback to determine if a retry should be attempted.
* Return `true` for another retry and `false` to quit trying prematurely.
*/
retryCondition?: RetryConditionFunction
maxRetries?: undefined
}
)
function fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(
error: BaseQueryError<BaseQuery>,
meta?: BaseQueryMeta<BaseQuery>,
): never {
throw Object.assign(new HandledError({ error, meta }), {
throwImmediately: true,
})
}
/**
* Checks if the abort signal is aborted and fails immediately if so.
* Used to exit retry loops cleanly when a request is aborted.
*/
function failIfAborted(signal: AbortSignal): void {
if (signal.aborted) {
fail({ status: 'CUSTOM_ERROR', error: 'Aborted' })
}
}
const EMPTY_OPTIONS = {}
const retryWithBackoff: BaseQueryEnhancer<
unknown,
RetryOptions,
RetryOptions | void
> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
// We need to figure out `maxRetries` before we define `defaultRetryCondition.
// This is probably goofy, but ought to work.
// Put our defaults in one array, filter out undefineds, grab the last value.
const possibleMaxRetries: number[] = [
5,
((defaultOptions as any) || EMPTY_OPTIONS).maxRetries,
((extraOptions as any) || EMPTY_OPTIONS).maxRetries,
].filter((x) => x !== undefined)
const [maxRetries] = possibleMaxRetries.slice(-1)
const defaultRetryCondition: RetryConditionFunction = (_, __, { attempt }) =>
attempt <= maxRetries
const options: {
maxRetries: number
backoff: typeof defaultBackoff
retryCondition: typeof defaultRetryCondition
} = {
maxRetries,
backoff: defaultBackoff,
retryCondition: defaultRetryCondition,
...defaultOptions,
...extraOptions,
}
let retry = 0
while (true) {
// Check if aborted before each attempt
failIfAborted(api.signal)
try {
const result = await baseQuery(args, api, extraOptions)
// baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying
if (result.error) {
throw new HandledError(result)
}
return result
} catch (e: any) {
retry++
if (e.throwImmediately) {
if (e instanceof HandledError) {
return e.value
}
// We don't know what this is, so we have to rethrow it
throw e
}
if (e instanceof HandledError) {
if (
!options.retryCondition(e.value.error as FetchBaseQueryError, args, {
attempt: retry,
baseQueryApi: api,
extraOptions,
})
) {
return e.value // Max retries for expected error
}
} else {
// For unexpected errors, respect maxRetries
if (retry > options.maxRetries) {
// Return the error as a proper error response instead of throwing
return { error: e }
}
}
// Check if aborted before backoff
failIfAborted(api.signal)
try {
await options.backoff(retry, options.maxRetries, api.signal)
} catch (backoffError) {
// If backoff was aborted, exit the retry loop
failIfAborted(api.signal)
// Otherwise, rethrow the backoff error
throw backoffError
}
}
}
}
/**
* A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.
*
* @example
*
* ```ts
* // codeblock-meta title="Retry every request 5 times by default"
* import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.
* const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });
* export const api = createApi({
* baseQuery: staggeredBaseQuery,
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => ({ url: 'posts' }),
* }),
* getPost: build.query<PostsResponse, string>({
* query: (id) => ({ url: `post/${id}` }),
* extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint
* }),
* }),
* });
*
* export const { useGetPostsQuery, useGetPostQuery } = api;
* ```
*/
export const retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail })

View File

@@ -0,0 +1,35 @@
import type { StandardSchemaV1 } from '@standard-schema/spec'
import { SchemaError } from '@standard-schema/utils'
import type { SchemaType } from './endpointDefinitions'
export class NamedSchemaError extends SchemaError {
constructor(
issues: readonly StandardSchemaV1.Issue[],
public readonly value: any,
public readonly schemaName: `${SchemaType}Schema`,
public readonly _bqMeta: any,
) {
super(issues)
}
}
export const shouldSkip = (
skipSchemaValidation: boolean | SchemaType[] | undefined,
schemaName: SchemaType,
) =>
Array.isArray(skipSchemaValidation)
? skipSchemaValidation.includes(schemaName)
: !!skipSchemaValidation
export async function parseWithSchema<Schema extends StandardSchemaV1>(
schema: Schema,
data: unknown,
schemaName: `${SchemaType}Schema`,
bqMeta: any,
): Promise<StandardSchemaV1.InferOutput<Schema>> {
const result = await schema['~standard'].validate(data)
if (result.issues) {
throw new NamedSchemaError(result.issues, data, schemaName, bqMeta)
}
return result.value
}

View File

@@ -0,0 +1,170 @@
import { configureStore } from '@reduxjs/toolkit'
import {
ApiProvider,
buildCreateApi,
coreModule,
createApi,
reactHooksModule,
} from '@reduxjs/toolkit/query/react'
import { fireEvent, render, waitFor } from '@testing-library/react'
import { delay } from 'msw'
import * as React from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import {
Provider,
createDispatchHook,
createSelectorHook,
createStoreHook,
} from 'react-redux'
const api = createApi({
baseQuery: async (arg: any) => {
await delay(150)
return { data: arg?.body ? arg.body : null }
},
endpoints: (build) => ({
getUser: build.query<any, number>({
query: (arg) => arg,
}),
updateUser: build.mutation<any, { name: string }>({
query: (update) => ({ body: update }),
}),
}),
})
afterEach(() => {
vi.resetAllMocks()
})
describe('ApiProvider', () => {
test('ApiProvider allows a user to make queries without a traditional Redux setup', async () => {
function User() {
const [value, setValue] = React.useState(0)
const { isFetching } = api.endpoints.getUser.useQuery(1, {
skip: value < 1,
})
return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
<button onClick={() => setValue((val) => val + 1)}>
Increment value
</button>
</div>
)
}
const { getByText, getByTestId } = render(
<ApiProvider api={api}>
<User />
</ApiProvider>,
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('true'),
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
// Being that nothing has changed in the args, this should never fire.
expect(getByTestId('isFetching').textContent).toBe('false')
})
test('ApiProvider throws if nested inside a Redux context', () => {
// Intentionally swallow the "unhandled error" message
vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() =>
render(
<Provider store={configureStore({ reducer: () => null })}>
<ApiProvider api={api}>child</ApiProvider>
</Provider>,
),
).toThrowErrorMatchingInlineSnapshot(
`[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]`,
)
})
test('ApiProvider allows a custom context', async () => {
const customContext = React.createContext<ReactReduxContextValue | null>(
null,
)
const createApiWithCustomContext = buildCreateApi(
coreModule(),
reactHooksModule({
hooks: {
useStore: createStoreHook(customContext),
useSelector: createSelectorHook(customContext),
useDispatch: createDispatchHook(customContext),
},
}),
)
const customApi = createApiWithCustomContext({
baseQuery: async (arg: any) => {
await delay(150)
return { data: arg?.body ? arg.body : null }
},
endpoints: (build) => ({
getUser: build.query<any, number>({
query: (arg) => arg,
}),
updateUser: build.mutation<any, { name: string }>({
query: (update) => ({ body: update }),
}),
}),
})
function User() {
const [value, setValue] = React.useState(0)
const { isFetching } = customApi.endpoints.getUser.useQuery(1, {
skip: value < 1,
})
return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
<button onClick={() => setValue((val) => val + 1)}>
Increment value
</button>
</div>
)
}
const { getByText, getByTestId } = render(
<ApiProvider api={customApi} context={customContext}>
<User />
</ApiProvider>,
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('true'),
)
await waitFor(() =>
expect(getByTestId('isFetching').textContent).toBe('false'),
)
fireEvent.click(getByText('Increment value'))
// Being that nothing has changed in the args, this should never fire.
expect(getByTestId('isFetching').textContent).toBe('false')
// won't throw if nested, because context is different
expect(() =>
render(
<Provider store={configureStore({ reducer: () => null })}>
<ApiProvider api={customApi} context={customContext}>
child
</ApiProvider>
</Provider>,
),
).not.toThrow()
})
})

View File

@@ -0,0 +1,32 @@
import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query'
describe('type tests', () => {
test('BaseQuery meta types propagate to endpoint callbacks', () => {
createApi({
baseQuery: fetchBaseQuery(),
endpoints: (build) => ({
getDummy: build.query<null, undefined>({
query: () => 'dummy',
onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {
const { meta } = await cacheDataLoaded
const { request, response } = meta! // Expect request and response to be there
},
}),
}),
})
const baseQuery = retry(fetchBaseQuery()) // Even when wrapped with retry
createApi({
baseQuery,
endpoints: (build) => ({
getDummy: build.query<null, undefined>({
query: () => 'dummy',
onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {
const { meta } = await cacheDataLoaded
const { request, response } = meta! // Expect request and response to be there
},
}),
}),
})
})
})

View File

@@ -0,0 +1,168 @@
import { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'
import {
buildCreateApi,
coreModule,
reactHooksModule,
} from '@reduxjs/toolkit/query/react'
import { render, screen, waitFor } from '@testing-library/react'
import { delay } from 'msw'
import * as React from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import {
Provider,
createDispatchHook,
createSelectorHook,
createStoreHook,
} from 'react-redux'
import { setupApiStore, useRenderCounter } from '../../tests/utils/helpers'
const MyContext = React.createContext<ReactReduxContextValue | null>(null)
describe('buildCreateApi', () => {
test('Works with all hooks provided', async () => {
const customCreateApi = buildCreateApi(
coreModule(),
reactHooksModule({
hooks: {
useDispatch: createDispatchHook(MyContext),
useSelector: createSelectorHook(MyContext),
useStore: createStoreHook(MyContext),
},
}),
)
const api = customCreateApi({
baseQuery: async (arg: any) => {
await delay(150)
return {
data: arg?.body ? { ...arg.body } : {},
}
},
endpoints: (build) => ({
getUser: build.query<{ name: string }, number>({
query: () => ({
body: { name: 'Timmy' },
}),
}),
}),
})
let getRenderCount: () => number = () => 0
const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })
// Copy of 'useQuery hook basic render count assumptions' from `buildHooks.test.tsx`
function User() {
const { isFetching } = api.endpoints.getUser.useQuery(1)
getRenderCount = useRenderCounter()
return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
</div>
)
}
function Wrapper({ children }: any) {
return (
<Provider store={storeRef.store} context={MyContext}>
{children}
</Provider>
)
}
render(<User />, { wrapper: Wrapper })
// By the time this runs, the initial render will happen, and the query
// will start immediately running by the time we can expect this
expect(getRenderCount()).toBe(2)
await waitFor(() =>
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
)
expect(getRenderCount()).toBe(3)
})
test("Throws an error if you don't provide all hooks", async () => {
const callBuildCreateApi = () => {
const customCreateApi = buildCreateApi(
coreModule(),
reactHooksModule({
// @ts-ignore
hooks: {
useDispatch: createDispatchHook(MyContext),
useSelector: createSelectorHook(MyContext),
},
}),
)
}
expect(callBuildCreateApi).toThrowErrorMatchingInlineSnapshot(
`
[Error: When using custom hooks for context, all 3 hooks need to be provided: useDispatch, useSelector, useStore.
Hook useStore was either not provided or not a function.]
`,
)
})
test('allows passing createSelector instance', async () => {
const memoize = vi.fn(lruMemoize)
const createSelector = createSelectorCreator(memoize)
const createApi = buildCreateApi(
coreModule({ createSelector }),
reactHooksModule({ createSelector }),
)
const api = createApi({
baseQuery: async (arg: any) => {
await delay(150)
return {
data: arg?.body ? { ...arg.body } : {},
}
},
endpoints: (build) => ({
getUser: build.query<{ name: string }, number>({
query: () => ({
body: { name: 'Timmy' },
}),
}),
}),
})
const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })
await storeRef.store.dispatch(api.endpoints.getUser.initiate(1))
const selectUser = api.endpoints.getUser.select(1)
expect(selectUser(storeRef.store.getState()).data).toEqual({
name: 'Timmy',
})
expect(memoize).toHaveBeenCalledTimes(4)
memoize.mockClear()
function User() {
const { isFetching } = api.endpoints.getUser.useQuery(1)
return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
</div>
)
}
function Wrapper({ children }: any) {
return <Provider store={storeRef.store}>{children}</Provider>
}
render(<User />, { wrapper: Wrapper })
await waitFor(() =>
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
)
// select() + selectFromResult
expect(memoize).toHaveBeenCalledTimes(8)
})
})

View File

@@ -0,0 +1,374 @@
import type {
QueryStateSelector,
UseMutation,
UseQuery,
} from '@internal/query/react/buildHooks'
import { ANY } from '@internal/tests/utils/helpers'
import type { SerializedError } from '@reduxjs/toolkit'
import type {
QueryDefinition,
SubscriptionOptions,
TypedQueryStateSelector,
} from '@reduxjs/toolkit/query/react'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { useState } from 'react'
let amount = 0
let nextItemId = 0
interface Item {
id: number
}
const api = createApi({
baseQuery: (arg: any) => {
if (arg?.body && 'amount' in arg.body) {
amount += 1
}
if (arg?.body && 'forceError' in arg.body) {
return {
error: {
status: 500,
data: null,
},
}
}
if (arg?.body && 'listItems' in arg.body) {
const items: Item[] = []
for (let i = 0; i < 3; i++) {
const item = { id: nextItemId++ }
items.push(item)
}
return { data: items }
}
return {
data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},
}
},
endpoints: (build) => ({
getUser: build.query<{ name: string }, number>({
query: () => ({
body: { name: 'Timmy' },
}),
}),
getUserAndForceError: build.query<{ name: string }, number>({
query: () => ({
body: {
forceError: true,
},
}),
}),
getIncrementedAmount: build.query<{ amount: number }, void>({
query: () => ({
url: '',
body: {
amount,
},
}),
}),
updateUser: build.mutation<{ name: string }, { name: string }>({
query: (update) => ({ body: update }),
}),
getError: build.query({
query: () => '/error',
}),
listItems: build.query<Item[], { pageNumber: number }>({
serializeQueryArgs: ({ endpointName }) => {
return endpointName
},
query: ({ pageNumber }) => ({
url: `items?limit=1&offset=${pageNumber}`,
body: {
listItems: true,
},
}),
merge: (currentCache, newItems) => {
currentCache.push(...newItems)
},
forceRefetch: () => {
return true
},
}),
}),
})
describe('type tests', () => {
test('useLazyQuery hook callback returns various properties to handle the result', () => {
function User() {
const [getUser] = api.endpoints.getUser.useLazyQuery()
const [{ successMsg, errMsg, isAborted }, setValues] = useState({
successMsg: '',
errMsg: '',
isAborted: false,
})
const handleClick = (abort: boolean) => async () => {
const res = getUser(1)
// no-op simply for clearer type assertions
res.then((result) => {
if (result.isSuccess) {
expectTypeOf(result).toMatchTypeOf<{
data: {
name: string
}
}>()
}
if (result.isError) {
expectTypeOf(result).toMatchTypeOf<{
error: { status: number; data: unknown } | SerializedError
}>()
}
})
expectTypeOf(res.arg).toBeNumber()
expectTypeOf(res.requestId).toBeString()
expectTypeOf(res.abort).toEqualTypeOf<() => void>()
expectTypeOf(res.unsubscribe).toEqualTypeOf<() => void>()
expectTypeOf(res.updateSubscriptionOptions).toEqualTypeOf<
(options: SubscriptionOptions) => void
>()
expectTypeOf(res.refetch).toMatchTypeOf<() => void>()
expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
}
return (
<div>
<button onClick={handleClick(false)}>Fetch User successfully</button>
<button onClick={handleClick(true)}>Fetch User and abort</button>
<div>{successMsg}</div>
<div>{errMsg}</div>
<div>{isAborted ? 'Request was aborted' : ''}</div>
</div>
)
}
})
test('useMutation hook callback returns various properties to handle the result', async () => {
function User() {
const [updateUser] = api.endpoints.updateUser.useMutation()
const [successMsg, setSuccessMsg] = useState('')
const [errMsg, setErrMsg] = useState('')
const [isAborted, setIsAborted] = useState(false)
const handleClick = async () => {
const res = updateUser({ name: 'Banana' })
expectTypeOf(res).resolves.toMatchTypeOf<
| {
error: { status: number; data: unknown } | SerializedError
}
| {
data: {
name: string
}
}
>()
expectTypeOf(res.arg).toMatchTypeOf<{
endpointName: string
originalArgs: { name: string }
track?: boolean
}>()
expectTypeOf(res.requestId).toBeString()
expectTypeOf(res.abort).toEqualTypeOf<() => void>()
expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
expectTypeOf(res.reset).toEqualTypeOf<() => void>()
}
return (
<div>
<button onClick={handleClick}>Update User and abort</button>
<div>{successMsg}</div>
<div>{errMsg}</div>
<div>{isAborted ? 'Request was aborted' : ''}</div>
</div>
)
}
})
test('top level named hooks', () => {
interface Post {
id: number
name: string
fetched_at: string
}
type PostsResponse = Post[]
const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
tagTypes: ['Posts'],
endpoints: (build) => ({
getPosts: build.query<PostsResponse, void>({
query: () => ({ url: 'posts' }),
providesTags: (result) =>
result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],
}),
updatePost: build.mutation<Post, Partial<Post>>({
query: ({ id, ...body }) => ({
url: `post/${id}`,
method: 'PUT',
body,
}),
invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],
}),
addPost: build.mutation<Post, Partial<Post>>({
query: (body) => ({
url: `post`,
method: 'POST',
body,
}),
invalidatesTags: ['Posts'],
}),
}),
})
expectTypeOf(api.useGetPostsQuery).toEqualTypeOf(
api.endpoints.getPosts.useQuery,
)
expectTypeOf(api.useUpdatePostMutation).toEqualTypeOf(
api.endpoints.updatePost.useMutation,
)
expectTypeOf(api.useAddPostMutation).toEqualTypeOf(
api.endpoints.addPost.useMutation,
)
})
test('UseQuery type can be used to recreate the hook type', () => {
const fakeQuery = ANY as UseQuery<
typeof api.endpoints.getUser.Types.QueryDefinition
>
expectTypeOf(fakeQuery).toEqualTypeOf(api.endpoints.getUser.useQuery)
})
test('UseMutation type can be used to recreate the hook type', () => {
const fakeMutation = ANY as UseMutation<
typeof api.endpoints.updateUser.Types.MutationDefinition
>
expectTypeOf(fakeMutation).toEqualTypeOf(
api.endpoints.updateUser.useMutation,
)
})
test('TypedQueryStateSelector creates a pre-typed version of QueryStateSelector', () => {
type Post = {
id: number
title: string
}
type PostsApiResponse = {
posts: Post[]
total: number
skip: number
limit: number
}
type QueryArgument = number | undefined
type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
type SelectedResult = Pick<PostsApiResponse, 'posts'>
const postsApiSlice = createApi({
baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
reducerPath: 'postsApi',
tagTypes: ['Posts'],
endpoints: (build) => ({
getPosts: build.query<PostsApiResponse, QueryArgument>({
query: (limit = 5) => `?limit=${limit}&select=title`,
}),
}),
})
const { useGetPostsQuery } = postsApiSlice
function PostById({ id }: { id: number }) {
const { post } = useGetPostsQuery(undefined, {
selectFromResult: (state) => ({
post: state.data?.posts.find((post) => post.id === id),
}),
})
expectTypeOf(post).toEqualTypeOf<Post | undefined>()
return <li>{post?.title}</li>
}
const EMPTY_ARRAY: Post[] = []
const typedSelectFromResult: TypedQueryStateSelector<
PostsApiResponse,
QueryArgument,
BaseQueryFunction,
SelectedResult
> = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
expectTypeOf<
TypedQueryStateSelector<
PostsApiResponse,
QueryArgument,
BaseQueryFunction,
SelectedResult
>
>().toEqualTypeOf<
QueryStateSelector<
SelectedResult,
QueryDefinition<
QueryArgument,
BaseQueryFunction,
string,
PostsApiResponse
>
>
>()
expectTypeOf(typedSelectFromResult).toEqualTypeOf<
QueryStateSelector<
SelectedResult,
QueryDefinition<
QueryArgument,
BaseQueryFunction,
string,
PostsApiResponse
>
>
>()
function PostsList() {
const { posts } = useGetPostsQuery(undefined, {
selectFromResult: typedSelectFromResult,
})
expectTypeOf(posts).toEqualTypeOf<Post[]>()
return (
<div>
<ul>
{posts.map((post) => (
<PostById key={post.id} id={post.id} />
))}
</ul>
</div>
)
}
})
})

Some files were not shown because too many files have changed in this diff Show More