UNPKG

lemon-bot

Version:
76 lines 3.62 kB
"use strict"; 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 }); const utils_1 = require("@xhmm/utils"); const IORedis = require("ioredis"); const debugMod = require("debug"); class Session { constructor(...options) { this.redis = new IORedis(options); } static genSessionKey(params) { const clone = JSON.parse(JSON.stringify(params)); if (typeof clone.fromUser === 'object') { if (clone.fromUser.flag) delete clone.fromUser.flag; } const key = Object.values(clone).join('-'); return key; } getSession(params) { return __awaiter(this, void 0, void 0, function* () { const key = Session.genSessionKey(params); const data = yield this.redis.hgetall(key); if (Object.keys(data).length !== 0) { Object.keys(data).map(key => { try { data[key] = JSON.parse(data[key] + ''); } catch (e) { } }); Session.debug(`获取到key为${key}的session记录`); return data; } return null; }); } setSession(params, data, sessionName, expireSeconds = 300) { return __awaiter(this, void 0, void 0, function* () { const key = Session.genSessionKey(params); sessionName = sessionName.toString(); utils_1.assertType(sessionName, 'string'); if (!sessionName.startsWith('session')) sessionName = 'session' + sessionName; const storedData = Object.assign(Object.assign({}, params), { className: data.className, historyMessage: data.historyMessage, sessionName }); yield this.redis.hmset(key, ...Object.entries(storedData).map(([key, val]) => [key, typeof val === 'undefined' ? '' : JSON.stringify(val)])); yield this.redis.expire(key, expireSeconds); Session.debug(`Key is ${key}: 函数名为${sessionName}的session函数已建立,时长${expireSeconds}秒`); }); } updateSession(params, hashKey, val) { return __awaiter(this, void 0, void 0, function* () { const key = Session.genSessionKey(params); yield this.redis.hset(key, hashKey, JSON.stringify(val)); Session.debug(`Key is ${key}: 该session的${hashKey}字段已被更新`); }); } removeSession(params) { return __awaiter(this, void 0, void 0, function* () { const key = Session.genSessionKey(params); yield this.redis.del(key); Session.debug(`Key is ${key}: 该session会话已被清除`); }); } } exports.Session = Session; Session.debug = debugMod(`lemon-bot[Session]`); //# sourceMappingURL=Session.js.map