@botol/tg-session
Version:
## Example ```typescript import { BotolTg } from '@botol/tg-bot'; import { BotolSession } from '@botol/tg-session';
67 lines (66 loc) • 2.93 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BotolSession = exports.defaultGetKey = exports.MemorySession = void 0;
class MemorySession {
constructor() {
this.store = new Map();
}
get(key) {
var _a;
return (_a = this.store.get(key)) === null || _a === void 0 ? void 0 : _a.session;
}
set(key, val) {
this.store.set(key, { session: val });
}
delete(key) {
this.store.delete(key);
}
}
exports.MemorySession = MemorySession;
function defaultGetKey(ctx) {
var _a, _b;
let chatId = (_a = ctx.chat) === null || _a === void 0 ? void 0 : _a.id;
let fromId = (_b = ctx.from) === null || _b === void 0 ? void 0 : _b.id;
if (chatId == null || fromId == null) {
return void 0;
}
return `${fromId}:${chatId}`;
}
exports.defaultGetKey = defaultGetKey;
function BotolSession(options) {
var _a, _b, _c, _d;
const getKey = (_a = options === null || options === void 0 ? void 0 : options.getKey) !== null && _a !== void 0 ? _a : defaultGetKey;
const store = (_b = options === null || options === void 0 ? void 0 : options.store) !== null && _b !== void 0 ? _b : new MemorySession();
const init = (_c = options === null || options === void 0 ? void 0 : options.init) !== null && _c !== void 0 ? _c : (() => ({}));
const update = (_d = options === null || options === void 0 ? void 0 : options.update) !== null && _d !== void 0 ? _d : ((ctx, key) => {
if (key != null) {
store.set(key, ctx.session);
}
});
return (ctx, next) => __awaiter(this, void 0, void 0, function* () {
const key = yield Promise.resolve(getKey(ctx));
if (key == null) {
ctx.session = yield Promise.resolve(init(ctx, key));
return next();
}
let session = yield Promise.resolve(store.get(key));
if (session == null) {
ctx.session = yield Promise.resolve(init(ctx, key));
}
else {
ctx.session = session;
}
yield next();
yield Promise.resolve(update(ctx, key));
});
}
exports.BotolSession = BotolSession;