-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.js
44 lines (36 loc) · 827 Bytes
/
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
class Router {
constructor() {
this.stacks = []
}
register(path, method, middleware) {
this.stacks.push({
path, method, middleware
})
}
get(path, middleware) {
this.register(path, 'get', middleware)
}
post(path, middleware) {
this.register(path, 'post', middleware)
}
routes() {
return async (ctx, next) => {
let url = ctx.url === '/index' ? '/' : ctx.url
let method = ctx.method
let route
for (let i = 0; i < this.stacks.length; i++) {
let item = this.stacks[i]
if (item.path === url && item.method === method) {
route = item.middleware
break
}
}
if (typeof route === 'function') {
await route(ctx, next)
return
}
await next()
}
}
}
module.exports = Router