- commit
- 0ba8393
- parent
- 4d4f2d8
- author
- Eric Bower
- date
- 2023-09-17 02:44:36 +0000 UTC
refactor(redux): use signal for middleware
2 files changed,
+24,
-22
+2,
-4
1@@ -1,5 +1,5 @@
2-import { Action, Operation, Signal } from "../deps.ts";
3-import { createContext, createSignal, each, spawn } from "../deps.ts";
4+import type { Action, Operation, Signal } from "../deps.ts";
5+import { createContext, each, spawn } from "../deps.ts";
6 import { call } from "../fx/mod.ts";
7 import { ActionPattern, matcher } from "../matcher.ts";
8 import type { ActionWPayload, AnyAction } from "../types.ts";
9@@ -8,9 +8,7 @@ import type { StoreLike } from "./types.ts";
10
11 export const ActionContext = createContext<Signal<Action, void>>(
12 "redux:action",
13- createSignal<Action, void>(),
14 );
15-
16 export const StoreContext = createContext<StoreLike>("redux:store");
17
18 export function emit({
+22,
-18
1@@ -1,24 +1,28 @@
2-import { BATCH, BatchAction, ReducersMapObject, Scope } from "../deps.ts";
3-import { combineReducers, createScope, enableBatching } from "../deps.ts";
4+import {
5+ BATCH,
6+ BatchAction,
7+ combineReducers,
8+ createScope,
9+ createSignal,
10+ enableBatching,
11+ ReducersMapObject,
12+ Scope,
13+ Signal,
14+} from "../deps.ts";
15 import type { AnyAction } from "../types.ts";
16 import { ActionContext, emit, StoreContext } from "./fx.ts";
17 import { reducers as queryReducers } from "./query.ts";
18 import type { StoreLike } from "./types.ts";
19
20-export function* send(action: AnyAction) {
21- const signal = yield* ActionContext;
22- if (action.type === BATCH) {
23- const actions = action.payload as BatchAction[];
24- emit({
25- signal,
26- action: actions,
27- });
28- } else {
29- emit({
30- signal,
31- action,
32- });
33+export function send(signal: Signal<AnyAction, void>, act: AnyAction) {
34+ let action: AnyAction | AnyAction[] = act;
35+ if (act.type === BATCH) {
36+ action = act.payload as BatchAction[];
37 }
38+ emit({
39+ signal,
40+ action,
41+ });
42 }
43
44 export function createFxMiddleware(initScope?: Scope) {
45@@ -29,15 +33,15 @@ export function createFxMiddleware(initScope?: Scope) {
46 const tuple = createScope();
47 scope = tuple[0];
48 }
49+ const signal = createSignal<AnyAction, void>();
50
51 function middleware<S = unknown>(store: StoreLike<S>) {
52 scope.set(StoreContext, store);
53+ scope.set(ActionContext, signal);
54
55 return (next: (a: unknown) => unknown) => (action: unknown) => {
56 const result = next(action); // hit reducers
57- scope.run(function* () {
58- yield* send(action as AnyAction);
59- });
60+ send(signal, action as AnyAction);
61 return result;
62 };
63 }