UNPKG

tg-bot-builder

Version:

Modular NestJS builder for multi-step Telegram bots with Prisma persistence and pluggable session storage.

71 lines 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createSessionManager = exports.SessionManager = void 0; class SessionManager { constructor(options = {}) { this.sessionCache = new Map(); this.sessionStorage = options.sessionStorage ?? this.createDefaultSessionStorage(); } async getSession(chatId) { const key = chatId.toString(); const cached = this.sessionCache.get(key); if (cached) { return cached; } const stored = await this.sessionStorage.get(chatId); const session = this.normalizeSessionState(stored) ?? { pageId: undefined, data: {}, }; this.sessionCache.set(key, session); return session; } async saveSession(chatId, session) { const key = chatId.toString(); this.sessionCache.set(key, session); await this.sessionStorage.set(chatId, session); } normalizeSessionState(stored) { if (!stored) { return undefined; } if (this.isChatSessionState(stored)) { stored.data = stored.data ?? {}; return stored; } if (this.isSessionState(stored)) { return { pageId: undefined, data: stored, }; } return undefined; } isChatSessionState(value) { return (typeof value === 'object' && value !== null && 'data' in value && !Array.isArray(value.data)); } isSessionState(value) { return (typeof value === 'object' && value !== null && !Array.isArray(value)); } createDefaultSessionStorage() { const store = new Map(); return { get: (chatId) => store.get(chatId.toString()), set: (chatId, state) => { store.set(chatId.toString(), state); }, delete: (chatId) => { store.delete(chatId.toString()); }, }; } } exports.SessionManager = SessionManager; const createSessionManager = (options = {}) => new SessionManager(options); exports.createSessionManager = createSessionManager; //# sourceMappingURL=session-manager.js.map