-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
314 lines (269 loc) · 11.5 KB
/
router.js
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
/**
* @typedef {["error", function({message: string, err: Error, req: Express.Request}): void]} Events
* @typedef {import("express").NextFunction} Express.NextFunction
* @typedef {import("express").Request} Express.Request
* @typedef {import("express").Response} Express.Response
* @typedef {import("express").Router} Express.Router
* @typedef {import("http-errors").HttpError} HttpErrors.HttpError
* @typedef {import("./routerBase").BaseRoute} RouterBase.BaseRoute
* @typedef {import("./routerBase").Route} RouterBase.Route
* @typedef {import("./routerBase").WebRoute} RouterBase.WebRoute
* @typedef {import("./routerBase").WebsocketRoute} RouterBase.WebsocketRoute
*/
const EventEmitter = require("events").EventEmitter,
fs = require("fs/promises"),
path = require("path"),
express = require("express");
/** @type {{[x: string]: RouterBase.Route}} */
const routes = {};
let notFoundFilename = "",
methodNotAllowedFilename = "",
serverErrorFilename = "";
// #### #
// # # #
// # # ### # # #### ### # ##
// #### # # # # # # # ## #
// # # # # # # # ##### #
// # # # # # ## # # # #
// # # ### ## # ## ### #
/**
* A class that handles the router for the website.
*/
class Router extends EventEmitter {
// # # # # #
// # # # #
// ### ### ### # ## ### ### ## ### ## ###
// # # # # # # # # ## # # ## # # # ## # #
// # ## # # # # # # ## # ## # # ## #
// # # ### ### #### ### ### ## ## # # ## #
/**
* Adds a listener.
* @param {Events} args The arguments.
* @returns {this} The return.
*/
addListener(...args) {
return super.addListener(...args);
}
// ## ###
// # # # #
// # # # #
// ## # #
/**
* Adds a listener.
* @param {Events} args The arguments.
* @returns {this} The return.
*/
on(...args) {
return super.on(...args);
}
// # # ## #
// # # # # #
// ## ### ## ## # # # ### ## ### ##
// # # # # ## # ## # # # # # # # ##
// # # # ## # # # # # # ## # # # ##
// ## # # ## ## # # ## # # ## # # ##
/**
* Checks the cache and refreshes it if necessary.
* @param {string} file The name of the class.
* @returns {Promise} A promise that resolves once the cache is checked.
*/
async checkCache(file) {
// Ensure we've already loaded the class, otherwise bail.
const route = routes[file];
if (!route) {
throw new Error("Invald class name.");
}
const stats = await fs.stat(require.resolve(route.file));
if (!route.lastModified || route.lastModified.getTime() !== stats.mtime.getTime()) {
delete require.cache[require.resolve(route.file)];
route.class = require(route.file);
route.lastModified = stats.mtime;
}
}
// # ## ##
// # # # #
// ### ## ### # # ### ### ### ## ###
// # # # ## # # # # # ## ## # ## ##
// ## ## # # # # # ## ## ## ## ##
// # ## ## ## ### # # ### ### ## ###
// ###
/**
* Gets all of the available classes.
* @param {string} dir The directory to get the classes for.
* @returns {Promise} A promise that resolves when all the classes are retrieved.
*/
async getClasses(dir) {
const list = await fs.readdir(dir);
for (const file of list) {
const filename = path.resolve(dir, file);
const stat = await fs.stat(filename);
if (stat && stat.isDirectory()) {
await this.getClasses(filename);
} else {
const routeClass = require(filename);
/** @type {RouterBase.Route} */
const route = routeClass.route;
routes[filename] = route;
if (route.webSocket) {
routes[filename].events = Object.getOwnPropertyNames(routeClass).filter((p) => typeof routeClass[p] === "function");
} else if (!route.include) {
routes[filename].methods = Object.getOwnPropertyNames(routeClass).filter((p) => typeof routeClass[p] === "function");
}
if (route.notFound) {
notFoundFilename = filename;
} else if (route.methodNotAllowed) {
methodNotAllowedFilename = filename;
} else if (route.serverError) {
serverErrorFilename = filename;
}
routes[filename].file = filename;
this.checkCache(filename);
}
}
}
// # ### #
// # # # #
// ### ## ### # # ## # # ### ## ###
// # # # ## # ### # # # # # # ## # #
// ## ## # # # # # # # # ## #
// # ## ## # # ## ### ## ## #
// ###
/**
* Gets the router to use for the website.
* @param {string} routesPath The directory with the route classes.
* @param {object} [options] The options to use.
* @param {boolean} [options.hot] Whether to use hot reloading for RouterBase classes. Defaults to true.
* @returns {Promise<Express.Router>} A promise that resolves with the router to use for the website.
*/
async getRouter(routesPath, options) {
options = {...{hot: false}, ...options || {}};
await this.getClasses(routesPath);
const router = express.Router(),
filenames = Object.keys(routes),
includes = filenames.filter((c) => routes[c].include),
webSockets = filenames.filter((c) => routes[c].webSocket),
pages = filenames.filter((c) => !routes[c].include && !routes[c].webSocket && routes[c].path && routes[c].methods && routes[c].methods.length > 0);
// Set up websocket routes.
webSockets.forEach((filename) => {
const route = /** @type {RouterBase.BaseRoute & RouterBase.WebsocketRoute} */(routes[filename]); // eslint-disable-line no-extra-parens
router.ws(route.path, ...route.middleware, (ws, req) => {
// @ts-ignore
ws._url = req.url.replace("/.websocket", "").replace(".websocket", "") || "/";
route.events.forEach((event) => {
ws.on(event === "connection" ? "_init" : event, (...args) => {
route.class[event](ws, ...args);
});
});
// Since the connection event is not re-fired, we use the _init event to forward the connection event to the client.
ws.emit("_init", req);
});
});
// Set up page routes.
pages.forEach((filename) => {
const route = /** @type {RouterBase.BaseRoute & RouterBase.WebRoute} */(routes[filename]); // eslint-disable-line no-extra-parens
route.methods.forEach((method) => {
router[method](route.path, ...route.middleware, async (/** @type {Express.Request} */ req, /** @type {Express.Response} */ res, /** @type {function} */ next) => {
if (res.headersSent) {
return;
}
try {
if (options.hot) {
for (const include of includes) {
await this.checkCache(include);
}
await this.checkCache(filename);
}
if (!route.class[req.method.toLowerCase()]) {
if (methodNotAllowedFilename !== "") {
await routes[methodNotAllowedFilename].class.get(req, res, next);
return;
}
res.status(405).send("HTTP 405 Method Not Allowed");
return;
}
await route.class[req.method.toLowerCase()](req, res, next);
return;
} catch (err) {
this.emit("error", {
message: `An error occurred in ${req.method.toLowerCase()} ${route.path} from ${req.ip} for ${req.url}.`,
err, req
});
}
if (serverErrorFilename !== "") {
await routes[serverErrorFilename].class.get(req, res, next);
return;
}
res.status(500).send("HTTP 500 Server Error");
});
});
});
// 404 remaining pages.
router.use(async (req, res, next) => {
if (res.headersSent) {
return;
}
if (notFoundFilename !== "") {
await routes[notFoundFilename].class.get(req, res, next);
return;
}
res.status(404).send("HTTP 404 Not Found");
});
// 500 errors.
router.use(async (err, req, res, next) => {
if (err.status && err.status !== 500 && err.expose) {
if (res.headersSent) {
return;
}
res.status(err.status).send(err.message);
} else {
this.emit("error", {
message: "An unhandled error has occurred.",
err, req
});
if (res.headersSent) {
return;
}
if (serverErrorFilename !== "") {
await routes[serverErrorFilename].class.get(req, res, next);
return;
}
res.status(500).send("HTTP 500 Server Error");
}
});
return router;
}
// ## ### ### ## ###
// # ## # # # # # # # #
// ## # # # # #
// ## # # ## #
/**
* Handles a router error.
* @param {HttpErrors.HttpError} err The error object.
* @param {Express.Request} req The request.
* @param {Express.Response} res The response.
* @param {Express.NextFunction} next The function to be called if the error is not handled.
* @returns {Promise} A promise that resolves when the error is handled.
*/
async error(err, req, res, next) {
if (err.status && err.status !== 500 && err.expose) {
if (res.headersSent) {
return;
}
res.status(err.status).send(err.message);
} else {
this.emit("error", {
message: "An unhandled error has occurred.",
err, req
});
if (res.headersSent) {
return;
}
if (serverErrorFilename !== "") {
await routes[serverErrorFilename].class.get(req, res, next);
return;
}
res.status(500).send("HTTP 500 Server Error");
}
}
}
module.exports = Router;