-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.ts
50 lines (38 loc) · 1.41 KB
/
handler.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
import Context from './context.ts';
import Handle from './handle.ts';
import Plugin from './plugin.ts';
// interface Options {
// plugins: [];
// }
export default class Handler {
#plugins = new Set();
// constructor (options?: Options) {
// super(options?.plugins);
// }
add (plugin: Handle | Plugin) {
// if (!plugin || typeof plugin === 'object') {
// throw new Error('Handler - not valid requires function or object');
// }
this.#plugins.add(plugin);
}
async handle (request: Request) {
const context = new Context(request);
const iterator = this.#plugins.values();
let result = iterator.next();
while (!result.done) {
const plugin = result.value as any;
let response;
if (plugin && typeof plugin === 'object') {
if (typeof plugin.handle !== 'function') throw new Error('Handler - plugin requires handle method');
response = await plugin.handle(context);
} else if (typeof plugin === 'function') {
response = await plugin(context);
} else {
throw new Error('Handler - not valid requires function or object');
}
if (response instanceof Response) return response;
result = iterator.next();
}
return new Response('Not Found', { status: 404 });
}
}