-
Notifications
You must be signed in to change notification settings - Fork 2
/
Server.ts
64 lines (55 loc) · 2.01 KB
/
Server.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
60
61
62
63
64
import { Endpoint, EndpointRoutes, QueryType, EndpointMap } from "./types.ts";
import {
listenAndServe,
ServerRequest,
} from "https://deno.land/std/http/server.ts";
import { exists } from "https://deno.land/std/fs/exists.ts";
import { StaticHandler } from "./StaticHandler.ts";
export class Server {
private routes: Map<string, EndpointRoutes> = new Map();
private staticHandler: StaticHandler | undefined;
public use(endpoint: Endpoint) {
const endpoints: EndpointRoutes = new Map();
endpoints.set(QueryType.GET, endpoint.routes.getRoutes);
endpoints.set(QueryType.POST, endpoint.routes.postRoutes);
endpoints.set(QueryType.PUT, endpoint.routes.putRoutes);
endpoints.set(QueryType.DELETE, endpoint.routes.deleteRoutes);
endpoints.set(QueryType.HEAD, endpoint.routes.headRoutes);
endpoints.set(QueryType.PATCH, endpoint.routes.patchRoutes);
endpoints.set(QueryType.OPTIONS, endpoint.routes.optionsRoutes);
this.routes.set(endpoint.uri, endpoints);
}
public async static(localFolderPath: string, urlPrefix: string = "") {
if (!(await exists(localFolderPath))) {
return;
}
this.staticHandler = new StaticHandler(localFolderPath, urlPrefix);
}
private async listenAndServeHandler(req: ServerRequest) {
for (const [routePrefix, routePrefixEndpoints] of this.routes) {
let methodRoutes: EndpointMap | undefined = routePrefixEndpoints.get(
req.method as QueryType
);
if (methodRoutes) {
for (const [endpoint, func] of methodRoutes) {
if (req.url === (routePrefix + endpoint).replace(/(\/\/)/g, "/")) {
func(req);
return;
}
}
}
}
if (
this.staticHandler &&
req.url.indexOf(this.staticHandler.staticUrlPrefix) === 0
) {
this.staticHandler.process(req);
return;
}
req.respond({ status: 404 });
}
public async start(config: Deno.ListenOptions) {
listenAndServe(config, this.listenAndServeHandler.bind(this));
return config;
}
}