-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
36 lines (33 loc) · 1012 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
34
35
36
const {selectById, insert, defSession} = require('./helpers');
module.exports = function (opts) {
opts = Object.assign({
property: 'session',
table_name: 'telegraf_session',
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`
}, opts);
const store = new Map();
return (ctx, next) => {
const key = opts.getSessionKey(ctx);
if (!key) {
return next(ctx)
}
let {session} = store.get(key) || {};
if (!session) {
selectById(key, opts)
.then(rows => {
if (rows.length) {
session = JSON.parse(rows[0].session);
return defSession(ctx, next, session, opts, key, store)
} else {
session = {};
insert(key, JSON.stringify(session), opts)
.then(() => {
return defSession(ctx, next, session, opts, key, store)
})
}
})
} else {
return defSession(ctx, next, session, opts, key, store)
}
}
};