-
Notifications
You must be signed in to change notification settings - Fork 32
/
server.ts
456 lines (396 loc) · 13 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import * as Drash from "../../mod.ts";
import { ConnInfo, StdServer } from "../../deps.ts";
async function runServices(
Services: Drash.Interfaces.IService[],
request: Drash.Request,
response: Drash.Response,
serviceMethod: "runBeforeResource" | "runAfterResource",
): Promise<void> {
// There are two ways a service can short-circuit the
// request-resource-response lifecycle:
//
// 1. The service throws an error.
// 2. The service calls `request.end()`.
//
// If the service throws an error, then the request handler we pass in to `new
// StdServer()` will catch it and return a response.
//
// If the service calls `request.end()`, then the request handler we pass in
// to `new StdServer()` will return `new Response()`.
for (const Service of Services) {
if (serviceMethod in Service) {
await Service[serviceMethod]!(request, response);
if (request.end_lifecycle) {
break;
}
}
}
}
/**
* This class handles the entire request-resource-response lifecycle. It is in
* charge of handling incoming requests, matching them to resources for further
* processing, and sending responses based on the processes set in the resource.
* It is also in charge of sending error responses that "bubble up" during the
* request-resource-response lifecycle.
*/
export class Server {
/**
* See Drash.Interfaces.IServerOptions.
*/
readonly #options: Drash.Interfaces.IServerOptions;
/**
* A list of all instanced resources the user specified, and
* a url pattern for every path specified. This means when a request
* comes in, the paths are already converted to patterns, saving us time
*/
readonly #resources: Drash.Types.ResourcesAndPatternsMap = new Map();
/**
* Our server instance that is serving the app
*/
#server!: StdServer;
/**
* All services that provide extra functionality to the server and the overall
* application.
*/
#services: Drash.Interfaces.IService[] = [];
/**
* A promise we need to await after calling close() on #server
*/
#server_promise!: Promise<void>;
/**
* A custom Error object handler.
*/
#error_handler!: Drash.Interfaces.IErrorHandler;
/**
* The error handler to use in the event `this.#error_handler` cannot handle
* errors.
*/
#default_error_handler = new Drash.ErrorHandler();
/**
* Property to track request URLs to resources. This is used so that the
* server does not have to find a resource if it was already matched to a
* previous request's URL.
*/
#request_to_resource_map = new Map<
string,
Drash.Interfaces.IResourceAndParams
>();
//////////////////////////////////////////////////////////////////////////////
// FILE MARKER - CONSTRUCTOR /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/**
* @param options - See the interface for the options' schema.
*/
constructor(options: Drash.Interfaces.IServerOptions) {
this.#options = options;
this.#error_handler = new (options.error_handler || Drash.ErrorHandler)();
// Compile the application
this.#addServices();
this.#addResources();
}
//////////////////////////////////////////////////////////////////////////////
// FILE MARKER - GETTERS / SETTERS ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/**
* Get the full address that this server is running on.
*/
get address(): string {
return `${this.#options.protocol}://${this.#options.hostname}:${this.#options.port}`;
}
//////////////////////////////////////////////////////////////////////////////
// FILE MARKER - PUBLIC METHODS //////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/**
* Add the given resource to this server's list of resources.
*
* @param resourceClass - The resource class to instantiate and store in the
* resources map.
*/
public addResource(resourceClass: typeof Drash.Resource): void {
const resource = new resourceClass();
const patterns: URLPattern[] = [];
resource.paths.forEach((path: string) => {
// Add "{/}?" to match possible trailing slashes too
patterns.push(new URLPattern({ pathname: path + "{/}?" }));
});
this.#resources.set(this.#resources.size, {
resource,
patterns,
});
}
/**
* Close the server.
*/
public async close(): Promise<void> {
try {
this.#server.close();
await this.#server_promise;
} catch (_error) {
// Do nothing. The server was probably already closed.
}
}
/**
* Run the server.
*/
public run() {
this.#server = new StdServer({
hostname: this.#options.hostname,
port: this.#options.port,
handler: async (originalRequest: Request, connInfo: ConnInfo) => {
return await this.#handleRequest(originalRequest, connInfo);
},
});
if (this.#options.protocol === "http") {
this.#server_promise = this.#server.listenAndServe();
}
if (this.#options.protocol === "https") {
this.#server_promise = this.#server.listenAndServeTls(
this.#options.cert_file as string,
this.#options.key_file as string,
);
}
}
//////////////////////////////////////////////////////////////////////////////
// FILE MARKER - METHODS - PRIVATE ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/**
* Add all resources to this server -- instantiating them so that they
* are ready to handle requests at runtime.
*/
#addResources(): void {
this.#options.resources?.forEach((resourceClass: typeof Drash.Resource) => {
this.addResource(resourceClass);
});
}
/**
* Add all given services in the options.
*/
#addServices(): void {
if (this.#options.services) {
this.#services = this.#options.services;
}
this.#services.forEach(async (service: Drash.Interfaces.IService) => {
if (service.runAtStartup) {
await service.runAtStartup({
server: this,
resources: this.#resources,
});
}
});
}
/**
* Get the resource associated with the given URL and its path params
* associated with it.
*
* @param url - The URL to match to a resource.
* @param resources - The resources map to use to find the resource.
*/
#getResourceAndParams(
url: string,
resources: Drash.Types.ResourcesAndPatternsMap,
): Drash.Interfaces.IResourceAndParams | undefined {
let resourceAndParams: Drash.Interfaces.IResourceAndParams | undefined =
undefined;
if (this.#request_to_resource_map.has(url)) {
return this.#request_to_resource_map.get(url)!;
}
for (const { resource, patterns } of resources.values()) {
for (const pattern of patterns) {
const result = pattern.exec(url);
// No resource? Check the next one.
if (result === null) {
continue;
}
// this is the resource we need, and below are the params
const params = new Map();
for (const key in result.pathname.groups) {
params.set(key, result.pathname.groups[key]);
}
resourceAndParams = {
resource,
pathParams: params,
};
this.#request_to_resource_map.set(url, resourceAndParams);
break;
}
}
return resourceAndParams;
}
/**
* Handle the given native request. This request gets wrapped around by a
* `Drash.Request` object. Reason being we want to make sure methods like
* `request.bodyAll()` is available in resources.
*
* @param originalRequest The native request from Deno's internals.
* @param connInfo The connection info from Deno's internals.
*
* @returns A native response.
*/
async #handleRequest(
originalRequest: Request,
connInfo: ConnInfo,
): Promise<Response> {
// Grab resource and path params
const resourceAndParams = this.#getResourceAndParams(
originalRequest.url,
this.#resources,
) ?? {
resource: null,
pathParams: new Map(),
};
const { resource, pathParams } = resourceAndParams;
// Construct request and response objects to pass to services and resource
// Keep response top level so we can reuse the headers should an error be thrown
// in the try
const response = new Drash.Response();
try {
const request = await Drash.Request.create(
originalRequest,
pathParams,
connInfo,
this.#options.request ?? {},
);
// Run server-level services (before we get to the resource)
await runServices(
this.#services,
request,
response,
"runBeforeResource",
);
if (request.end_lifecycle) {
return this.#respond(response);
}
// If no resource found, throw 404. Unable to call class/resource services
// when the class doesn't exist!
if (!resource) {
throw new Drash.Errors.HttpError(404);
}
// Run resource-level services (before their HTTP method is called)
await runServices(
resource.services.ALL ?? [],
request,
response,
"runBeforeResource",
);
if (request.end_lifecycle) {
return this.#respond(response);
}
// If the method does not exist on the resource, then the method is not
// allowed. So, throw that 405 and GTFO. Unable to call resource method
// services if the method doesn't exist!
const method = request.method
.toUpperCase() as Drash.Types.HttpMethodName;
if (!(method in resource)) {
throw new Drash.Errors.HttpError(405);
}
// Run resource HTTP method level services (before the HTTP method is
// called)
await runServices(
resource.services[method] ?? [],
request,
response,
"runBeforeResource",
);
if (request.end_lifecycle) {
return this.#respond(response);
}
// Execute the HTTP method on the resource
// Ignoring because we know by now the method exists due to the above check
// deno-lint-ignore ban-ts-comment
// @ts-ignore
await resource[method](request, response);
// Run resource HTTP method level services (after the HTTP method is
// called)
await runServices(
resource.services[method] ?? [],
request,
response,
"runAfterResource",
);
if (request.end_lifecycle) {
return this.#respond(response);
}
// Run resource-level services (after the HTTP method is called)
await runServices(
resource.services.ALL ?? [],
request,
response,
"runAfterResource",
);
if (request.end_lifecycle) {
return this.#respond(response);
}
// Run server-level services as a last step before returning a response
// that the resource has formed
await runServices(
this.#services,
request,
response,
"runAfterResource",
);
if (request.end_lifecycle) {
return this.#respond(response);
}
const requestAcceptHeader = request.headers.get("accept");
const responseContentTypeHeader = response.headers.get("content-type");
if (requestAcceptHeader && responseContentTypeHeader) {
this.#verifyAcceptHeader(
requestAcceptHeader,
responseContentTypeHeader,
);
}
return this.#respond(response);
} catch (e) {
try {
await this.#error_handler.catch(e, originalRequest, response, connInfo);
} catch (e) {
await this.#default_error_handler.catch(
e,
originalRequest,
response,
connInfo,
);
}
return this.#respond(response);
}
}
/**
* Respond to the client making the request.
*
* @param response The response details to use in the `Response` object.
*
* @returns A native Response.
*/
#respond(response: Drash.Response): Response {
if (response.upgraded && response.upgraded_response) {
return response.upgraded_response;
}
return new Response(response.body, {
headers: response.headers,
statusText: response.statusText,
status: response.status,
});
}
/**
* If the request Accept header is present, then make sure the response
* Content-Type header is accepted.
*
* @param requestAcceptHeader
* @param responseContentTypeHeader
*/
#verifyAcceptHeader(
requestAcceptHeader: string,
responseContentTypeHeader: string,
): void {
if (requestAcceptHeader.includes("*/*")) {
return;
}
if (requestAcceptHeader.includes(responseContentTypeHeader)) {
return;
}
throw new Drash.Errors.HttpError(
406,
"The requested resource is only capable of returning content that is not acceptable according to the request's Accept headers.",
);
}
}