-
Notifications
You must be signed in to change notification settings - Fork 2
/
Server.ts
208 lines (178 loc) · 6.06 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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";
import xmlParse from "https://denopkg.com/nekobato/deno-xml-parser/index.ts";
export class Server {
private routes: Map<string, EndpointRoutes> = new Map();
private staticHandler: StaticHandler | undefined;
private bodyParsers: Map<string, (body: string) => any> = new Map();
constructor() {
this.bodyParsers.set("application/json", JSON.parse);
this.bodyParsers.set("application/x-www-form-urlencoded", (body) => {
const bodyObj: { [key: string]: string } = {};
const formBits = body.split("&");
for (const bit of formBits) {
const [key, val] = bit.split("=");
bodyObj[decodeURIComponent(key)] = decodeURIComponent(val);
}
return bodyObj;
});
this.bodyParsers.set("application/xml", xmlParse);
}
/**
* Register endpoints with the Server.
*
* @deprecated Will be removed or rewritten by 1.0. Use useRoute() to register endpoints
*/
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);
}
/**
* Register an endpoint and its associated routes with the Server
*
* @param endpoint - The object generated by the Router class
*/
public useRoute(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);
}
/**
* Register a body parser based on a given content type.
*
* @param contentType - A valid HTTP Content-Type (ex: application/json)
* @param func - A function that takes a stringified body and return a desired value
*/
public useParser(contentType: string, func: (body: string) => any): void {
this.bodyParsers.set(contentType, func);
}
/**
* Register which folder should be returned as static assets.
*
* @param localFolderPath - Path to the folder
* @param urlPrefix - Endpoint that will be called to load the assets
*/
public async static(localFolderPath: string, urlPrefix: string = "") {
if (!(await exists(localFolderPath))) {
return;
}
this.staticHandler = new StaticHandler(localFolderPath, urlPrefix);
}
private async listenAndServeHandler(req: ServerRequest) {
const [url, queryString] = req.url.split("?");
const pathBits = this.parsePathBits(url);
const query: {
[key: string]: string;
} = {};
if (queryString) {
for (const param of queryString.split("&")) {
const [key, value] = param.split("=");
query[key] = value;
}
}
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) {
const route = (routePrefix + endpoint).replace(/(\/\/)/g, "/");
if (
url === route ||
this.doesRouteMatch(
pathBits,
this.parsePathBits(
route,
),
)
) {
const param: { [key: string]: string } = {};
if (route.includes("{")) {
this.parsePathBits(route).forEach((bit, index) => {
if (bit.match(/{([A-Z, a-z,0-9]+)}/)) {
const key = bit.replace("{", "").replace("}", "");
param[key] = pathBits[index];
}
});
}
func(req, {
query,
param,
body: this.parseBody(
new TextDecoder("utf-8").decode(
await Deno.readAll(req.body),
),
req.headers,
),
});
return;
}
}
}
}
if (
this.staticHandler &&
req.url.indexOf(this.staticHandler.staticUrlPrefix) === 0
) {
this.staticHandler.process(req);
return;
}
req.respond({ status: 404 });
}
private parsePathBits(path: string): string[] {
const bits = path.split("/");
bits.shift();
return bits;
}
private doesRouteMatch(req: string[], route: string[]): boolean {
if (req.length !== route.length) return false;
for (let i = 0; i < route.length; i++) {
if (
!(req[i] === route[i] || route[i].match(/{([A-Z, a-z,0-9]+)}/))
) {
return false;
}
}
return true;
}
private parseBody(body: string, headers: Headers): any {
const contentType = headers.get("content-type");
if (!contentType) return body;
try {
if (this.bodyParsers.get(contentType)) {
return this.bodyParsers.get(contentType)?.(body);
}
} catch (e) {
console.error(e);
return {};
}
return body;
}
/**
* Start the server
*
* @param config - Deno.ListenOptions object
*/
public async start(config: Deno.ListenOptions) {
listenAndServe(config, this.listenAndServeHandler.bind(this));
return config;
}
}