forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.ts
46 lines (40 loc) · 1.51 KB
/
application.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
// Copyright 2018-2019 the oak authors. All rights reserved. MIT license.
import { Context } from "./context.ts";
import { compose, Middleware } from "./middleware.ts";
import { serve, Server } from "./deps.ts";
/** A class which registers middleware (via `.use()`) and then processes
* inbound requests against that middleware (via `.listen()`).
*
* The `context.state` can be typed via passing a generic argument when
* constructing an instance of `Application`.
*/
export class Application<S extends object = { [key: string]: any }> {
private _middleware: Middleware<S, Context<S>>[] = [];
private _serve: typeof serve;
/** Generic state of the application, which can be specified by passing the
* generic argument when constructing:
*
* const app = new Application<{ foo: string }>();
*/
state = {} as S;
constructor(_serve = serve) {
this._serve = _serve;
}
/** Start listening for requests, processing registered middleware on each
* request.
*/
async listen(addr: string): Promise<void> {
const middleware = compose<S, Context<S>>(this._middleware);
const server = this._serve(addr);
for await (const request of server) {
const context = new Context<S>(this, request);
await middleware(context);
await request.respond(context.response.toServerResponse());
}
}
/** Register middleware to be used with the application. */
use(...middleware: Middleware<S, Context<S>>[]): this {
this._middleware.push(...middleware);
return this;
}
}