UNPKG

zents

Version:

ZenTS is a Node.js & TypeScript MVC-Framework for building rich web applications, released as free and open-source software under the MIT License. It is designed for building web applications with modern tools and design patterns.

96 lines 3.4 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileSessionStoreAdapter = void 0; const dayjs_1 = __importDefault(require("dayjs")); const FS_1 = require("../../filesystem/FS"); const path_1 = require("path"); const logger_1 = require("../../log/logger"); const fs_1 = require("fs"); class FileSessionStoreAdapter { constructor(_databaseContainer, providerOptions) { this.folder = providerOptions.fileStoreFolder; this.prefix = providerOptions.storePrefix; this.expire = providerOptions.expireInMS; } async create(sessionId) { const filePath = this.getFilePath(sessionId); if (await FS_1.fs.exists(filePath)) { const content = await FS_1.fs.readJson(filePath); const expiredAt = dayjs_1.default(content.expiredAt); const now = dayjs_1.default(); if (expiredAt.isAfter(now)) { return; } } const data = { sessionId, data: {}, createdAt: dayjs_1.default().toString(), expiredAt: this.expire > 0 ? dayjs_1.default().add(this.expire, 'ms').toString() : dayjs_1.default().add(7, 'day').toString(), }; await FS_1.fs.writeJson(filePath, data); } async load(sessionId) { const filePath = this.getFilePath(sessionId); const defaultData = {}; if (!(await FS_1.fs.exists(filePath))) { return defaultData; } const content = await FS_1.fs.readJson(filePath); const expiredAt = dayjs_1.default(content.expiredAt); const now = dayjs_1.default(); if (expiredAt.isAfter(now)) { return defaultData; } return content.data; } async persist(sessionId, data) { const filePath = this.getFilePath(sessionId); if (!(await FS_1.fs.exists(filePath))) { return; } const content = await FS_1.fs.readJson(filePath); const expiredAt = dayjs_1.default(content.expiredAt); const now = dayjs_1.default(); if (expiredAt.isAfter(now)) { return; } content.data = data; await FS_1.fs.writeJson(filePath, data); } async remove(sessionId) { const filePath = this.getFilePath(sessionId); if (!(await FS_1.fs.exists(filePath))) { return; } try { await fs_1.promises.unlink(filePath); } catch (e) { logger_1.log.error(e); } } async has(sessionId) { const filePath = this.getFilePath(sessionId); if (!(await FS_1.fs.exists(filePath))) { return false; } const content = await FS_1.fs.readJson(filePath); const expiredAt = dayjs_1.default(content.expiredAt); const now = dayjs_1.default(); if (expiredAt.isAfter(now)) { return false; } return true; } getFilePath(sessionId) { return path_1.join(this.folder, FS_1.fs.sanitizeFilename(`${this.prefix}${sessionId}.json`)); } } exports.FileSessionStoreAdapter = FileSessionStoreAdapter; //# sourceMappingURL=FileSessionStoreAdapter.js.map