Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import { Dispatch, Middleware } from "@reduxjs/toolkit"; import { RootState } from "store/configureStore"; import throttle from "lodash/throttle"; import { DebouncedFunc } from "lodash"; type ThrottleableAction = { type: string; meta: { throttle: number; key: string; }; }; const isThrottleableAction = ( action: unknown ): action is ThrottleableAction => { Iif (typeof action !== "object" || action === null) return false; const actionWithMeta = action as { meta?: unknown }; Iif (typeof actionWithMeta.meta !== "object" || actionWithMeta.meta === null) { return false; } const metaWithThrottle = actionWithMeta.meta as { throttle?: unknown; key?: unknown; }; return ( typeof metaWithThrottle.throttle === "number" && typeof metaWithThrottle.key === "string" ); }; const throttled: Record<string, DebouncedFunc<Dispatch<ThrottleableAction>>> = {}; const throttleMiddleware: Middleware<Dispatch, RootState> = (_store) => (next) => async (action) => { Iif (!isThrottleableAction(action)) { return next(action); } const time = (action.meta && action.meta.throttle) as number | undefined; Iif (!time) return next(action); const key = `${action.type}_${action.meta.key}`; const previousCall = throttled[key]; Iif (previousCall) { return previousCall(action); } const newCall = throttle(next, time, { leading: true, trailing: true, }) as DebouncedFunc<Dispatch<ThrottleableAction>>; throttled[key] = newCall; return newCall(action); }; export default throttleMiddleware; |