smart-cache-gc
Version:
A GC-aware cache using WeakRef and FinalizationRegistry
91 lines (89 loc) • 2.5 kB
TypeScript
interface NotificationOptions<K, T> {
key: K;
value: T;
unregisterToken: object;
cleanup?: (heldValue: {
key: K;
value: T;
}) => void;
}
interface SetOptions {
ttl?: number;
}
interface SetOptions {
ttl?: number;
}
declare class SmartCache<K, T> {
#private;
constructor(options?: {
defaultTtl?: number;
maxSize?: number;
});
/**
* Gets a value from the cache by key
* @param key - The key to look up
* @returns The cached value or null if not found/garbage collected
*/
get(key: K): T | undefined;
/**
* Sets a value in the cache with automatic cleanup on GC
* @param key - The key to store under
* @param value - The value to store (must be object or symbol)
*/
set(key: K, value: T, options?: SetOptions): void;
/**
* Registers for GC notification without storing in cache
* @param options - Notification options
*/
getNotificationOnGC(options: NotificationOptions<K, T>): void;
/**
* Manually removes an entry from the cache
* @param key - The key to remove
* @returns true if the key existed and was removed
*/
delete(key: K): boolean;
/**
* Checks if a key exists in the cache and its value is still alive and not expired
* @param key - The key to check
* @returns true if key exists and value is still alive and non-expired
*/
has(key: K): boolean;
/**
* Gets the number of entries in the cache (only alive and non-expired ones)
* @returns The number of alive and non-expired entries
*/
get size(): number;
/**
* Clears all entries from the cache
*/
clear(): void;
/**
* Gets all alive keys in the cache
* @returns Array of keys with alive values
*/
keys(): K[];
/**
* Gets TTL information for a key
* @param key - The key to check
* @returns TTL info or null if key doesn't exist
*/
getTtl(key: K): {
ttl: number;
expiresAt: number;
} | null;
/**
* Updates the TTL for an existing key
* @param key - The key to update
* @param ttl - New TTL in milliseconds
* @returns true if key existed and TTL was updated
*/
updateTtl(key: K, ttl: number): boolean;
getStats(): {
size: number;
stringItems: number;
objectItems: number;
symbolItems: number;
lruNodes: number;
};
}
export { SmartCache };