UNPKG

@daiso-tech/core

Version:

The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.

104 lines 3.12 kB
/* eslint-disable @typescript-eslint/require-await */ /** * @module Cache */ import { TypeCacheError, } from "../../../../cache/contracts/_module-exports.js"; /** * To utilize the `MemoryCacheAdapter`, you must create instance of it. * * IMPORT_PATH: `"@daiso-tech/core/cache/adapters"` * @group Adapters */ export class MemoryCacheAdapter { map; timeoutMap = new Map(); /** * You can provide an optional {@link Map | `Map`}, that will be used for storing the data. * @example * ```ts * import { MemoryCacheAdapter } from "@daiso-tech/core/cache/adapters"; * * const map = new Map<any, any>(); * const cacheAdapter = new MemoryCacheAdapter(map); * ``` */ constructor(map = new Map()) { this.map = map; } async get(key) { return (this.map.get(key) ?? null); } async getAndRemove(key) { const value = await this.get(key); await this.remove(key); return value; } async add(key, value, ttl) { const hasNotKey = !this.map.has(key); if (hasNotKey) { this.map.set(key, value); } if (hasNotKey && ttl !== null) { this.timeoutMap.set(key, setTimeout(() => { this.map.delete(key); this.timeoutMap.delete(key); }, ttl.toMilliseconds())); } return hasNotKey; } async put(key, value, ttl) { const hasKey = await this.remove(key); await this.add(key, value, ttl); return hasKey; } async update(key, value) { const hasKey = this.map.has(key); if (hasKey) { this.map.set(key, value); } return hasKey; } async increment(key, value) { const prevValue = this.map.get(key); const hasKey = prevValue !== undefined; if (hasKey) { if (typeof prevValue !== "number") { throw new TypeCacheError(`Unable to increment or decrement none number type key "${key}"`); } const newValue = prevValue + value; this.map.set(key, newValue); } return hasKey; } async remove(key) { clearTimeout(this.timeoutMap.get(key)); this.timeoutMap.delete(key); return this.map.delete(key); } async removeMany(keys) { let deleteCount = 0; for (const key of keys) { clearTimeout(this.timeoutMap.get(key)); this.timeoutMap.delete(key); const hasDeleted = this.map.delete(key); if (hasDeleted) { deleteCount++; } } return deleteCount > 0; } async removeAll() { this.map.clear(); this.timeoutMap.clear(); } async removeByKeyPrefix(prefix) { for (const key of this.map.keys()) { if (key.startsWith(prefix)) { clearTimeout(this.timeoutMap.get(key)); this.timeoutMap.delete(key); this.map.delete(key); } } } } //# sourceMappingURL=memory-cache-adapter.js.map