Started to implement server
This commit is contained in:
1 parent
1f2ea8b7e5
commit
17a1b4bed3
177 files changed
+29894
-74
No files matched your search
+46
@@ -0,0 +1,46 @@
|
||||
// Copyright 2018-2022 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<string, any>,
|
||||
T extends Context = Context<S>,
|
||||
> {
|
||||
(context: T, next: () => Promise<unknown>): Promise<unknown> | unknown;
|
||||
}
|
||||
|
||||
/** Compose multiple middleware functions into a single middleware function. */
|
||||
export function compose<
|
||||
S extends State = Record<string, any>,
|
||||
T extends Context = Context<S>,
|
||||
>(
|
||||
middleware: Middleware<S, T>[],
|
||||
): (context: T, next?: () => Promise<unknown>) => Promise<unknown> {
|
||||
return function composedMiddleware(
|
||||
context: T,
|
||||
next?: () => Promise<unknown>,
|
||||
): Promise<unknown> {
|
||||
let index = -1;
|
||||
|
||||
async function dispatch(i: number): Promise<void> {
|
||||
if (i <= index) {
|
||||
throw new Error("next() called multiple times.");
|
||||
}
|
||||
index = i;
|
||||
let fn: Middleware<S, T> | undefined = middleware[i];
|
||||
if (i === middleware.length) {
|
||||
fn = next;
|
||||
}
|
||||
if (!fn) {
|
||||
return;
|
||||
}
|
||||
await fn(context, dispatch.bind(null, i + 1));
|
||||
}
|
||||
|
||||
return dispatch(0);
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user