/
server.ts
335 lines (301 loc) · 10.4 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
import * as Drash from "../../mod.ts";
import { ConnInfo, StdServer } from "../../deps.ts";
interface ResourceAndParams {
resource: Drash.Resource;
pathParams: Map<string, string>;
}
type ResourcesAndPatterns = Map<number, {
resource: Drash.Resource;
patterns: URLPattern[];
}>;
function getResourceAndParams(
url: string,
resources: ResourcesAndPatterns,
): ResourceAndParams | undefined {
let resourceAndParams: ResourceAndParams | undefined = undefined;
for (const { resource, patterns } of resources.values()) {
for (const pattern of patterns) {
const result = pattern.exec(url);
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,
};
break;
}
}
return resourceAndParams;
}
async function runServices(
Services: Drash.Service[],
request: Drash.Request,
response: Drash.Response,
serviceMethod: "runBeforeResource" | "runAfterResource",
): Promise<Error | null> {
let err: Error | null = null;
for (const Service of Services) {
try {
await Service[serviceMethod](request, response);
} catch (e) {
if (!err) {
err = e;
}
}
}
return err;
}
/**
* 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: ResourcesAndPatterns = new Map();
/**
* Our server instance that is serving the app
*/
#server!: StdServer;
/**
* A promise we need to await after calling close() on #server
*/
#serverPromise!: Promise<void>;
/**
* The internal and external services used by this server. Internal services
* are ones created by Drash. External services are ones specified by the
* user.
*/
//////////////////////////////////////////////////////////////////////////////
// FILE MARKER - CONSTRUCTOR /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/**
* @param options - See the interface for the options' schema.
*/
constructor(options: Drash.Interfaces.IServerOptions) {
if (!options.services) {
options.services = [];
}
this.#options = options;
this.#options.resources.forEach((resourceClass) => {
const resource = new resourceClass();
const patterns: URLPattern[] = [];
resource.paths.forEach((path) => {
// Add "{/}?" to match possible trailing slashes too
patterns.push(new URLPattern({ pathname: path + "{/}?" }));
});
this.#resources.set(this.#resources.size, {
resource,
patterns,
});
});
}
//////////////////////////////////////////////////////////////////////////////
// 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 //////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/**
* Close the server.
*/
public async close(): Promise<void> {
try {
this.#server.close();
await this.#serverPromise;
} catch (_error) {
// Do nothing. The server was probably already closed.
}
}
/**
* Run the server.
*/
public run() {
const addr = `${this.#options.hostname}:${this.#options.port}`;
this.#server = new StdServer({ addr, handler: this.#getHandler() });
if (this.#options.protocol === "http") {
this.#serverPromise = this.#server.listenAndServe();
}
if (this.#options.protocol === "https") {
this.#serverPromise = this.#server.listenAndServeTls(
this.#options.cert_file as string,
this.#options.key_file as string,
);
}
}
//////////////////////////////////////////////////////////////////////////////
// FILE MARKER - PRIVATE METHODS /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#getHandler(): (r: Request, connInfo: ConnInfo) => Promise<Response> {
const resources = this.#resources;
const serverServices = this.#options.services ?? [];
return async function (
originalRequest: Request,
connInfo: ConnInfo,
): Promise<Response> {
// Grab resource and path params
const resourceAndParams = getResourceAndParams(
originalRequest.url,
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,
);
// If a service wants to respond early, then allow it but dont run the resource method and still
// allow services to run eg csrf, paladin
let serviceError: Error | null = null;
// Server level services, run before resource
const serverBeforeServicesError = await runServices(
serverServices,
request,
response,
"runBeforeResource",
);
if (serverBeforeServicesError) {
serviceError = serverBeforeServicesError;
}
// If no resource found, then still run server level services for after resource eg paladin,
// then throw a 404
if (!resource) {
await runServices(
serverServices,
request,
response,
"runAfterResource",
);
throw new Drash.Errors.HttpError(404);
}
// If the method does not exist on the resource, then the method is not
// allowed. So, throw that 405 and GTFO and still allow after reosurce server services to run
const method = request.method
.toUpperCase() as Drash.Types.THttpMethod;
if (!(method in resource)) {
await runServices(
serverServices,
request,
response,
"runAfterResource",
);
throw new Drash.Errors.HttpError(405);
}
// By now, we all gucci, do run services and resource method as usual
// Class before resource services
const classBeforeServicesError = await runServices(
resource.services.ALL ?? [],
request,
response,
"runBeforeResource",
);
if (classBeforeServicesError && !serviceError) {
serviceError = classBeforeServicesError;
}
// resource before middleware
const resourceBeforeServicesError = await runServices(
resource.services[method] ?? [],
request,
response,
"runBeforeResource",
);
if (resourceBeforeServicesError && !serviceError) {
serviceError = resourceBeforeServicesError;
}
if (serviceError == null) {
// 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);
}
// after resource middleware. always run
const resourceAfterServicesError = await runServices(
resource.services[method] ?? [],
request,
response,
"runAfterResource",
);
if (resourceAfterServicesError && !serviceError) {
serviceError = resourceAfterServicesError;
}
// Class after resource middleware. always run
const classAfterServicesError = await runServices(
resource.services.ALL ?? [],
request,
response,
"runAfterResource",
);
if (classAfterServicesError && !serviceError) {
serviceError = classAfterServicesError;
}
// Server after resource services. always run
const serverAfterServicesError = await runServices(
serverServices,
request,
response,
"runAfterResource",
);
if (serverAfterServicesError && !serviceError) {
serviceError = serverAfterServicesError;
}
const accept = request.headers.get("accept") ?? "";
const contentType = response.headers.get("content-type") ?? "";
if (accept.includes("*/*") === false) {
if (accept.includes(contentType) === false) {
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.",
);
}
}
if (serviceError) {
throw serviceError;
}
if (response.upgraded && response.upgraded_response) {
return response.upgraded_response;
}
return new Response(response.body, {
headers: response.headers,
statusText: response.statusText,
status: response.status,
});
} catch (e) {
return new Response(e.stack, {
status: e.code,
headers: response.headers,
});
}
};
}
}