forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.js
33 lines (31 loc) · 950 Bytes
/
session.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 = function (opts) {
const options = {
property: 'session',
store: new Map(),
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`,
...opts
}
const ttlMs = options.ttl && options.ttl * 1000
return (ctx, next) => {
const key = options.getSessionKey(ctx)
if (!key) {
return next(ctx)
}
const now = new Date().getTime()
return Promise.resolve(options.store.get(key))
.then((state) => state || { session: {} })
.then(({ session, expires }) => {
if (expires && expires < now) {
session = {}
}
Object.defineProperty(ctx, options.property, {
get: function () { return session },
set: function (newValue) { session = { ...newValue } }
})
return next(ctx).then(() => options.store.set(key, {
session,
expires: ttlMs ? now + ttlMs : null
}))
})
}
}