UNPKG

axiodb

Version:

A blazing-fast, lightweight, and scalable nodejs package based DBMS for modern application. Supports schemas, encryption, and advanced query capabilities.

175 lines 7.58 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 }); exports.InMemoryCache = void 0; /* eslint-disable @typescript-eslint/no-explicit-any */ /** * @description This class is responsible for caching data in memory * @class InMemoryCache * @export InMemoryCache * @version 1.0.1 * @since 23 April 2025 **/ class InMemoryCache { /** * Creates a new instance of the cache operation class * @param TTL - Time to live in seconds for cache entries. Defaults to 86400 seconds (24 hours) */ constructor(TTL = 86400) { this.tempSearchQuery = []; this.autoResetCacheInterval = 86400; // 24 hours this.threshold = 2; // 2 times this.ttl = typeof TTL === "string" ? parseInt(TTL) : TTL; this.cacheObject = new Map(); this.tempSearchQuery = []; // this.autoResetCacheInterval is already initialized to 86400 (24 hours) this.autoResetCache(); // Start the auto-reset cache process } /** * Sets a value in the cache with the specified key. * The cached item will expire after the TTL (Time To Live) duration set for the cache. * * @param key - The unique identifier for the cached item * @param value - The value to be stored in the cache * @returns A Promise that resolves when the value has been cached * * @example * ```typescript * await cache.setCache('user-123', { name: 'John', age: 30 }); * ``` */ setCache(key, value) { return __awaiter(this, void 0, void 0, function* () { // check the key is already exceed the threshold or not const KeyStatus = yield this.setTempSearchQuery(key); if (KeyStatus === true) { // check if the key is already in the cache const cacheItem = this.cacheObject.get(key); if (!cacheItem) { this.cacheObject.set(key, { value: value, registeredAt: new Date(), }); return true; } else { // check if the cache is expired or not const now = new Date(); const diff = Math.abs(now.getTime() - cacheItem.registeredAt.getTime()); if (diff > this.ttl * 1000) { // if the cache is expired, remove it from the cache this.cacheObject.delete(key); this.cacheObject.set(key, { value: value, registeredAt: new Date(), }); return true; } else { return true; } } } else { return false; } }); } setTempSearchQuery(queryString) { return __awaiter(this, void 0, void 0, function* () { // check if the query string is already in the temp search query for the threshold times const existingQuery = this.tempSearchQuery.filter((item) => item.queryString === queryString); if ((existingQuery === null || existingQuery === void 0 ? void 0 : existingQuery.length) >= this.threshold) { return true; } else { // if the query string is not in the temp search query, add it to the temp search query this.tempSearchQuery.push({ queryString: queryString, registeredAt: new Date(), }); return false; } }); } /** * Retrieves a value from the cache using the specified key * @param key - The unique identifier to lookup in the cache * @returns A Promise that resolves to the cached value if found and not expired, null otherwise */ getCache(key) { return __awaiter(this, void 0, void 0, function* () { const cacheItem = this.cacheObject.get(key); if (!cacheItem) { return false; } return cacheItem.value; }); } /** * Clears all cached data stored in memory. * Resets the cache object and temporary search query array to their initial empty states. * * @returns A Promise that resolves to true when the cache has been successfully cleared. */ clearAllCache() { return __awaiter(this, void 0, void 0, function* () { // clear all cache this.cacheObject.clear(); this.tempSearchQuery = []; return true; }); } /** * Sets up an automatic cache reset mechanism. * This method creates an interval timer that periodically checks and removes expired items from the cache. * * The method performs the following operations: * 1. Checks if the cache is empty, and returns early if it is. * 2. Iterates through all cache items and removes those that have expired based on the `autoResetCacheInterval`. * 3. Filters out expired temporary search queries based on the same interval. * * The interval for this automatic reset is determined by the `ttl` (time-to-live) property. * * @private * @returns {Promise<void>} A promise that resolves when the interval is set up. */ autoResetCache() { return __awaiter(this, void 0, void 0, function* () { setInterval(() => { // check if the cache is empty or not if (Object.keys(this.cacheObject).length === 0) { return; } // check if the cache is expired or not // if the cache is expired, remove it from the cache const now = new Date(); for (const key in this.cacheObject) { const cacheItem = this.cacheObject.get(key); if (cacheItem) { const diff = Math.abs(now.getTime() - cacheItem.registeredAt.getTime()); if (diff > this.autoResetCacheInterval * 1000) { this.cacheObject.delete(key); } } } // also remove the expired temp search queries this.tempSearchQuery = this.tempSearchQuery.filter((item) => { const diff = Math.abs(now.getTime() - item.registeredAt.getTime()); return diff < this.autoResetCacheInterval * 1000; }); }, parseInt(String(this.ttl))); }); } } exports.InMemoryCache = InMemoryCache; exports.default = new InMemoryCache(86400); // 24 hours //# sourceMappingURL=cache.operation.js.map