// Copyright 2018-2020 the oak authors. All rights reserved. MIT license. // deno-lint-ignore-file import type { State } from "./application.ts"; import type { Context } from "./context.ts"; /** Middleware are functions which are chained together to deal with requests. */ export interface Middleware< S extends State = Record, T extends Context = Context, > { (context: T, next: () => Promise): Promise | void; } /** Compose multiple middleware functions into a single middleware function. */ export function compose< S extends State = Record, T extends Context = Context, >( middleware: Middleware[], ): (context: T, next?: () => Promise) => Promise { return function composedMiddleware( context: T, next?: () => Promise, ): Promise { let index = -1; async function dispatch(i: number): Promise { if (i <= index) { throw new Error("next() called multiple times."); } index = i; let fn: Middleware | undefined = middleware[i]; if (i === middleware.length) { fn = next; } if (!fn) { return; } await fn(context, dispatch.bind(null, i + 1)); } return dispatch(0); }; }