import type { GenericRecord } from "@webiny/api/types.js"; export type Middleware = ( input: Input, next: () => Promise ) => Promise; export function middleware( middlewares: Middleware[] ) { return async function runner(input: Input, defaultValue: Output): Promise { let current = -1; async function dispatch(index: number): Promise { /** * Should not be possible to run next multiple times. * Or do we want to allow it? What are possible downsides except something being done multiple times? */ if (index <= current) { throw new Error("next() called multiple times"); } current = index; const fn = middlewares[index]; if (!fn) { return defaultValue; } return fn(input, () => dispatch(index + 1)); } return dispatch(0); }; }