forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 6
/
stage.js
51 lines (44 loc) · 1.22 KB
/
stage.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
const SceneContext = require('./scenes/context')
const Composer = require('./composer')
const { compose, optional, lazy, safePassThru } = Composer
class Stage extends Composer {
constructor (scenes = [], options) {
super()
this.options = {
sessionName: 'session',
...options
}
this.scenes = new Map()
scenes.forEach((scene) => this.register(scene))
}
register (...scenes) {
scenes.forEach((scene) => {
if (!scene || !scene.id || typeof scene.middleware !== 'function') {
throw new Error('telegraf: Unsupported scene')
}
this.scenes.set(scene.id, scene)
})
return this
}
middleware () {
const handler = compose([
(ctx, next) => {
ctx.scene = new SceneContext(ctx, this.scenes, this.options)
return next()
},
super.middleware(),
lazy((ctx) => ctx.scene.current || safePassThru())
])
return optional((ctx) => ctx[this.options.sessionName], handler)
}
static enter (...args) {
return (ctx) => ctx.scene.enter(...args)
}
static reenter (...args) {
return (ctx) => ctx.scene.reenter(...args)
}
static leave (...args) {
return (ctx) => ctx.scene.leave(...args)
}
}
module.exports = Stage