-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
133 lines (115 loc) · 3.52 KB
/
router.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
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
class Router {
constructor(){
this._routes = []
this._prefix = ''
}
route(specs, methods, handlers){
if(this._prefix !== ''){
specs = `${this._prefix}/${specs}`
}
handlers = this._cleanHandlers(handlers)
this._routes.push({
methods,
...this._patternToRegex(specs),
handlers
})
}
group(prefix, fn){
this._prefix = prefix
fn(this)
this._prefix = ''
}
all(specs, handlers){
this.route(specs, ['GET', 'POST', 'PUT', 'DELETE'], handlers)
}
get(specs, handlers){
this.route(specs, ['GET'], handlers)
}
post(specs, handlers){
this.route(specs, ['POST'], handlers)
}
put(specs, handlers){
this.route(specs, ['PUT'], handlers)
}
delete(specs, handlers){
this.route(specs, ['DELETE'], handlers)
}
_dispatch(request, response){
let match, handledRequest = false, {url} = request
for(let route of this._routes){
// Keep trying till we find a match
match = url.match(route.regex)
if(match === null || !route.methods.includes(request.method)){
continue
}
// Collect route params value when match found
match = match.filter(item => {
return !item || !item.startsWith('/')
})
request.params = route.params.reduce((obj, param, idx) => {
obj[param] = match[idx]
return obj
}, {})
// Create handler chain and start processing request
let nextHandler
const handlerStack = route.handlers.slice().reverse()
const params = Object.values(request.params)
for(const handler of handlerStack){
let lastNext = nextHandler
const next = () => {
handler(request, response, lastNext, ...params)
}
nextHandler = next
}
nextHandler()
handledRequest = true
break;
}
if(handledRequest){
return
}
response.statusCode = 404;
response.end("Not Found !")
}
_patternToRegex(pattern){
/* example of transformation
* /student/:id -> ^/student/([_a-zA-Z0-9\-]+)$
* /project/:name/:sprint? -> ^/project/([_a-zA-Z0-9\-]+)(\/([_a-zA-Z0-9\-]+))?$
*/
let regex = ''
let params = []
let parts = pattern.split('/')
for(let part of parts){
if(part.trim() === '')
continue
if(part.startsWith(':')){
if(part.endsWith('?')){
regex += '(/([_a-zA-Z0-9\\-]+))?'
} else {
regex += '/([_a-zA-Z0-9\\-]+)'
}
params.push(part.replace(/(\?|:)/g, ''))
continue
}
regex += `/${part}`
}
// Handle special case (e.i web root)
if(regex === ''){
regex = '/'
}
regex = new RegExp(`^${regex}$`)
return {regex , params}
}
_cleanHandlers(handlers){
if(!Array.isArray(handlers)){
handlers = [handlers]
}
for(let handler of handlers){
if(typeof handler !== 'function'){
throw new Error('Route handler should be callable')
}
}
return handlers
}
}
module.exports = Router