repos / starfx

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

starfx / docs / posts
Eric Bower · 04 Mar 24

mdw.md

 1---
 2title: Middleware
 3slug: middleware
 4description: The structure of a middleware function
 5---
 6
 7Here is the most basic middleware (mdw) function in `starfx`:
 8
 9```ts
10function* (ctx, next) {
11  yield* next();
12}
13```
14
15Thunks and endpoints are just thin wrappers around a mdw stack:
16
17For example, the recommended mdw stack for `createApi()` looks like this:
18
19```ts
20import { createApi, mdw } from "starfx";
21import { schema } from "./schema";
22
23// this api:
24const api = createApi();
25api.use(mdw.api({ schema }));
26api.use(api.routes());
27api.use(mdw.fetch({ baseUrl: "https://api.com" }));
28
29// looks like this:
30[
31  mdw.err,
32  mdw.queryCtx,
33  mdw.customKey,
34  mdw.nameParser,
35  mdw.actions,
36  mdw.loaderApi({ schema }),
37  mdw.cache({ schema }),
38  api.routes(),
39  mdw.composeUrl("https://api.com"),
40  mdw.payload,
41  mdw.request,
42  mdw.json,
43];
44```
45
46When a mdw function calls `yield* next()`, all it does it call the next mdw in
47the stack. When that yield point resolves, it means all the mdw functions after
48it have been called. This doesn't necessarily mean all mdw in the stack will be
49called, because like `koa`, you can return early inside a mdw function,
50essentially cancelling all subsequent mdw.
51
52# Context
53
54The context object is just a plain javascript object that gets passed to every
55mdw. The type of `ctx` depends ... on the context. But for thunks, we have this
56basic structure:
57
58```ts
59interface Payload<P> {
60  payload: P;
61}
62
63interface ThunkCtx<P = any> extends Payload<P> {
64  name: string;
65  key: string;
66  action: ActionWithPayload<CreateActionPayload<P>>;
67  actionFn: IfAny<
68    P,
69    CreateAction<ThunkCtx>,
70    CreateActionWithPayload<ThunkCtx<P>, P>
71  >;
72  result: Result<void>;
73}
74```
75
76There are **three** very important properties that you should know about:
77
78- `name` - the name you provided when creating the thunk
79- `payload` - the arbitrary data you passed into the thunk
80- `key` - a hash of `name` and `payload`