forked from neurosnap/starfx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompose.ts
48 lines (42 loc) · 1.41 KB
/
compose.ts
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
import { call } from "./fx/mod.ts";
import type { Next } from "./query/mod.ts";
import type { Instruction, Operation, Result } from "./deps.ts";
import { Err, Ok } from "./deps.ts";
// deno-lint-ignore no-explicit-any
export type BaseCtx = Record<string, any>;
export type BaseMiddleware<Ctx extends BaseCtx = BaseCtx, T = unknown> = (
ctx: Ctx,
next: Next,
) => Operation<T>;
export function compose<Ctx extends BaseCtx = BaseCtx, T = unknown>(
middleware: BaseMiddleware<Ctx, T>[],
) {
if (!Array.isArray(middleware)) {
throw new TypeError("Middleware stack must be an array!");
}
for (const fn of middleware) {
if (typeof fn !== "function") {
throw new TypeError("Middleware must be composed of functions!");
}
}
return function* composeFn(context: Ctx, next?: BaseMiddleware<Ctx, T>) {
// last called middleware #
let index = -1;
function* dispatch(i: number): Generator<Instruction, Result<T>, void> {
if (i <= index) {
return Err(new Error("next() called multiple times"));
}
index = i;
let fn: BaseMiddleware<Ctx, T> | undefined = middleware[i];
if (i === middleware.length) {
fn = next;
}
if (!fn) return Err(new Error("fn is falsy"));
const nxt = dispatch.bind(null, i + 1);
const result = yield* fn(context, nxt);
return Ok(result);
}
yield* call(() => dispatch(0));
return context;
};
}