Skip to content

Commit

Permalink
Simplify listener/dynamic middleware code
Browse files Browse the repository at this point in the history
  • Loading branch information
EskiMojo14 committed Nov 27, 2024
1 parent 2ad4bb4 commit 3bb8486
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 51 deletions.
17 changes: 6 additions & 11 deletions packages/toolkit/src/dynamicMiddleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { compose } from 'redux'
import { createAction } from '../createAction'
import { isAllOf } from '../matchers'
import { nanoid } from '../nanoid'
import { find, getOrInsertComputed } from '../utils'
import { getOrInsertComputed } from '../utils'
import type {
AddMiddleware,
DynamicMiddleware,
Expand All @@ -23,7 +23,6 @@ const createMiddlewareEntry = <
>(
middleware: Middleware<any, State, DispatchType>,
): MiddlewareEntry<State, DispatchType> => ({
id: nanoid(),
middleware,
applied: new Map(),
})
Expand All @@ -38,7 +37,10 @@ export const createDynamicMiddleware = <
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(): DynamicMiddlewareInstance<State, DispatchType> => {
const instanceId = nanoid()
const middlewareMap = new Map<string, MiddlewareEntry<State, DispatchType>>()
const middlewareMap = new Map<
Middleware<any, State, DispatchType>,
MiddlewareEntry<State, DispatchType>
>()

const withMiddleware = Object.assign(
createAction(
Expand All @@ -58,14 +60,7 @@ export const createDynamicMiddleware = <
...middlewares: Middleware<any, State, DispatchType>[]
) {
middlewares.forEach((middleware) => {
let entry = find(
Array.from(middlewareMap.values()),
(entry) => entry.middleware === middleware,
)
if (!entry) {
entry = createMiddlewareEntry(middleware)
}
middlewareMap.set(entry.id, entry)
getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)
})
},
{ withTypes: () => addMiddleware },
Expand Down
1 change: 0 additions & 1 deletion packages/toolkit/src/dynamicMiddleware/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ export type MiddlewareEntry<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
id: string
middleware: Middleware<any, State, DispatchType>
applied: Map<
MiddlewareAPI<DispatchType, State>,
Expand Down
27 changes: 9 additions & 18 deletions packages/toolkit/src/listenerMiddleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'
import { isAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { createAction } from '../createAction'
import { nanoid } from '../nanoid'

import { find } from '../utils'
import {
TaskAbortError,
listenerCancelled,
Expand Down Expand Up @@ -48,6 +46,7 @@ import {
catchRejection,
noop,
} from './utils'
import { getOrInsertComputed } from '@internal/utils'
export { TaskAbortError } from './exceptions'
export type {
AsyncTaskExecutor,
Expand Down Expand Up @@ -221,9 +220,7 @@ export const createListenerEntry: TypedCreateListenerEntry<unknown> =
(options: FallbackAddListenerOptions) => {
const { type, predicate, effect } = getListenerEntryPropsFrom(options)

const id = nanoid()
const entry: ListenerEntry<unknown> = {
id,
effect,
type,
predicate,
Expand All @@ -247,7 +244,7 @@ const cancelActiveListeners = (
}

const createClearListenerMiddleware = (
listenerMap: Map<string, ListenerEntry>,
listenerMap: Map<ListenerEntry['effect'], ListenerEntry>,
) => {
return () => {
listenerMap.forEach(cancelActiveListeners)
Expand Down Expand Up @@ -324,15 +321,15 @@ export const createListenerMiddleware = <
>(
middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},
) => {
const listenerMap = new Map<string, ListenerEntry>()
const listenerMap = new Map<ListenerEntry['effect'], ListenerEntry>()
const { extra, onError = defaultErrorHandler } = middlewareOptions

assertFunction(onError, 'onError')

const insertEntry = (entry: ListenerEntry) => {
entry.unsubscribe = () => listenerMap.delete(entry!.id)
entry.unsubscribe = () => listenerMap.delete(entry.effect)

listenerMap.set(entry.id, entry)
listenerMap.set(entry.effect, entry)
return (cancelOptions?: UnsubscribeListenerOptions) => {
entry.unsubscribe()
if (cancelOptions?.cancelActive) {
Expand All @@ -342,15 +339,9 @@ export const createListenerMiddleware = <
}

const startListening = ((options: FallbackAddListenerOptions) => {
let entry = find(
Array.from(listenerMap.values()),
(existingEntry) => existingEntry.effect === options.effect,
const entry = getOrInsertComputed(listenerMap, options.effect, () =>
createListenerEntry(options as any),
)

if (!entry) {
entry = createListenerEntry(options as any)
}

return insertEntry(entry)
}) as AddListenerOverloads<any>

Expand All @@ -363,7 +354,7 @@ export const createListenerMiddleware = <
): boolean => {
const { type, effect, predicate } = getListenerEntryPropsFrom(options)

const entry = find(Array.from(listenerMap.values()), (entry) => {
const entry = Array.from(listenerMap.values()).find((entry) => {
const matchPredicateOrType =
typeof type === 'string'
? entry.type === type
Expand Down Expand Up @@ -419,7 +410,7 @@ export const createListenerMiddleware = <
fork: createFork(internalTaskController.signal, autoJoinPromises),
unsubscribe: entry.unsubscribe,
subscribe: () => {
listenerMap.set(entry.id, entry)
listenerMap.set(entry.effect, entry)
},
cancelActiveListeners: () => {
entry.pending.forEach((controller, _, set) => {
Expand Down
35 changes: 27 additions & 8 deletions packages/toolkit/src/listenerMiddleware/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,9 +578,13 @@ export type TypedAddListener<
OverrideStateType,
unknown,
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedAddListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>
>,
OverrideExtraArgument = unknown,
>() => TypedAddListener<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}

/**
Expand Down Expand Up @@ -641,7 +645,11 @@ export type TypedRemoveListener<
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedRemoveListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>
>() => TypedRemoveListener<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}

/**
Expand Down Expand Up @@ -701,7 +709,11 @@ export type TypedStartListening<
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedStartListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>
>() => TypedStartListening<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}

/**
Expand Down Expand Up @@ -756,7 +768,11 @@ export type TypedStopListening<
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>
>() => TypedStopListening<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}

/**
Expand Down Expand Up @@ -813,7 +829,11 @@ export type TypedCreateListenerEntry<
UnknownAction
>,
OverrideExtraArgument = unknown,
>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>
>() => TypedStopListening<
OverrideStateType,
OverrideDispatchType,
OverrideExtraArgument
>
}

/**
Expand All @@ -825,7 +845,6 @@ export type ListenerEntry<
State = unknown,
DispatchType extends Dispatch = Dispatch,
> = {
id: string
effect: ListenerEffect<any, State, DispatchType>
unsubscribe: () => void
pending: Set<AbortController>
Expand Down
13 changes: 0 additions & 13 deletions packages/toolkit/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,6 @@ export function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}

export function find<T>(
iterable: Iterable<T>,
comparator: (item: T) => boolean,
): T | undefined {
for (const entry of iterable) {
if (comparator(entry)) {
return entry
}
}

return undefined
}

export class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<
Items[number]
> {
Expand Down

0 comments on commit 3bb8486

Please sign in to comment.