UNPKG

2.92 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.isSessionContext = exports.MemorySessionStore = exports.session = void 0;
4/**
5 * Returns middleware that adds `ctx.session` for storing arbitrary state per session key.
6 *
7 * The default `getSessionKey` is <code>\`${ctx.from.id}:${ctx.chat.id}\`</code>.
8 * If either `ctx.from` or `ctx.chat` is `undefined`, default session key and thus `ctx.session` are also `undefined`.
9 *
10 * Session data is kept only in memory by default,
11 * which means that all data will be lost when the process is terminated.
12 * If you want to store data across restarts, or share it among workers,
13 * you can [install persistent session middleware from npm](https://www.npmjs.com/search?q=telegraf-session),
14 * or pass custom `storage`.
15 *
16 * @example https://github.com/telegraf/telegraf/blob/develop/docs/examples/session-bot.ts
17 * @deprecated https://github.com/telegraf/telegraf/issues/1372#issuecomment-782668499
18 */
19function session(options) {
20 var _a, _b;
21 const getSessionKey = (_a = options === null || options === void 0 ? void 0 : options.getSessionKey) !== null && _a !== void 0 ? _a : defaultGetSessionKey;
22 const store = (_b = options === null || options === void 0 ? void 0 : options.store) !== null && _b !== void 0 ? _b : new MemorySessionStore();
23 return async (ctx, next) => {
24 const key = await getSessionKey(ctx);
25 if (key == null) {
26 return await next();
27 }
28 ctx.session = await store.get(key);
29 await next();
30 if (ctx.session == null) {
31 await store.delete(key);
32 }
33 else {
34 await store.set(key, ctx.session);
35 }
36 };
37}
38exports.session = session;
39async function defaultGetSessionKey(ctx) {
40 var _a, _b;
41 const fromId = (_a = ctx.from) === null || _a === void 0 ? void 0 : _a.id;
42 const chatId = (_b = ctx.chat) === null || _b === void 0 ? void 0 : _b.id;
43 if (fromId == null || chatId == null) {
44 return undefined;
45 }
46 return `${fromId}:${chatId}`;
47}
48/** @deprecated https://github.com/telegraf/telegraf/issues/1372#issuecomment-782668499 */
49class MemorySessionStore {
50 constructor(ttl = Infinity) {
51 this.ttl = ttl;
52 this.store = new Map();
53 }
54 get(name) {
55 const entry = this.store.get(name);
56 if (entry == null) {
57 return undefined;
58 }
59 else if (entry.expires < Date.now()) {
60 this.delete(name);
61 return undefined;
62 }
63 return entry.session;
64 }
65 set(name, value) {
66 const now = Date.now();
67 this.store.set(name, { session: value, expires: now + this.ttl });
68 }
69 delete(name) {
70 this.store.delete(name);
71 }
72}
73exports.MemorySessionStore = MemorySessionStore;
74function isSessionContext(ctx) {
75 return 'session' in ctx;
76}
77exports.isSessionContext = isSessionContext;