-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathroutegroup.js
88 lines (85 loc) · 1.79 KB
/
routegroup.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
const http = require("http");
const httpMethods = http.METHODS;
class RouteGroup {
/**
*
* @param {*} router
* @param {string} path
*/
constructor(router, path, handlers = []) {
if (path[0] !== "/") {
throw new Error("path must begin with '/' in path '" + path + "'");
}
//Strip trailing / (if present) as all added sub paths must start with a /
if (path[path.length - 1] === "/") {
path = path.substr(0, path.length - 1);
}
this.handlers = [...handlers];
this.r = router;
this.p = path;
}
/**
* @param {string} path
*/
subpath(path) {
if (path[0] !== "/") {
throw new Error("path must start with a '/'");
}
if (path === "/") {
return this.p;
}
return this.p + path;
}
/**
*
* @param {string} path
*/
newGroup(path) {
return new RouteGroup(this.r, this.subpath(path), this.handlers);
}
on(method, path, ...handle) {
handle.unshift(...this.handlers);
this.r.on(method, this.subpath(path), ...handle);
return this;
}
get(...arg) {
return this.on("GET", ...arg);
}
put(...arg) {
return this.on("PUT", ...arg);
}
post(...arg) {
return this.on("POST", ...arg);
}
delete(...arg) {
return this.on("DELETE", ...arg);
}
head(...arg) {
return this.on("HEAD", ...arg);
}
patch(...arg) {
return this.on("PATCH", ...arg);
}
options(...arg) {
return this.on("OPTIONS", ...arg);
}
trace(...arg) {
return this.on("TRACE", ...arg);
}
connect(...arg) {
return this.on("CONNECT", ...arg);
}
all(...arg) {
httpMethods.forEach((method) => {
this.on(method, ...arg);
});
return this;
}
use(...handle) {
this.handlers.push(...handle);
}
routes() {
return this.r.routes();
}
}
module.exports = RouteGroup;