-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-router.js
More file actions
43 lines (31 loc) · 913 Bytes
/
http-router.js
File metadata and controls
43 lines (31 loc) · 913 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
36
37
38
39
40
41
42
// Условие и примеры https://maxcode.dev/problems/http-router/
class HttpRouter {
constructor() {
this.requests = {};
}
addHandler(path, verb, cb) {
this.requests[path] ??= {};
this.requests[path][verb] = cb;
}
runRequest(path, verb) {
return this.requests?.[path]?.[verb]?.() ?? 'Error 404: Not Found';
}
}
const router = new HttpRouter();
router.addHandler("/api/users", "GET", () => {
return ["user1", "user2"];
});
router.addHandler("/api/users", "POST", () => {
return "User added";
});
router.addHandler("/api/login", "POST", () => {
return "OK";
});
console.log(router.runRequest("/api/users", "GET"));
// ["user1", "user2"]
console.log(router.runRequest("/api/login", "POST"));
// "OK"
console.log(router.runRequest("/api/login", "PUT"));
// "Error 404: Not Found"
console.log(router.runRequest("/api/send", "POST"));
// "Error 404: Not Found"