-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomRouter.js
79 lines (71 loc) · 1.64 KB
/
CustomRouter.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
import { parse } from "url";
export default class CustomRouter {
#listeners = {
ACL: [],
BIND: [],
CHECKOUT: [],
CONNECT: [],
COPY: [],
DELETE: [],
GET: [],
HEAD: [],
LINK: [],
LOCK: [],
MERGE: [],
MKACTIVITY: [],
MKCALENDAR: [],
MKCOL: [],
MOVE: [],
NOTIFY: [],
OPTIONS: [],
PATCH: [],
POST: [],
PRI: [],
PROPFIND: [],
PROPPATCH: [],
PURGE: [],
PUT: [],
REBIND: [],
REPORT: [],
SEARCH: [],
SOURCE: [],
SUBSCRIBE: [],
TRACE: [],
UNBIND: [],
UNLINK: [],
UNLOCK: [],
UNSUBSCRIBE: [],
};
#errorListener = function (req, res) {
res.writeHead(404);
res.end();
};
#mapping = new Map();
on = function (method, url, callback) {
if (this.#mapping.has(url)) {
console.error(`Error : Duplicate ${url} : Ignoring Endpoint`);
} else {
this.#listeners[method].push({ url, callback });
this.#mapping.set(url, this.#listeners[method].length - 1);
}
};
route = function (req, res, time = Date.now()) {
const pathname = parse(req.url, true).pathname;
const callback = this.#getListener(pathname, req.method.toUpperCase());
if (callback === undefined) {
this.#errorListener(req, res);
} else {
callback(req, res);
}
console.log(`${req.url}: Request took ${Date.now() - time}ms`);
};
#getListener = function (url, method) {
if (this.#mapping.has(url)) {
const index = this.#mapping.get(url);
if (this.#listeners[method][index].url === url) {
return this.#listeners[method][index].callback;
}
}
return undefined;
};
}