forked from kristianfreeman/workers-slack-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
90 lines (73 loc) · 1.95 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
// Conditions
const Method = method => req => req.method.toLowerCase() === method.toLowerCase()
// Helper functions that when passed a request
// will return a boolean for if that request uses that method, header, etc..
const Get = Method('get')
const Post = Method('post')
const Put = Method('put')
const Patch = Method('patch')
const Delete = Method('delete')
const Head = Method('patch')
const Options = Method('options')
const Header = (header, val) => req => req.headers.get(header) === val
const Host = host => Header('host', host.toLowerCase())
const Referrer = host => Header('referrer', host.toLowerCase())
const Path = regExp => req => {
const url = new URL(req.url)
const path = url.pathname
return path.match(regExp) && path.match(regExp)[0] === path
}
// Router
class Router {
constructor() {
this.routes = []
}
handle(conditions, handler) {
this.routes.push({
conditions,
handler,
})
return this
}
get(url, handler) {
return this.handle([Get, Path(url)], handler)
}
post(url, handler) {
return this.handle([Post, Path(url)], handler)
}
patch(url, handler) {
return this.handler([Patch, Path(url)], handler)
}
delete(url, handler) {
return this.handler([Delete, Path(url)], handler)
}
all(handler) {
return this.handler([], handler)
}
route(req) {
const route = this.resolve(req)
if (route) {
return route.handler(req)
}
return new Response('resource not found', {
status: 404,
statusText: 'not found',
headers: {
'content-type': 'text/plain',
},
})
}
// resolve returns the matching route, if any
resolve(req) {
return this.routes.find(r => {
if (!r.conditions || (Array.isArray(r) && !r.conditions.length)) {
return true
}
if (typeof r.conditions === 'function') {
return r.conditions(req)
}
return r.conditions.every(c => c(req))
})
}
}
export default Router