-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
35 lines (29 loc) · 834 Bytes
/
router.js
File metadata and controls
35 lines (29 loc) · 834 Bytes
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
class Router {
constructor (server) {
this._server = server;
this._routes = {};
this._server.use(this._onRequest.bind(this));
}
/**
* Registers the method and route to the given handler.
* @param {string} method The HTTP method for this route.
* @param {string} route The path to handle.
* @param {function} handler The function to handle an incoming request.
*/
_register (method, route, handler) {
this._routes[`${method.toUpperCase()}:${route}`] = handler;
}
_onRequest (ctx) {
const compiled = `${ctx.method}:${ctx.path}`;
if (compiled in this._routes) {
this._routes[compiled](ctx);
}
}
get (route, handler) {
this._register('GET', route, handler);
}
post (route, handler) {
this._register('POST', route, handler);
}
}
module.exports = Router;