UNPKG

create-snippet

Version:
59 lines (58 loc) 2.19 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ModuleCache = void 0; const chalk_1 = __importDefault(require("chalk")); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const enums_1 = require("../../enums"); class ModuleCache { cacheDir; constructor() { this.cacheDir = path_1.default.join(__dirname, '..', '..', '__cache__'); if (!fs_1.default.existsSync(this.cacheDir)) { fs_1.default.mkdirSync(this.cacheDir); } } get(key) { const filePath = this.getFilePath(key); if (fs_1.default.existsSync(filePath)) { const content = fs_1.default.readFileSync(filePath, 'utf-8'); const { data, expiration } = JSON.parse(content); // проверяем, не истекло ли время жизни кэша if (expiration === null || Date.now() < expiration) { return data; } this.delete(key); } return null; } set(key, value, expiration = 0) { const filePath = this.getFilePath(key); const content = JSON.stringify({ data: value, expiration: Date.now() + expiration, }); fs_1.default.writeFileSync(filePath, content, 'utf-8'); } delete(key) { const filePath = this.getFilePath(key); if (fs_1.default.existsSync(filePath)) { fs_1.default.unlinkSync(filePath); } } getFilePath(key) { const fileName = `${key}.json`; return path_1.default.join(this.cacheDir, fileName); } clear() { fs_1.default.readdirSync(this.cacheDir).forEach((file) => { fs_1.default.unlinkSync(path_1.default.join(this.cacheDir, file)); }); // eslint-disable-next-line no-console console.log(`${chalk_1.default.green(enums_1.enumSymbol.check)} ${chalk_1.default.gray(`Cache cleared successfully!`)}`); } } exports.ModuleCache = ModuleCache;