forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
43 lines (38 loc) · 1.08 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
const { compose, lazy, passThru } = require('./composer')
class Router {
constructor (routeFn, handlers = new Map()) {
if (!routeFn) {
throw new Error('Missing routing function')
}
this.routeFn = routeFn
this.handlers = handlers
this.otherwiseHandler = passThru()
}
on (route, ...fns) {
if (fns.length === 0) {
throw new TypeError('At least one handler must be provided')
}
this.handlers.set(route, compose(fns))
return this
}
otherwise (...fns) {
if (fns.length === 0) {
throw new TypeError('At least one otherwise handler must be provided')
}
this.otherwiseHandler = compose(fns)
return this
}
middleware () {
return lazy((ctx) => {
return Promise.resolve(this.routeFn(ctx)).then((result) => {
if (!result || !result.route || !this.handlers.has(result.route)) {
return this.otherwiseHandler
}
Object.assign(ctx, result.context)
Object.assign(ctx.state, result.state)
return this.handlers.get(result.route)
})
})
}
}
module.exports = Router