File size: 2,693 Bytes
c2b7eb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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,
  }
}