UNPKG

ddnet

Version:

A typescript npm package for interacting with data from ddnet.org

93 lines 2.06 kB
import Keyv from 'keyv'; import KeyvSqlite from '@keyv/sqlite'; /** * A simple cache manager. * * @typeParam T The type of the cached objects. */ export class CacheManager { /** * Data store. */ store; /** * "Time-To-Live" - How much time (in milliseconds) before a cached object becomes stale, and thus removed automatically. * * Changing this value does not affect old objects. * * @default 7200000 // 2 hours */ ttl; /** * Default TTL. */ static defaultTTL = 4 * 60 * 60 * 1000; // 4h /** * Construct a new {@link CacheManager} instance. */ constructor( /** * The namespace to use for this cache. */ namespace, /** * The TTL (Time-To-Live) for objects in cache. * * @default 7200000 // 2 hours */ ttl) { this.store = new Keyv({ namespace, store: new KeyvSqlite({ uri: 'sqlite://ddnet_cache.sqlite' }) }); this.ttl = ttl ?? CacheManager.defaultTTL; } /** * Sets a key to a value in the cache. */ async set( /** * The key to set. */ key, /** * The value to set. */ value) { await this.store.set(key, value, this.ttl); } /** * Gets the value of the given key from the cache. */ async get( /** * The key to get. */ key) { return await this.store.get(key); } /** * Checks if the cache has a value for the given key. */ async has( /** * The key to check. */ key) { return await this.store.has(key); } /** * Sets the {@link CacheManager.ttl}. */ setTTL( /** * If provided, sets the {@link CacheManager.ttl} to this value, otherwise uses the default value. */ ttlMS) { this.ttl = ttlMS ?? CacheManager.defaultTTL; } /** * Clears the {@link CacheManager.store}. */ async clearCache() { return await this.store.clear(); } } //# sourceMappingURL=CacheManager.js.map