repos / starfx

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

commit
654cbc5
parent
35d4d7e
author
Eric Bower
date
2024-01-06 03:36:09 +0000 UTC
feat(query): generic loader mdw
1 files changed,  +37, -1
M store/query.ts
+37, -1
 1@@ -1,4 +1,4 @@
 2-import type { ApiCtx, Next } from "../query/mod.ts";
 3+import type { ApiCtx, Next, ThunkCtx } from "../query/mod.ts";
 4 import { compose } from "../compose.ts";
 5 import type { AnyAction, AnyState } from "../types.ts";
 6 
 7@@ -61,6 +61,42 @@ export function* dispatchActions(ctx: { actions: AnyAction[] }, next: Next) {
 8   yield* put(ctx.actions);
 9 }
10 
11+/**
12+ * This middleware will track the status of a middleware fn
13+ */
14+export function* loader<
15+  Ctx extends ThunkCtx = ThunkCtx,
16+  M extends AnyState = AnyState,
17+>(
18+  loaderSchema: LoaderOutput<M, AnyState>,
19+) {
20+  return function* (ctx: Ctx, next: Next) {
21+    yield* updateStore([
22+      loaderSchema.start({ id: ctx.name }),
23+      loaderSchema.start({ id: ctx.key }),
24+    ]);
25+
26+    try {
27+      yield* next();
28+      yield* updateStore([
29+        loaderSchema.success({ id: ctx.name }),
30+        loaderSchema.success({ id: ctx.key }),
31+      ]);
32+    } catch (err) {
33+      yield* updateStore([
34+        loaderSchema.error({
35+          id: ctx.name,
36+          message: err.message,
37+        }),
38+        loaderSchema.error({
39+          id: ctx.key,
40+          message: err.message,
41+        }),
42+      ]);
43+    }
44+  };
45+}
46+
47 /**
48  * This middleware will track the status of a fetch request.
49  */