-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
33 lines (30 loc) · 959 Bytes
/
index.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
module.exports = (sessionRef, opts) => {
const options = Object.assign({
property: 'session',
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}/${ctx.chat.id}`
}, opts)
function getSession (key) {
return sessionRef.child(key).once('value')
.then((snapshot) => snapshot.val())
}
function saveSession (key, session) {
if (!session || Object.keys(session).length === 0) {
return sessionRef.child(key).remove()
}
return sessionRef.child(key).set(session)
}
return (ctx, next) => {
const key = options.getSessionKey(ctx)
if (!key) {
return next()
}
return getSession(key).then((value) => {
let session = value || {}
Object.defineProperty(ctx, options.property, {
get: function () { return session },
set: function (newValue) { session = Object.assign({}, newValue) }
})
return next().then(() => saveSession(key, session))
})
}
}