forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.js
More file actions
29 lines (27 loc) · 817 Bytes
/
session.js
File metadata and controls
29 lines (27 loc) · 817 Bytes
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
module.exports = function (opts) {
opts = Object.assign({
property: 'session',
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`
}, opts)
const ttlMs = opts.ttl && opts.ttl * 1000
const store = new Map()
return (ctx, next) => {
const key = opts.getSessionKey(ctx)
if (!key) {
return next(ctx)
}
const now = new Date().getTime()
let { session, expires } = store.get(key) || { session: {} }
if (expires && expires < now) {
session = {}
}
Object.defineProperty(ctx, opts.property, {
get: function () { return session },
set: function (newValue) { session = Object.assign({}, newValue) }
})
return next(ctx).then(() => store.set(key, {
session,
expires: ttlMs ? now + ttlMs : null
}))
}
}