-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
194 lines (170 loc) · 4.48 KB
/
router.js
File metadata and controls
194 lines (170 loc) · 4.48 KB
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
import http from 'node:http';
import qs from 'node:querystring';
import { pathToRegexp } from 'path-to-regexp';
import Response from '#app/response';
/**
* Helpers
*/
import StringHelper from '#helpers/string';
/**
* Single route type
* @typedef {{ method: string, handler: function, options: RouteOptions, middlewares: Array<function> }} Route
*/
/**
* Route options type
* @typedef {{ params: Array, exact: boolean, regexp: RegExp }} RouteOptions
*/
class Router {
constructor() {
/**
* Store the current list of routes
*/
this.routes = {};
}
/**
* This function checks for the existence of a route
* and calls its middlewares and handler
*
* @param {http.ClientRequest} req
* @param {Response} res
* @returns
*/
async call(req, res) {
const mask = `${req.method}:${StringHelper.delTrailingSlash(req.url)}`;
const keys = Object.keys(this.routes);
let i = keys.length;
await this.#collectData(req, res);
while (i--) {
let route = this.routes[mask];
/**
* Find exact route
*/
if (this.routes.hasOwnProperty(mask)) {
this.#middlewares(route, req, res).then(() => route.handler(req, res));
return;
}
/* Route url is not exact */
route = this.routes[keys[i]];
/**
* Find route by regular expression
*/
if (!route.options.exact && route.options.regexp !== undefined) {
const match = req.url.match(route.options.regexp);
if (match && keys[i].includes(req.method)) {
if (route.options.params !== undefined) {
req.params = {};
route.options.params.forEach((param) => {
req.params[param.name] = match[1];
});
}
this.#middlewares(route, req, res).then(() =>
route.handler(req, res)
);
return;
}
}
}
res.render('./views/404.hbs', { title: '404 | Page not found' }, 404);
}
/**
* This function will execute every middleware of a route
*
* @param {Route} route Route
* @param {http.ClientRequest} req HTTP Request
* @param {Response} res HTTP Response
* @returns
*/
async #middlewares(route, req, res) {
if (!route || !route.middlewares || !Array.isArray(route.middlewares)) {
return;
}
const middlewares = route.middlewares.flat();
if (middlewares.length !== 0) {
for (const middleware of middlewares) {
await middleware(req, res);
}
}
}
async #collectData(req, res) {
/**
* Collect POST data
*/
if (
req.method === 'POST' &&
req.headers['content-type'] === 'application/x-www-form-urlencoded'
) {
const buffers = [];
for await (const chunk of req) {
if (
req.method === 'POST' &&
req.headers['content-type'] === 'application/x-www-form-urlencoded'
) {
buffers.push(chunk);
}
}
const data = qs.parse(Buffer.concat(buffers).toString());
req['getPostData'] = () => data;
}
}
/**
* Add more routes to router store
*
* @param {string} method HTTP Method
* @param {string} url Route url
* @param {function} handler Route handler function
*/
define(method = 'GET', url, handler) {
const mask = `${method}:${StringHelper.delTrailingSlash(url)}`;
const options = { exact: true, regexp: undefined, params: undefined };
if (url.includes(':')) {
options.params = [];
options.exact = false;
options.regexp = pathToRegexp(url, options.params);
}
this.routes[mask] = {
method,
handler,
options,
middlewares: [],
};
return {
/**
* Store the list of middlewares for each router
*
* @param {function | [function]} middleware
*/
middleware: (middleware) => {
middleware = Array.isArray(middleware) ? middleware : [middleware];
this.routes[mask].middlewares.push(middleware);
},
};
}
/**
* GET Method route
*
* @param {string} url
* @param {function} handler
*/
get(url, handler) {
return this.define('GET', url, handler);
}
/**
* POST Method route
*
* @param {string} url
* @param {function} handler
*/
post(url, handler) {
return this.define('POST', url, handler);
}
/**
* DELETE Method route
*
* @param {*} url
* @param {*} handler
*/
delete(url, handler) {
return this.define('DELETE', url, handler);
}
}
export default new Router();