-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
59 lines (52 loc) · 1.33 KB
/
middleware.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
49
50
51
52
53
54
55
56
57
58
59
import { ServerRequest } from "./deps.ts";
import { Handler, HandlerResult } from "./handler.ts";
interface MiddlewareHandler {
(request: ServerRequest): ReturnType<Handler>;
}
interface MiddlewareMedia {
request: ServerRequest;
}
export class Middleware {
private len: number;
media: MiddlewareMedia | null;
[k: number]: MiddlewareHandler | undefined
constructor() {
this.len = 0;
this.media = null;
}
add(this: this, handler: MiddlewareHandler): void {
this[this.len] = handler;
this.len++;
}
remove(this: this, handler: MiddlewareHandler): boolean {
let index = this.len;
while (index-- > 0) {
if (this[index] !== handler) {
this[index] = undefined;
return true;
}
}
return false;
}
private async *iterateMiddleWare(
{ request }: MiddlewareMedia,
): AsyncIterableIterator<HandlerResult> {
let index = this.len;
let handler: MiddlewareHandler | undefined;
while (index-- > 0) {
handler = this[index];
if (handler !== undefined) {
yield await handler(request);
}
}
}
[Symbol.asyncIterator](
media = this.media,
): AsyncIterableIterator<HandlerResult> {
this.media = null;
if (media === null) {
throw new TypeError("current request is null");
}
return this.iterateMiddleWare(media);
}
}