repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

commit
8c23451
parent
0f6e95e
author
Eric Bower
date
2023-12-12 17:43:34 +0000 UTC
feat(store): `reset` updater to revert store to initialState provided by
user
3 files changed,  +49, -0
M store/store.test.ts
+34, -0
 1@@ -136,3 +136,37 @@ it(tests, "emit Action and update store", async () => {
 2     dev: true,
 3   });
 4 });
 5+
 6+it(tests, "resets store", async () => {
 7+  const initialState: Partial<State> = {
 8+    users: { 1: { id: "1", name: "testing" }, 2: { id: "2", name: "wow" } },
 9+    dev: false,
10+    theme: "",
11+    token: "",
12+  };
13+  const store = configureStore({ initialState });
14+
15+  await store.run(function* () {
16+    yield* store.update((s) => {
17+      s.users = { 3: { id: "3", name: "hehe" } };
18+      s.dev = true;
19+      s.theme = "darkness";
20+    });
21+  });
22+
23+  asserts.assertEquals(store.getState(), {
24+    users: { 3: { id: "3", name: "hehe" } },
25+    theme: "darkness",
26+    token: "",
27+    dev: true,
28+  });
29+
30+  await store.run(store.reset(["users"]));
31+
32+  asserts.assertEquals(store.getState(), {
33+    users: { 3: { id: "3", name: "hehe" } },
34+    dev: false,
35+    theme: "",
36+    token: "",
37+  });
38+});
M store/store.ts
+14, -0
 1@@ -150,11 +150,25 @@ export function createStore<S extends AnyState>({
 2     return initialState;
 3   }
 4 
 5+  function* reset(ignoreList: (keyof S)[] = []) {
 6+    return yield* update((s) => {
 7+      const keep = ignoreList.reduce<S>((acc, key) => {
 8+        acc[key] = s[key];
 9+        return acc;
10+      }, { ...initialState });
11+
12+      Object.keys(s).forEach((key: keyof S) => {
13+        s[key] = keep[key];
14+      });
15+    });
16+  }
17+
18   return {
19     getScope,
20     getState,
21     subscribe,
22     update,
23+    reset,
24     run,
25     // instead of actions relating to store mutation, they
26     // refer to pieces of business logic -- that can also mutate state
M store/types.ts
+1, -0
1@@ -41,6 +41,7 @@ export interface FxStore<S extends AnyState> {
2   getState: () => S;
3   subscribe: (fn: Listener) => () => void;
4   update: (u: StoreUpdater<S> | StoreUpdater<S>[]) => Operation<UpdaterCtx<S>>;
5+  reset: (ignoreList?: (keyof S)[]) => Operation<UpdaterCtx<S>>;
6   run: <T>(op: Callable<T>) => Task<Result<T>>;
7   // deno-lint-ignore no-explicit-any
8   dispatch: (a: AnyAction) => any;