### Simple LRU Cache Setup Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/usage-patterns.md Initialize a basic LRUCache with a maximum capacity. Demonstrates setting, getting, and deleting items. ```typescript import { LRUCache } from 'lru-cache' const cache = new LRUCache({ max: 500 // Store at most 500 items }) cache.set('key', 'value') console.log(cache.get('key')) // 'value' cache.delete('key') console.log(cache.get('key')) // undefined ``` -------------------------------- ### Basic LRU Cache Setup Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Demonstrates the fundamental setup of an LRU cache with a maximum number of items. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, }); ``` -------------------------------- ### Install node-lru-cache Source: https://github.com/isaacs/node-lru-cache/blob/main/README.md Install the lru-cache package using npm. ```bash npm install lru-cache --save ``` -------------------------------- ### TTL-based Expiration Cache Setup Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Illustrates how to configure a cache with time-to-live (TTL) based expiration for its entries. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, ttl: 1000 * 60 * 5, // 5 minutes }); ``` -------------------------------- ### Size-limited Cache Setup (Bytes) Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Shows how to create a cache that is limited by the total size of its entries in bytes, using a sizeCalculation function. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ maxSize: 1024 * 1024, // 1MB // calculate the size of the entry sizeCalculation: (value, key) => { return Buffer.byteLength(value); }, }); ``` -------------------------------- ### GetOptions Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md Options for the `get()` method. ```APIDOC ## GetOptions ### Description Options for the `get()` method. ### Properties - `allowStale` (boolean) - Optional - Return stale value if available. Defaults to constructor default. - `updateAgeOnGet` (boolean) - Optional - Reset item's TTL. Defaults to constructor default. - `noDeleteOnStaleGet` (boolean) - Optional - Don't delete stale items. Defaults to constructor default. - `status` (Status) - Optional - Status object to populate. ``` -------------------------------- ### Fetch Simulation Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Provides an example of simulating fetch requests for testing purposes, allowing control over responses and errors. ```javascript import LRU from 'lru-cache'; // Mock the global fetch function global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ message: 'success' }), }) ); const cache = new LRU({ max: 100, fetchMethod: async (key) => { const response = await fetch(`https://example.com/${key}`); return await response.json(); }, }); cache.fetch('data').then(data => console.log(data)); // { message: 'success' } ``` -------------------------------- ### File Descriptor Cleanup on Eviction Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Provides an example of managing resource cleanup, specifically file descriptors, when cache entries are evicted. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, disposeAfter: 1000 * 60 * 5, // 5 minutes dispose: (value, key) => { // close the file descriptor value.close(); }, }); ``` -------------------------------- ### Cache Serialization (Dump/Load) Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Provides examples for serializing the cache's current state to a JSON string and loading it back. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, }); cache.set('a', 1); cache.set('b', 2); const json = cache.dump(); // {'a':1,'b':2} const newCache = new LRU({ max: 100, }); newCache.load(JSON.parse(json)); console.log(newCache.get('a')); // 1 ``` -------------------------------- ### get(k, getOptions?) Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Retrieve a value from the cache and mark it as recently used. Options can be provided to control stale data handling and TTL updates. ```APIDOC ## get(k, getOptions?) ### Description Retrieve a value from the cache and mark it as recently used. Options can be provided to control stale data handling and TTL updates. ### Method Signature ```typescript get(k: K, getOptions?: LRUCache.GetOptions): V | undefined ``` ### Parameters #### Path Parameters - **k** (K) - Required - The key to retrieve #### Query Parameters - **getOptions** (LRUCache.GetOptions) - Optional - Options for this get operation - **allowStale?** (boolean) - Return stale value if available - **updateAgeOnGet?** (boolean) - Reset item's TTL - **noDeleteOnStaleGet?** (boolean) - Don't delete stale items - **status?** (Status) - Status object to populate with operation details ### Returns - (V | undefined) - The cached value, or `undefined` if not found or stale ### Example ```typescript const cache = new LRUCache({ max: 10, ttl: 1000 }) cache.set('mykey', 'myvalue') console.log(cache.get('mykey')) // 'myvalue' console.log(cache.get('notfound')) // undefined ``` ``` -------------------------------- ### Basic LRUCache Usage Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/README.md Demonstrates basic operations of LRUCache including setting, getting, checking presence, asynchronous fetching, synchronous memoization, and clearing the cache. Configure with max items, max size, size calculation, TTL, and stale item behavior. ```typescript import { LRUCache } from 'lru-cache' const cache = new LRUCache({ max: 500, maxSize: 50000, sizeCalculation: (value) => JSON.stringify(value).length, ttl: 1000 * 60 * 5, allowStale: true }) cache.set('key', { data: 'value' }) const value = cache.get('key') if (cache.has('key')) { console.log('Found') } const data = await cache.fetch('api-key', { signal: fetchAbortSignal, forceRefresh: false }) const computed = cache.memo('computation', { forceRefresh: false }) cache.clear() ``` -------------------------------- ### LRUCache Methods Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/CONTENTS.txt Reference for all available methods on the LRUCache class, including their signatures, parameters, return types, and usage examples. ```APIDOC ## LRUCache Methods Reference This section details all the methods available on the LRUCache class. ### `get(key: K, options?: GetOptions): V | undefined` #### Description Retrieves the value associated with the given key from the cache. #### Parameters - **key** (K) - Required - The key of the item to retrieve. - **options** (GetOptions) - Optional - Options for the get operation. #### Returns The value associated with the key, or undefined if the key is not found. ### `set(key: K, value: V, options?: SetOptions): this` #### Description Adds or updates an item in the cache. #### Parameters - **key** (K) - Required - The key of the item to set. - **value** (V) - Required - The value of the item to set. - **options** (SetOptions) - Optional - Options for the set operation. #### Returns The LRUCache instance for chaining. ### `has(key: K, options?: HasOptions): boolean` #### Description Checks if a key exists in the cache. #### Parameters - **key** (K) - Required - The key to check. - **options** (HasOptions) - Optional - Options for the has operation. #### Returns True if the key exists, false otherwise. ### `peek(key: K, options?: PeekOptions): V | undefined` #### Description Retrieves the value associated with the key without updating its position in the LRU order. #### Parameters - **key** (K) - Required - The key of the item to peek. - **options** (PeekOptions) - Optional - Options for the peek operation. #### Returns The value associated with the key, or undefined if the key is not found. ### `delete(key: K): boolean` #### Description Removes an item from the cache. #### Parameters - **key** (K) - Required - The key of the item to delete. #### Returns True if the item was deleted, false otherwise. ### `clear(): void` #### Description Removes all items from the cache. ### `pop(): V | undefined` #### Description Removes and returns the least recently used item from the cache. #### Returns The least recently used item's value, or undefined if the cache is empty. ### `fetch(key: K, fetcher: Fetcher, options?: FetchOptions): Promise` #### Description Retrieves an item from the cache, or fetches it using the provided fetcher if it's not present. #### Parameters - **key** (K) - Required - The key of the item to fetch. - **fetcher** (Fetcher) - Required - The function to call if the item is not in the cache. - **options** (FetchOptions) - Optional - Options for the fetch operation. #### Returns A promise that resolves with the fetched value, or undefined. ### `forceFetch(key: K, fetcher: Fetcher, options?: FetchOptions): Promise` #### Description Forces a fetch of an item, bypassing the cache if it exists. #### Parameters - **key** (K) - Required - The key of the item to fetch. - **fetcher** (Fetcher) - Required - The function to call to fetch the item. - **options** (FetchOptions) - Optional - Options for the fetch operation. #### Returns A promise that resolves with the fetched value. ### `memo(key: K, fn: () => V, options?: MemoOptions): V` #### Description Memoizes a function call, returning the cached result if available. #### Parameters - **key** (K) - Required - The key to associate with the memoized result. - **fn** (() => V) - Required - The function to memoize. - **options** (MemoOptions) - Optional - Options for the memoization. #### Returns The memoized result. ### `entries(): IterableIterator<[K, V]>` #### Description Returns an iterator for all cache entries (key-value pairs). ### `rentries(): IterableIterator<[K, V]>` #### Description Returns a reverse iterator for all cache entries (key-value pairs). ### `keys(): IterableIterator` #### Description Returns an iterator for all cache keys. ### `rkeys(): IterableIterator` #### Description Returns a reverse iterator for all cache keys. ### `values(): IterableIterator` #### Description Returns an iterator for all cache values. ### `rvalues(): IterableIterator` #### Description Returns a reverse iterator for all cache values. ### `find(predicate: (value: V, key: K, cache: this) => boolean, options?: FindOptions): K | undefined` #### Description Finds the first key in the cache that satisfies the provided predicate function. #### Parameters - **predicate** ((value: V, key: K, cache: this) => boolean) - Required - The function to test each key-value pair. - **options** (FindOptions) - Optional - Options for the find operation. #### Returns The key of the first matching entry, or undefined if no entry satisfies the predicate. ### `forEach(callbackfn: (value: V, key: K, cache: this) => void, options?: ForEachOptions): void` #### Description Executes a provided function once for each cache entry. #### Parameters - **callbackfn** ((value: V, key: K, cache: this) => void) - Required - Function to execute for each entry. - **options** (ForEachOptions) - Optional - Options for the forEach operation. ### `rforEach(callbackfn: (value: V, key: K, cache: this) => void, options?: ForEachOptions): void` #### Description Executes a provided function once for each cache entry in reverse order. #### Parameters - **callbackfn** ((value: V, key: K, cache: this) => void) - Required - Function to execute for each entry. - **options** (ForEachOptions) - Optional - Options for the rforEach operation. ### `purgeStale(options?: PurgeStaleOptions): Count` #### Description Removes all stale entries from the cache. #### Parameters - **options** (PurgeStaleOptions) - Optional - Options for purging stale entries. #### Returns The number of entries purged. ### `info(): CacheInfo` #### Description Returns information about the cache's current state. #### Returns An object containing cache information. ### `getRemainingTTL(key: K): Milliseconds` #### Description Gets the remaining Time To Live for a given key. #### Parameters - **key** (K) - Required - The key to check. #### Returns The remaining TTL in milliseconds. ### `dump(): CacheDump` #### Description Returns a serializable representation of the cache's current state. #### Returns A CacheDump object. ### `load(dump: CacheDump): this` #### Description Loads the cache state from a previously dumped representation. #### Parameters - **dump** (CacheDump) - Required - The CacheDump object to load. #### Returns The LRUCache instance for chaining. ### `Symbol.iterator(): IterableIterator<[K, V]>` #### Description Provides an iterator for the cache entries, same as `entries()`. ### `[Symbol.toStringTag]: string` #### Description Returns the string tag for the object, typically 'LRUCache'. ``` -------------------------------- ### Storage Methods Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Methods for managing cache storage: set, get, peek, has, delete, clear, and pop. ```APIDOC ## Storage Methods ### Description Methods for managing cache storage. ### `set(key, value, [options])` #### Description Adds or updates an item in the cache. #### Parameters - **key** (any) - The key of the item. - **value** (any) - The value of the item. - **options** (object) - Optional settings for the set operation. #### Returns (Details on return value would be listed here if available in the source.) ### `get(key, [options])` #### Description Retrieves an item from the cache. #### Parameters - **key** (any) - The key of the item to retrieve. - **options** (object) - Optional settings for the get operation. #### Returns (Details on return value and stale values would be listed here if available in the source.) ### `peek(key, [options])` #### Description Retrieves an item from the cache without updating its position or TTL. #### Parameters - **key** (any) - The key of the item to peek. - **options** (object) - Optional settings for the peek operation. #### Returns (Details on return value would be listed here if available in the source.) ### `has(key, [options])` #### Description Checks if an item exists in the cache. #### Parameters - **key** (any) - The key to check for. - **options** (object) - Optional settings for the has operation. #### Returns (Details on return value would be listed here if available in the source.) ### `delete(key, [options])` #### Description Removes an item from the cache. #### Parameters - **key** (any) - The key of the item to delete. - **options** (object) - Optional settings for the delete operation. #### Returns (Details on return value would be listed here if available in the source.) ### `clear([options])` #### Description Removes all items from the cache. #### Parameters - **options** (object) - Optional settings for the clear operation. #### Returns (Details on return value would be listed here if available in the source.) ### `pop([options])` #### Description Removes and returns the least recently used item from the cache. #### Parameters - **options** (object) - Optional settings for the pop operation. #### Returns (Details on return value would be listed here if available in the source.) ``` -------------------------------- ### info Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Get extended information about a cache entry. ```APIDOC ## info ### Description Get extended information about a cache entry. ### Method `info(key: K): LRUCache.Entry | undefined` ### Parameters #### Parameters - **key** (K) - Required - The key to get info for ### Returns An entry object with `{ value, ttl?, size?, start? }`, or `undefined` if not found ### Note Unlike `dump()`, the `start` value is the current timestamp, and `ttl` is the remaining time to live (negative if expired). ### Example ```typescript const cache = new LRUCache({ max: 10, ttl: 5000, maxSize: 100, sizeCalculation: (v) => v.length }) cache.set('key', 'value') const info = cache.info('key') console.log(info) // { value: 'value', ttl: 4999, size: 5, start: 1234567890 } ``` ``` -------------------------------- ### Cache Observability with Status Object Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/README.md Demonstrates how to use a status object to observe cache operations. Passing a status object to 'get' populates it with details about the operation, such as hit/miss status and remaining TTL. ```typescript const status = {} cache.get('key', { status }) console.log(status) // { op: 'get', key: 'key', get: 'hit|miss|stale|fetching', ttl, remainingTTL, ... } ``` -------------------------------- ### Stale-While-Revalidate Cache Example Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/README.md Demonstrates a stale-while-revalidate cache strategy. The fetchMethod asynchronously fetches data, returning fresh data if available and valid, stale data on error, or undefined if no cached data exists. ```typescript const cache = new LRUCache({ max: 1000, ttl: 60000, // 1 minute allowStaleOnFetchRejection: true, fetchMethod: async (key) => { const response = await fetch(`/api/${key}`) return response.ok ? await response.json() : undefined } }) // Returns fresh if cached and valid, stale on error, undefined if no cache const data = await cache.fetch('resource') ``` -------------------------------- ### LRUCache GetOptions Interface Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md Options for the get() method. Use these to control behavior like returning stale values, updating item age on retrieval, or preventing deletion of stale items. The status object can be provided to receive detailed operation feedback. ```typescript interface LRUCache.GetOptions extends Pick< OptionsBase, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' > { status?: Status } ``` -------------------------------- ### Get Extended Cache Entry Info Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `info()` to retrieve detailed information about a specific cache entry, including its value, TTL, size, and start timestamp. Returns `undefined` if the key is not found. ```typescript info(key: K): LRUCache.Entry | undefined ``` ```typescript const cache = new LRUCache({ max: 10, ttl: 5000, maxSize: 100, sizeCalculation: (v) => v.length }) cache.set('key', 'value') const info = cache.info('key') console.log(info) // { value: 'value', ttl: 4999, size: 5, start: 1234567890 } ``` -------------------------------- ### Prevent Deletion of Stale Items on Get Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/configuration.md Use `noDeleteOnStaleGet: true` to prevent stale items from being removed from the cache when accessed via `get()`. This is useful for stale-while-revalidate patterns. ```typescript const cache = new LRUCache({ ttl: 1000, noDeleteOnStaleGet: true }) cache.set('key', 'value') // After 1000ms... cache.get('key') // undefined (item not deleted) console.log(cache.has('key')) // false (still stale) console.log(cache.peek('key', { allowStale: true })) // 'value' ``` -------------------------------- ### Constructor Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Details on the constructor, including parameters, validation, and potential exceptions. ```APIDOC ## Constructor ### Description Provides details on the constructor, including parameters, validation, and potential exceptions. ### Parameters (Details on parameters, validation, and throws would be listed here if available in the source.) ### Throws (Details on thrown errors would be listed here if available in the source.) ``` -------------------------------- ### Enable TTL Reset on Get in LRUCache Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/configuration.md Set `updateAgeOnGet: true` to reset an item's TTL to the full duration when it is retrieved using `get()`. This prevents expiration of frequently accessed items. This option has no effect if `ttl` is not set. ```typescript const cache = new LRUCache({ ttl: 1000, updateAgeOnGet: true }) cache.set('key', 'value') cache.get('key') // TTL resets to full 1000ms ``` -------------------------------- ### Safe Reinsertion with disposeAfter Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Demonstrates how to safely reinsert items into the cache after a delay, utilizing the disposeAfter option. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, disposeAfter: 1000 * 60 * 5, // 5 minutes dispose: (value, key) => { // reinsert after a delay setTimeout(() => { cache.set(key, value); }, 1000); }, }); ``` -------------------------------- ### Memoization with Context Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Shows how to use memoization with a context object, allowing for dynamic behavior based on context during computation. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, memoMethod: (key, context) => { // Use context to influence computation return key * context.multiplier; }, }); console.log(cache.memo(5, { multiplier: 2 })); // Computes and caches console.log(cache.memo(5, { multiplier: 3 })); // Computes and caches again (different context) ``` -------------------------------- ### LRUCache Status Interface Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md The Status interface provides a detailed breakdown of cache operations. It includes fields for operation type, key, value, and specific details related to set, get, fetch, TTL, and size operations. Populate this object to get detailed feedback on cache interactions. ```typescript interface LRUCache.Status { op?: 'get' | 'set' | 'memo' | 'fetch' | 'delete' | 'has' | 'peek' set?: 'add' | 'update' | 'replace' | 'miss' | 'deleted' delete?: LRUCache.DisposeReason peek?: 'hit' | 'miss' | 'stale' memo?: 'hit' | 'miss' context?: unknown ttl?: Milliseconds start?: Milliseconds now?: Milliseconds remainingTTL?: Milliseconds entrySize?: Size totalCalculatedSize?: Size maxEntrySizeExceeded?: true key?: K value?: V oldValue?: V has?: 'hit' | 'stale' | 'miss' fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh' forceRefresh?: boolean fetchDispatched?: true fetchUpdated?: true fetchError?: Error fetchAborted?: true fetchAbortIgnored?: true fetchResolved?: true fetchRejected?: true get?: 'stale' | 'hit' | 'miss' | 'fetching' | 'stale-fetching' returnedStale?: true trace?: boolean cache?: LRUCache } ``` -------------------------------- ### Initialize LRUCache with Options Source: https://github.com/isaacs/node-lru-cache/blob/main/README.md Initialize an LRUCache instance with various configuration options. At least one of 'max', 'ttl', or 'maxSize' is required to prevent unbounded storage. Options like 'maxSize', 'sizeCalculation', 'dispose', 'onInsert', 'ttl', 'allowStale', 'updateAgeOnGet', 'updateAgeOnHas', and 'fetchMethod' can be configured. ```javascript // hybrid module, either works import { LRUCache } from 'lru-cache' // or: const { LRUCache } = require('lru-cache') // or in minified form for web browsers: import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs' // At least one of 'max', 'ttl', or 'maxSize' is required, to prevent // unsafe unbounded storage. // // In most cases, it's best to specify a max for performance, so all // the required memory allocation is done up-front. // // All the other options are optional, see the sections below for // documentation on what each one does. Most of them can be // overridden for specific items in get()/set() const options = { max: 500, // for use with tracking overall storage size maxSize: 5000, sizeCalculation: (value, key) => { return 1 }, // for use when you need to clean up something when objects // are evicted from the cache dispose: (value, key, reason) => { freeFromMemoryOrWhatever(value) }, // for use when you need to know that an item is being inserted // note that this does NOT allow you to prevent the insertion, // it just allows you to know about it. onInsert: (value, key, reason) => { logInsertionOrWhatever(key, value) }, // how long to live in ms ttl: 1000 * 60 * 5, // return stale items before removing from cache? allowStale: false, updateAgeOnGet: false, updateAgeOnHas: false, // async method to use for cache.fetch(), for // stale-while-revalidate type of behavior fetchMethod: async (key, staleValue, { options, signal, context }) => {} } const cache = new LRUCache(options) cache.set('key', 'value') cache.get('key') // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.clear() // empty the cache ``` -------------------------------- ### UnboundedCacheWarning Example Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/errors.md Illustrates the condition that triggers an UnboundedCacheWarning: configuring a cache with only a TTL limit and no ttlAutopurge, max, or maxSize. ```typescript const cache = new LRUCache({ ttl: 5000 // No max, maxSize, or ttlAutopurge! }) // Warning: "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption." ``` -------------------------------- ### PeekOptions Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md Options for the `peek()` method. ```APIDOC ## PeekOptions ### Description Options for the `peek()` method. ### Properties - `allowStale` (boolean) - Optional - Return stale value if available. Defaults to constructor default. - `status` (Status) - Optional - Status object to populate. ``` -------------------------------- ### Observability with Status Objects Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Illustrates how to use status objects for monitoring cache performance and health. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, }); const status = cache.getStats(); console.log(status.hits); console.log(status.misses); ``` -------------------------------- ### Basic Async Fetch with Fallback Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Illustrates a basic pattern for fetching data asynchronously, including a fallback mechanism if the primary fetch fails. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, fetchMethod: async (key, staleValue, { signal }) => { try { const response = await fetch(`https://example.com/${key}`, { signal }); if (!response.ok) { return staleValue; } return await response.json(); } catch (error) { return staleValue; } }, }); ``` -------------------------------- ### Basic Sync Computation Caching Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Demonstrates caching the results of synchronous computations using the memoMethod. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, memoMethod: (key) => { // Simulate a heavy computation return key * 2; }, }); console.log(cache.memo(5)); // Computes and caches console.log(cache.memo(5)); // Returns cached value ``` -------------------------------- ### Iteration and Search Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Shows how to iterate over cache entries and search for specific keys. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, }); cache.set('a', 1); cache.set('b', 2); for (const [key, value] of cache.entries()) { console.log(key, value); } console.log(cache.has('a')); // true console.log(cache.has('c')); // false ``` -------------------------------- ### Iterate Values in Order Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `values()` to get a generator yielding values in order from most recently used to least recently used. ```typescript *values(): Generator ``` -------------------------------- ### Iterate Keys in Order Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `keys()` to get a generator yielding keys in order from most recently used to least recently used. ```typescript *keys(): Generator ``` -------------------------------- ### Fetch with Context Object Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Illustrates fetching data using a context object that can be passed to the fetchMethod, useful for providing request-specific information. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, fetchMethod: async (key, staleValue, context) => { const { requestOptions } = context; const response = await fetch(`https://example.com/${key}`, requestOptions); return await response.json(); }, }); cache.fetch('data', { requestOptions: { headers: { 'Authorization': 'Bearer token' } }, }); ``` -------------------------------- ### peek(k, peekOptions?) Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Get a value without updating recency or removing stale items. Stale items are returned only if `allowStale` is true. ```APIDOC ## peek(k, peekOptions?) ### Description Get a value without updating recency or removing stale items. Stale items are returned only if `allowStale` is true. ### Method Signature ```typescript peek(k: K, peekOptions?: LRUCache.PeekOptions): V | undefined ``` ### Parameters #### Path Parameters - **k** (K) - Required - The key to peek at #### Query Parameters - **peekOptions** (LRUCache.PeekOptions) - Optional - Options for this peek operation - **allowStale?** (boolean) - Return stale value if available - **status?** (Status) - Status object to populate ### Returns - (V | undefined) - The cached value or stale value (if allowed), or `undefined` ### Example ```typescript const cache = new LRUCache({ max: 10 }) cache.set('key', 'value') const v = cache.peek('key') // Returns 'value' without marking as used ``` ``` -------------------------------- ### Memory Constraint Handling Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Illustrates strategies for handling memory constraints within the cache, such as using maxSize and sizeCalculation. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ maxSize: 1024 * 1024, // 1MB limit sizeCalculation: (value, key) => { return Buffer.byteLength(JSON.stringify(value)); }, }); ``` -------------------------------- ### Iterate Values in Reverse Order Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `rvalues()` to get a generator yielding values in reverse order (least recently used to most recently used). ```typescript *rvalues(): Generator ``` -------------------------------- ### Iterate Keys in Reverse Order Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `rkeys()` to get a generator yielding keys in reverse order (least recently used to most recently used). ```typescript *rkeys(): Generator ``` -------------------------------- ### Mock Time for TTL Testing Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Shows how to mock the system time to effectively test TTL-based expiration of cache entries. ```javascript import LRU from 'lru-cache'; // Mock Date.now() const realDateNow = Date.now; Date.now = () => 1000000000000; // Mocked time const cache = new LRU({ max: 100, ttl: 5000, // 5 seconds TTL }); cache.set('a', 1); Date.now = realDateNow; // Restore Date.now() setTimeout(() => { console.log(cache.has('a')); // Should be false after TTL expires }, 6000); ``` -------------------------------- ### set(k, v, setOptions?) Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Add or update a value in the cache. Options can specify size, TTL, and other behaviors. ```APIDOC ## set(k, v, setOptions?) ### Description Add or update a value in the cache. Options can specify size, TTL, and other behaviors. ### Method Signature ```typescript set( k: K, v: V | undefined, setOptions?: LRUCache.SetOptions ): this ``` ### Parameters #### Path Parameters - **k** (K) - Required - The key to set - **v** (V | undefined) - Required - The value to set (undefined = delete) #### Query Parameters - **setOptions** (LRUCache.SetOptions) - Optional - Options for this set operation - **size?** (Size) - Explicit size (prevents calling sizeCalculation) - **sizeCalculation?** (SizeCalculator) - Custom size calculation for this item - **ttl?** (Milliseconds) - Custom TTL for this item - **start?** (Milliseconds) - Custom TTL start time - **noDisposeOnSet?** (boolean) - Skip dispose on overwrite - **noUpdateTTL?** (boolean) - Don't update TTL on replacement - **status?** (Status) - Status object to populate ### Returns - (this) - The cache instance (for chaining) ### Throws - `TypeError` if size is invalid and size tracking is enabled - The item will not be added if its size exceeds `maxEntrySize` ### Example ```typescript const cache = new LRUCache({ max: 10, maxSize: 100, sizeCalculation: (v) => v.length }) cache.set('key1', 'value') cache.set('key2', 'another value', { ttl: 5000 }) cache.set('key3', 'sized', { size: 10 }) ``` ``` -------------------------------- ### Configure LRUCache to Allow Stale Values Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/configuration.md Set `allowStale` to true to enable `get()` and `fetch()` to return stale values before they are deleted. Defaults to false. ```typescript const cache = new LRUCache({ ttl: 1000, allowStale: true }) cache.set('key', 'value') // After 1000ms... console.log(cache.get('key')) // 'value' (stale, then deleted) console.log(cache.get('key')) // undefined (now gone) ``` -------------------------------- ### Create and Use LRUCache Instance Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Instantiate an LRUCache with specified options for size and TTL, then set and retrieve values. The cache automatically evicts the least recently used items when limits are reached. Remember to clear the cache when no longer needed. ```typescript import { LRUCache } from 'lru-cache' const cache = new LRUCache({ max: 500, maxSize: 5000, sizeCalculation: (value, key) => 1, ttl: 1000 * 60 * 5, allowStale: false, }) cache.set('key', 'value') console.log(cache.get('key')) // 'value' cache.clear() ``` -------------------------------- ### Iterate Entries in Reverse Order Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `rentries()` to get a generator yielding `[key, value]` pairs in reverse order (least recently used to most recently used). ```typescript rentries(): Generator<[K, V]> ``` -------------------------------- ### Handle Fetch Aborts with AbortSignal Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/errors.md Demonstrates how to use an AbortSignal with cache.fetch() to abandon or return stale values on abort, depending on configuration. ```typescript const cache = new LRUCache({ max: 10, allowStaleOnFetchAbort: true, fetchMethod: async (key, staleValue, { signal }) => { return await fetch(`/api/${key}`, { signal }) } }) try { const controller = new AbortController() controller.abort() const result = await cache.fetch('key', { signal: controller.signal }) // Returns stale value or undefined instead of throwing } catch (error) { // Depends on configuration } ``` -------------------------------- ### Entry Interface for Cache Data Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md Represents a single cache entry in a serialized format, used for dump() and load() operations. Includes value, ttl, size, and start time. ```typescript interface LRUCache.Entry { value: V ttl?: Milliseconds size?: Size start?: Milliseconds } ``` -------------------------------- ### Graceful Degradation on Fetch Failure Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/INDEX.md Demonstrates how to handle fetch failures gracefully, ensuring the application remains functional even if the cache cannot retrieve data. ```javascript import LRU from 'lru-cache'; const cache = new LRU({ max: 100, fetchMethod: async (key, staleValue) => { try { const response = await fetch(`https://example.com/${key}`); if (!response.ok) { throw new Error('Network response was not ok'); } return await response.json(); } catch (error) { console.error('Fetch failed:', error); return staleValue; // Return stale value on error } }, }); ``` -------------------------------- ### Get Remaining TTL for Cache Entry Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Retrieve the remaining time to live for a specific cache entry in milliseconds. Returns 0 if the key is not found, or Infinity if no TTL was set for the entry. ```typescript const cache = new LRUCache({ max: 10, ttl: 5000 }) cache.set('key', 'value') const remaining = cache.getRemainingTTL('key') console.log(remaining) // ~4999 or 5000 console.log(cache.getRemainingTTL('missing')) // 0 ``` -------------------------------- ### OptionsSizeLimit Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md Options configuration that specifies the maximum size allowed for the cache. ```APIDOC ## OptionsSizeLimit ### Description Options with `maxSize` specified (one of the three required limit types). ### Type Definition ```typescript interface LRUCache.OptionsSizeLimit extends OptionsBase { maxSize: Size } ``` ``` -------------------------------- ### Accessing Stale Values with Options Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/usage-patterns.md Access stale cache values even after they have expired using `peek()` or `get()` with the `allowStale` option. Note that `has()` will always return false for stale items. ```typescript const cache = new LRUCache({ max: 100, ttl: 1000 }) cache.set('config', { version: 1 }) // Peek without updating recency const value = cache.peek('config') // Gets current value console.log(value) // After expiry: // - peek() returns undefined unless allowStale is true // - get() with allowStale returns stale value before deleting it // - has() always returns false for stale items console.log(cache.peek('config', { allowStale: true })) console.log(cache.get('config', { allowStale: true })) console.log(cache.has('config')) ``` -------------------------------- ### Peek at value in LRU cache Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Get a value from the cache without updating its recency or triggering stale item removal. This is useful for inspecting cache contents without altering their usage status. ```typescript const cache = new LRUCache({ max: 10 }) cache.set('key', 'value') const v = cache.peek('key') // Returns 'value' without marking as used ``` -------------------------------- ### load Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Clear the cache and load items from a dump (typically from `dump()`). ```APIDOC ## load ### Description Clear the cache and load items from a dump (typically from `dump()`). ### Method `load(arr: Array<[K, LRUCache.Entry]>): void` ### Parameters #### Parameters - **arr** (`Array<[K, LRUCache.Entry]>`) - Required - Array of `[key, entry]` tuples ### Example ```typescript const cache1 = new LRUCache({ max: 10, ttl: 5000 }) cache1.set('a', 1) cache1.set('b', 2) const dump = cache1.dump() const cache2 = new LRUCache({ max: 10, ttl: 5000 }) cache2.load(dump) console.log(cache2.get('a')) // 1 console.log(cache2.get('b')) // 2 ``` ``` -------------------------------- ### LRUCache Constructor and Properties Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/CONTENTS.txt Documentation for the LRUCache constructor and its associated properties, including read-only and mutable properties. ```APIDOC ## LRUCache Constructor ### Description Initializes a new instance of the LRUCache. ### Parameters (Details on constructor parameters would be here if available in the source) ### Properties - **read-only properties**: (List of read-only properties and their descriptions) - **mutable properties**: (List of mutable properties and their descriptions) ``` -------------------------------- ### SetOptions Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md Options for the `set()` method. ```APIDOC ## SetOptions ### Description Options for the `set()` method. ### Properties - `size` (Size) - Optional - Explicit size (prevents sizeCalculation call). - `sizeCalculation` (SizeCalculator) - Optional - Custom size calculation. Defaults to constructor default. - `ttl` (Milliseconds) - Optional - Custom TTL for this item. Defaults to constructor default. - `start` (Milliseconds) - Optional - TTL start timestamp. Defaults to Date.now(). - `noDisposeOnSet` (boolean) - Optional - Skip dispose callback. Defaults to constructor default. - `noUpdateTTL` (boolean) - Optional - Don't update TTL on replacement. Defaults to constructor default. - `status` (Status) - Optional - Status object to populate. ``` -------------------------------- ### Dump Cache Contents Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Use `dump()` to get an array of `[key, entry]` tuples representing all items in the cache, including stale ones. The array is ordered from least recently used to most recently used. ```typescript dump(): Array<[K, LRUCache.Entry]> ``` ```typescript const cache = new LRUCache({ max: 10, ttl: 5000 }) cache.set('a', 1) cache.set('b', 2) const dump = cache.dump() console.log(dump) // [['a', { value: 1, ttl: 5000, start: 1234567890 }], ...] ``` -------------------------------- ### OptionsBase Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/types.md The base interface for all LRUCache constructor options, defining fundamental cache configuration parameters. ```APIDOC ## OptionsBase ### Description Base interface for all LRUCache constructor options. See the [configuration documentation](configuration.md) for detailed descriptions. ### Type Definition ```typescript interface LRUCache.OptionsBase { max?: Count ttl?: Milliseconds ttlResolution?: Milliseconds ttlAutopurge?: boolean updateAgeOnGet?: boolean updateAgeOnHas?: boolean allowStale?: boolean dispose?: Disposer onInsert?: Inserter disposeAfter?: Disposer noDisposeOnSet?: boolean noUpdateTTL?: boolean maxSize?: Size backgroundFetchSize?: number maxEntrySize?: Size sizeCalculation?: SizeCalculator fetchMethod?: Fetcher memoMethod?: Memoizer noDeleteOnFetchRejection?: boolean noDeleteOnStaleGet?: boolean allowStaleOnFetchRejection?: boolean allowStaleOnFetchAbort?: boolean ignoreFetchAbort?: boolean perf?: Perf } ``` ``` -------------------------------- ### Get value from LRU cache Source: https://github.com/isaacs/node-lru-cache/blob/main/_autodocs/api-reference.md Retrieve a value from the cache. This operation marks the item as recently used. Use this when you need to access cached data and ensure it remains in the cache if it's frequently accessed. ```typescript const cache = new LRUCache({ max: 10, ttl: 1000 }) cache.set('mykey', 'myvalue') console.log(cache.get('mykey')) // 'myvalue' console.log(cache.get('notfound')) // undefined ```