### Start Redis Service Source: https://github.com/jaredwray/cacheable/blob/main/CONTRIBUTING.md Run this command to start a Redis container for testing purposes. Ensure Docker is installed. ```bash pnpm test:services:start ``` -------------------------------- ### Install file-entry-cache Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Install the package using npm. ```bash npm install file-entry-cache ``` -------------------------------- ### Install Keyv Storage Adapters Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Commands to install various storage adapters supported by Keyv for use with cache-manager. ```bash npm install @keyv/redis npm install @keyv/memcache npm install @keyv/mongo npm install @keyv/sqlite npm install @keyv/postgres npm install @keyv/mysql npm install @keyv/etcd ``` -------------------------------- ### Install flat-cache Source: https://github.com/jaredwray/cacheable/blob/main/packages/flat-cache/README.md Install the flat-cache package using npm. ```bash npm install flat-cache ``` -------------------------------- ### Install Redis Keyv Storage Adapter Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable-request/README.md Install the official Redis Keyv storage adapter to use Redis as a cache backend. ```shell npm install @keyv/redis ``` -------------------------------- ### Install NodeCache Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Install the NodeCache package using npm. ```bash npm install @cacheable/node-cache --save ``` -------------------------------- ### Initialize CacheableNet and Make Requests Source: https://github.com/jaredwray/cacheable/blob/main/packages/net/README.md Demonstrates creating a CacheableNet instance and using its helper methods for GET, POST, and fetch requests. GET requests are cached by default. ```javascript import { CacheableNet } from '@cacheable/net'; const net = new CacheableNet(); // Simple GET request with caching (the response body is parsed into `data`) const { data, response } = await net.get('https://api.example.com/data'); console.log(response.status, data); // POST request with a JSON body (serialized automatically) const result = await net.post('https://api.example.com/users', { name: 'John Doe', email: 'john@example.com' }); console.log(result.data); // Using fetch directly returns the raw Response const fetchResponse = await net.fetch('https://api.example.com/data', { method: 'GET', headers: { Authorization: 'Bearer token' } }); console.log(await fetchResponse.json()); ``` -------------------------------- ### Install Cacheable Net Source: https://github.com/jaredwray/cacheable/blob/main/packages/net/README.md Install the @cacheable/net package using npm. ```bash npm install @cacheable/net ``` -------------------------------- ### Install cache-manager Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Command to install the core cache-manager package. ```bash npm install cache-manager ``` -------------------------------- ### Install Cacheable Utils Source: https://github.com/jaredwray/cacheable/blob/main/packages/utils/README.md Install the @cacheable/utils package using npm. ```bash npm install @cacheable/utils --save ``` -------------------------------- ### Install CacheableMemory Source: https://github.com/jaredwray/cacheable/blob/main/packages/memory/README.md Install the CacheableMemory package using npm. ```bash npm install @cacheable/memory ``` -------------------------------- ### Install cacheable Package Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Install the cacheable package using npm. ```bash npm install cacheable ``` -------------------------------- ### Install cacheable-request Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable-request/README.md Install the cacheable-request package using npm. ```shell npm install cacheable-request ``` -------------------------------- ### Basic Cacheable Sync Setup with Redis Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Demonstrates how to set up two cache instances that synchronize their state using a Redis message provider. Ensure to allow for potential network latency. ```javascript import { Cacheable } from 'cacheable'; import { RedisMessageProvider } from '@qified/redis'; // Create a Redis message provider const provider = new RedisMessageProvider({ connection: { host: 'localhost', port: 6379 } }); // Create cache instances with sync enabled const cache1 = new Cacheable({ sync: { qified: provider } }); const cache2 = new Cacheable({ sync: { qified: provider } }); // Set a value in cache1 await cache1.set('key', 'value'); // Note: you might want to sleep for a bit based on the backend. // The value is automatically synced to cache2 const value = await cache2.get('key'); // Returns 'value' ``` -------------------------------- ### Example with Custom Log Levels Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Demonstrates setting a specific log level (e.g., 'info') for the logger and processing files based on changes, with cache reconciliation. ```javascript import pino from 'pino'; import { FileEntryCache } from 'file-entry-cache'; // Create logger with specific level const logger = pino({ level: 'info' }); const cache = new FileEntryCache({ logger, useCheckSum: true }); // This will log at info level when files change const files = ['./src/index.js', './src/utils.js']; files.forEach(file => { const descriptor = cache.getFileDescriptor(file); if (descriptor.changed) { console.log(`Processing changed file: ${file}`); } }); cache.reconcile(); ``` -------------------------------- ### Cacheable Hook Example (BEFORE_SET) Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Implement a hook to execute custom logic before a value is set in the cache. This example logs the key and value being set. ```javascript import { Cacheable, CacheableHooks } from 'cacheable'; const cacheable = new Cacheable(); cacheable.onHook(CacheableHooks.BEFORE_SET, (data) => { console.log(`before set: ${data.key} ${data.value}`); }); ``` -------------------------------- ### Cache Operations: set, get, del, wrap Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Demonstrates basic cache operations including setting, getting, deleting, and wrapping functions. ```APIDOC ## Cache Operations ### Description Perform basic cache operations like setting, getting, deleting, and wrapping functions. ### Code Example ```typescript // With default ttl and refreshThreshold const cache = createCache({ ttl: 10000, refreshThreshold: 3000, }) await cache.set('foo', 'bar') // => bar await cache.get('foo') // => bar await cache.del('foo') // => true await cache.get('foo') // => null await cache.wrap('key', () => 'value') // => value ``` ``` -------------------------------- ### Initialize and Use CacheableMemory Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Demonstrates how to initialize CacheableMemory with custom options and perform basic set and get operations. Options include ttl, useClones, and lruSize. ```javascript import { CacheableMemory } from 'cacheable'; const options = { ttl: '1h', // 1 hour useClones: true, // use clones for the values (default is true) lruSize: 1000, // the size of the LRU cache (default is 0 which is unlimited) } const cache = new CacheableMemory(options); cache.set('key', 'value'); const value = cache.get('key'); // value ``` -------------------------------- ### Run Local Tests and Linting Source: https://github.com/jaredwray/cacheable/blob/main/CONTRIBUTING.md Execute this command locally to install dependencies, build the project, and run tests and linting before submitting a pull request. ```bash pnpm i && pnpm build && pnpm test ``` -------------------------------- ### Using CacheableMemory or lru-cache as Storage Adapter Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Examples of using Keyv with storage adapters like CacheableMemory or lru-cache. ```APIDOC ## Using CacheableMemory or lru-cache as Storage Adapter ### Description Utilize Keyv with storage adapters such as `CacheableMemory` or `lru-cache`. ### Example with CacheableMemory ```typescript import { createCache } from 'cache-manager'; import { Keyv } from 'keyv'; import { KeyvCacheableMemory } from 'cacheable'; const store = new KeyvCacheableMemory({ ttl: 60000, lruSize: 5000 }); const keyv = new Keyv({ store }); const cache = createCache({ stores: [keyv] }); ``` ### Example with lru-cache ```typescript import { createCache } from 'cache-manager'; import { Keyv } from 'keyv'; import { LRU } from 'lru-cache'; const keyv = new Keyv({ store: new LRU({ max: 5000, maxAge: 60000 }) }); const cache = createCache({ stores: [keyv] }); ``` ``` -------------------------------- ### CI/CD Environment Security Setup Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Shows how to configure FileEntryCache for strict security in CI/CD pipelines, restricting file operations to the workspace and using checksums for content validation. ```javascript // Strict security for CI/CD pipelines const cache = new FileEntryCache({ cwd: process.env.GITHUB_WORKSPACE || process.cwd(), restrictAccessToCwd: true, // Prevent access outside workspace useCheckSum: true // Content-based validation }); // All file operations are now restricted to the workspace cache.getFileDescriptor('./src/app.js'); // ✓ Allowed cache.getFileDescriptor('/etc/passwd'); // ✗ Blocked (absolute path outside cwd) cache.getFileDescriptor('../../../root'); // ✗ Blocked (path traversal) ``` -------------------------------- ### Layered Caching with Multiple Stores Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Example of setting up layered caching using multiple stores, such as in-memory and Redis. ```APIDOC ## Layered Caching with Multiple Stores ### Description Set up layered caching with multiple stores like in-memory and Redis. ### Code Example ```typescript import { Keyv } from 'keyv'; import KeyvRedis from '@keyv/redis'; import { CacheableMemory } from 'cacheable'; import { createCache } from 'cache-manager'; // Multiple stores const cache = createCache({ stores: [ // High performance in-memory cache with LRU and TTL new Keyv({ store: new CacheableMemory({ ttl: 60000, lruSize: 5000 }), }), // Redis Store new Keyv({ store: new KeyvRedis('redis://user:pass@localhost:6379'), }), ], }) ``` ``` -------------------------------- ### Importing NodeCache Correctly Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md When using NodeCache, ensure you import it correctly from the package. This example shows the recommended import statement. ```javascript import {NodeCache} from '@cacheable/node-cache'; const cache = new NodeCache(); cache.set('foo', 'bar'); cache.get('foo'); // 'bar' ``` -------------------------------- ### startInterval Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Manually starts the interval timer for checking expired keys. This is typically handled automatically on initialization. ```APIDOC ## startInterval() ### Description Starts the interval timer that periodically checks for and removes expired cache items, based on the configured `checkperiod`. ### Method `void` ``` -------------------------------- ### API Change Example Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable-request/README.md Highlights the specific code change required to adapt to the API modifications introduced in version 10.0.0 and later. ```diff - const cacheableRequest = new CacheableRequest(http.request); + const cacheableRequest = new CacheableRequest(http.request).request(); ``` -------------------------------- ### Cacheable with Secondary Storage (Redis) Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Configure Cacheable to use a secondary storage layer, such as Redis, for enhanced caching. This example uses KeyvRedis. ```javascript import { Cacheable } from 'cacheable'; import KeyvRedis from '@keyv/redis'; const secondary = new KeyvRedis('redis://user:pass@localhost:6379'); const cache = new Cacheable({secondary}); ``` -------------------------------- ### NodeCacheStore with Redis Adapter Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Configure NodeCacheStore to use a Redis storage adapter via Keyv. Ensure Keyv and the Redis adapter are installed. ```javascript import {NodeCacheStore} from '@cacheable/node-cache'; import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv({store: new KeyvRedis('redis://user:pass@localhost:6379')}); const cache = new NodeCacheStore({store: keyv}); // with storage you have the same functionality as the NodeCache but will be using async/await await cache.set('foo', 'bar'); await cache.get('foo'); // 'bar' ``` -------------------------------- ### Creating a Cache Instance Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Demonstrates how to create a cache instance with default memory store or with custom Keyv stores. ```APIDOC ## Creating a Cache Instance ### Description Instantiate a cache with default memory store or with custom Keyv stores. ### Code Example ```typescript import { Keyv } from 'keyv'; import { createCache } from 'cache-manager'; // Memory store by default const cache = createCache() // Single store which is in memory const cache = createCache({ stores: [new Keyv()] }) ``` ``` -------------------------------- ### getFileDescriptorsByPath Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Retrieves all file descriptors that start with the specified path. Useful for getting all files in a directory or a specific path. ```APIDOC ## getFileDescriptorsByPath(filePath: string): FileEntryDescriptor[] ### Description Gets all the file descriptors that start with the path specified. This is useful when you want to get all the files in a directory or a specific path. ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to search for file descriptors. ``` -------------------------------- ### Set, Get, and Clear All Cache Entries Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Illustrates setting multiple key-value pairs, retrieving them to confirm their presence, clearing the entire cache using `clear`, and verifying that all entries are removed. ```typescript await cache.set('key-1', 'value 1') await cache.set('key-2', 'value 2') await cache.get('key-1') // => value 1 await cache.get('key-2') // => value 2 await cache.clear() await cache.get('key-1') // => null await cache.get('key-2') // => null ``` -------------------------------- ### Create Non-Blocking Keyv Redis Instance Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Use `createKeyvNonBlocking` to simplify the setup of a non-blocking Redis instance for Cacheable. Ensure you are using `@keyv/redis` version 4.6.0 or later. ```javascript import { Cacheable } from 'cacheable'; import { createKeyvNonBlocking } from '@keyv/redis'; const secondary = createKeyvNonBlocking('redis://user:pass@localhost:6379'); const cache = new Cacheable({ secondary, nonBlocking: true }); ``` -------------------------------- ### Get Current Date Plus Shorthand Time Source: https://github.com/jaredwray/cacheable/blob/main/packages/utils/README.md Use `shorthandToTime` to calculate a future date and time based on a shorthand time string and a starting date. Returns milliseconds since epoch. ```typescript import { shorthandToTime } from '@cacheable/utils'; const currentDate = new Date(); const timeInMs = shorthandToTime('1h', currentDate); console.log(timeInMs); // Current date + 1 hour in milliseconds since epoch ``` -------------------------------- ### NodeCacheStore Initialization Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Demonstrates how to initialize NodeCacheStore with default settings and with a custom Keyv store. ```APIDOC ## NodeCacheStore Initialization ### Description Initialize `NodeCacheStore` with default in-memory Keyv store or a custom Keyv adapter. ### Usage ```javascript import {NodeCacheStore} from '@cacheable/node-cache'; // Default in-memory store const cache = new NodeCacheStore(); // With a custom Keyv store (e.g., Redis) import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv({store: new KeyvRedis('redis://user:pass@localhost:6379')}); const cacheWithRedis = new NodeCacheStore({store: keyv}); ``` ``` -------------------------------- ### Standalone GET Request with Caching Source: https://github.com/jaredwray/cacheable/blob/main/packages/net/README.md Use the standalone get function for GET requests. Pass a cache instance in the options to enable caching. Only GET responses are cached. ```javascript import { get } from '@cacheable/net'; import { Cacheable } from 'cacheable'; const cache = new Cacheable(); // get / post / patch / del — return { data, response } // Pass `cache` to enable caching. As with the class helpers, only GET // responses are cached; post/patch/del always bypass the cache. const { data } = await get('https://api.example.com/data', { cache }); ``` -------------------------------- ### Initializing CacheTags Source: https://github.com/jaredwray/cacheable/blob/main/packages/utils/README.md Demonstrates how to initialize the CacheTags service with a Keyv store and a namespace. ```APIDOC ## Initialize CacheTags ### Description Instantiates the `CacheTags` service, providing it with a Keyv store and an optional namespace for organizing cache tags. ### Method `new CacheTags(options: { store: Keyv; namespace?: string; enabled?: boolean; onError?: (error: Error) => void })` ### Parameters #### Constructor Parameters - **store** (Keyv) - Required - The Keyv store instance to use. - **namespace** (string) - Optional - A namespace to prefix tag keys. - **enabled** (boolean) - Optional - Whether the service is enabled. Defaults to true. - **onError** ((error: Error) => void) - Optional - Callback for handling errors from non-blocking operations. ### Request Example ```typescript import { Keyv } from 'keyv'; import { CacheTags } from '@cacheable/utils'; const store = new Keyv(); const cacheTags = new CacheTags({ store, namespace: 'app' }); ``` ``` -------------------------------- ### Create Cache with Multiple Keyv Stores Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Illustrates how to configure a cache with multiple storage adapters using Keyv. ```typescript import { createCache } from 'cache-manager'; import { createKeyv } from 'cacheable'; import { createKeyv as createKeyvRedis } from '@keyv/redis'; const memoryStore = createKeyv(); const redisStore = createKeyvRedis('redis://user:pass@localhost:6379'); const cache = createCache({ stores: [memoryStore, redisStore], }); ``` -------------------------------- ### get Source: https://github.com/jaredwray/cacheable/blob/main/packages/net/README.md Performs a GET request. Returns a `DataResponse`. Cached by default. ```APIDOC ## get(url, options?) ### Description Performs a GET request. Returns a `DataResponse`. Cached by default (`caching: false` to disable). ### Method `get` ### Parameters * `url` (string) - The URL for the GET request. * `options` (object, optional) - Request options, including `caching` to disable caching. ``` -------------------------------- ### Create Default Cache with Keyv (v6) Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Shows the basic way to create a cache instance in v6, which defaults to using Keyv. ```typescript import { createCache } from 'cache-manager'; const cache = createCache(); ``` -------------------------------- ### Create Cache with Options Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Create a cache instance with options for checksums, custom working directory, and key storage. ```javascript import fileEntryCache from 'file-entry-cache'; // Create cache with options const cache = fileEntryCache.create('myCache', './.cache', { useCheckSum: true, // Use checksums for more reliable change detection cwd: '/path/to/project', // Custom working directory restrictAccessToCwd: false, // Allow access outside cwd (use with caution) useAbsolutePathAsKey: false // Store relative paths in cache }); let fileDescriptor = cache.getFileDescriptor('./src/file.txt'); console.log(fileDescriptor.changed); // true console.log(fileDescriptor.meta.hash); // checksum hash ``` -------------------------------- ### Creating a New Cache with Options Source: https://github.com/jaredwray/cacheable/blob/main/packages/flat-cache/README.md Illustrates creating a new cache instance using the `create` function, specifying options like `cacheId`, `cacheDir`, and `ttl`. This method loads data from disk if the cache exists. ```javascript import { create } from 'flat-cache'; const cache = create({ cacheId: 'myCacheId', cacheDir: './mycache', ttl: 60 * 60 * 1000 }); ``` -------------------------------- ### get(key) Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Get a value from the cache by key. Returns `undefined` if the key does not exist or has expired. ```APIDOC ## get(key) ### Description Get a value from the cache by key. Returns `undefined` if the key does not exist or has expired. ### Parameters #### Path Parameters - **key** (string) - Required - The key to retrieve. ### Response #### Success Response (200) - **T | undefined** - The value associated with the key, or `undefined` if not found or expired. ``` -------------------------------- ### Create File Entry Cache Instances Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Demonstrates creating cache instances with default and custom working directories. The cache key is always the provided path, but file operations resolve relative paths using the configured `cwd`. ```javascript const cache1 = fileEntryCache.create('cache1'); const cache2 = fileEntryCache.create('cache2', './cache', { cwd: '/project/root' }); const cache3 = new FileEntryCache({ cwd: '/project/root' }); const descriptor = cache2.getFileDescriptor('./src/file.txt'); console.log(descriptor.key); // './src/file.txt' // But file operations resolve from: '/project/root/src/file.txt' ``` -------------------------------- ### Get a value by key Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Use `get` to retrieve a cached value. Returns `undefined` if the key is not found. ```javascript cache.get('foo'); // 'bar' ``` -------------------------------- ### Get Value by Key Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Retrieve a cached value using its key with the `get` method. Returns `undefined` if the key is not found or has expired. ```javascript await cache.get('foo'); // 'bar' ``` -------------------------------- ### Iterating Over Stores with Keyv Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Demonstrates how to iterate over all stores and retrieve all keys using the Keyv API. Be cautious with iterator usage due to potential performance impacts and ensure the storage adapter supports it. ```ts import Keyv from 'keyv'; import { createKeyv } from '@keyv/redis'; import { createCache } from 'cache-manager'; const keyv = new Keyv(); const keyvRedis = createKeyv('redis://user:pass@localhost:6379'); const cache = createCache({ stores: [keyv, keyvRedis], }); // add some data await cache.set('key-1', 'value 1'); await cache.set('key-2', 'value 2'); // get the store you want to iterate over. In this example we are using the second store (redis) const store = cache.stores[1]; if(store?.iterator) { for await (const [key, value] of store.iterator({})) { console.log(key, value); } } ``` -------------------------------- ### Create Cache Instance Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Demonstrates how to create a cache instance with a specific cache ID and retrieve it. ```ts const cache = createCache({cacheId: 'my-cache-id'}); cache.cacheId(); // => 'my-cache-id' ``` -------------------------------- ### Initialize NodeCacheStore Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Instantiate NodeCacheStore for basic usage. Requires importing the class. ```javascript import {NodeCacheStore} from '@cacheable/node-cache'; const cache = new NodeCacheStore(); await cache.set('foo', 'bar'); await cache.get('foo'); // 'bar' ``` -------------------------------- ### Cache Management Methods Source: https://github.com/jaredwray/cacheable/blob/main/packages/cacheable/README.md Methods for basic cache operations including setting, getting, checking existence, taking (get and delete), deleting, and clearing cache entries. ```APIDOC ## set(key, value, ttlOrOptions?) ### Description Sets a value in the cache. ### Parameters - **key** (string) - The key under which to store the value. - **value** (any) - The value to store in the cache. - **ttlOrOptions** (number | { ttl?: string | number, tags?: string[] }) - Optional. Either a Time To Live (TTL) in milliseconds or an options object containing `ttl` and `tags` for cache invalidation. ### Example ```javascript await cache.set('myKey', 'myValue', 3600); await cache.set('anotherKey', { data: 'some data' }, { ttl: '1h', tags: ['entity:123'] }); ``` ``` ```APIDOC ## setMany(items) ### Description Sets multiple values in the cache. ### Parameters - **items** (Array<{key: string, value: any, ttl?: string | number, tags?: string[]}>) - An array of objects, where each object contains the `key`, `value`, and optional `ttl` and `tags` for a cache entry. ### Example ```javascript await cache.setMany([ { key: 'key1', value: 'value1', ttl: 60 }, { key: 'key2', value: { data: 'info' }, tags: ['user:456'] } ]); ``` ``` ```APIDOC ## get(key, options?) ### Description Gets a value from the cache. ### Parameters - **key** (string) - The key of the value to retrieve. - **options** ({ raw?: boolean }) - Optional. If `raw` is true, the raw cached value is returned without any transformation. ### Example ```javascript const value = await cache.get('myKey'); const rawValue = await cache.get('myKey', { raw: true }); ``` ``` ```APIDOC ## getMany(keys, options?) ### Description Gets multiple values from the cache. ### Parameters - **keys** (Array) - An array of keys to retrieve values for. - **options** ({ raw?: boolean }) - Optional. If `raw` is true, the raw cached values are returned. ### Example ```javascript const values = await cache.getMany(['key1', 'key2']); const rawValues = await cache.getMany(['key1', 'key2'], { raw: true }); ``` ``` ```APIDOC ## has(key) ### Description Checks if a value exists in the cache. ### Parameters - **key** (string) - The key to check for. ### Returns - (boolean) - `true` if the key exists in the cache, `false` otherwise. ### Example ```javascript const exists = await cache.has('myKey'); ``` ``` ```APIDOC ## hasMany(keys) ### Description Checks if multiple values exist in the cache. ### Parameters - **keys** (Array) - An array of keys to check for. ### Returns - (boolean) - `true` if all keys exist in the cache, `false` otherwise. ### Example ```javascript const allExist = await cache.hasMany(['key1', 'key2']); ``` ``` ```APIDOC ## take(key) ### Description Retrieves a value from the cache and then deletes it. ### Parameters - **key** (string) - The key of the value to take. ### Returns - (any | undefined) - The value associated with the key, or `undefined` if the key does not exist. ### Example ```javascript const value = await cache.take('myKey'); ``` ``` ```APIDOC ## takeMany(keys) ### Description Retrieves multiple values from the cache and then deletes them. ### Parameters - **keys** (Array) - An array of keys to take. ### Returns - (Array) - An array of values corresponding to the keys, in the same order. ### Example ```javascript const values = await cache.takeMany(['key1', 'key2']); ``` ``` ```APIDOC ## delete(key) ### Description Deletes a value from the cache. ### Parameters - **key** (string) - The key of the value to delete. ### Example ```javascript await cache.delete('myKey'); ``` ``` ```APIDOC ## deleteMany(keys) ### Description Deletes multiple values from the cache. ### Parameters - **keys** (Array) - An array of keys to delete. ### Example ```javascript await cache.deleteMany(['key1', 'key2']); ``` ``` ```APIDOC ## clear() ### Description Clears all entries from the cache stores (both primary and secondary layers). ### Example ```javascript await cache.clear(); ``` ``` -------------------------------- ### Create Synchronous Memory Cache (v5) Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Demonstrates how to create a memory cache synchronously using the `memoryStore` from v5. ```typescript import { createCache, memoryStore } from 'cache-manager'; // Create memory cache synchronously const memoryCache = createCache(memoryStore({ max: 100, ttl: 10 * 1000 /*milliseconds*/, })); ``` -------------------------------- ### Legacy Cache Loading with require Source: https://github.com/jaredwray/cacheable/blob/main/packages/flat-cache/README.md Demonstrates how to load a cache using the legacy `require` method. If the cache does not exist for the given ID, a new one will be prepared. ```javascript const flatCache = require('flat-cache'); // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created const cache = flatCache.load('cacheId'); ``` -------------------------------- ### getStats() Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Get the stats of the cache. ```APIDOC ## getStats() ### Description Get the stats of the cache. ### Response #### Success Response (200) - **NodeCacheStats** - An object containing cache statistics (hits, misses, keys, ksize, vsize). ``` -------------------------------- ### HTTP Method Helpers with Typed Responses Source: https://github.com/jaredwray/cacheable/blob/main/packages/net/README.md Illustrates the use of various HTTP method helpers (get, post, put, patch, delete, head) provided by CacheableNet. GET requests are cached by default, while others have specific caching behaviors. ```javascript import { CacheableNet } from '@cacheable/net'; const net = new CacheableNet(); // GET — cached by default const { data } = await net.get('https://api.example.com/users/1'); // GET with a typed result (TypeScript) type User = { id: number; name: string }; const { data: user } = await net.get('https://api.example.com/users/1'); // POST — body is JSON-serialized and Content-Type set to application/json automatically await net.post('https://api.example.com/users', { name: 'Ada' }); // PUT / PATCH — same body handling as POST await net.put('https://api.example.com/users/1', { name: 'Ada Lovelace' }); await net.patch('https://api.example.com/users/1', { name: 'Ada' }); // DELETE — body is optional await net.delete('https://api.example.com/users/1'); // HEAD — returns the raw Response (no body) const head = await net.head('https://api.example.com/users/1'); console.log(head.headers.get('content-length')); ``` -------------------------------- ### mget(keys) Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Get multiple values from the cache by keys. ```APIDOC ## mget(keys) ### Description Get multiple values from the cache by keys. ### Parameters #### Path Parameters - **keys** (Array) - Required - An array of keys to retrieve. ### Response #### Success Response (200) - **Record** - An object where keys are the requested cache keys and values are their corresponding cached values or `undefined`. ``` -------------------------------- ### Getting Key Tags Source: https://github.com/jaredwray/cacheable/blob/main/packages/utils/README.md Retrieves the tags currently associated with a specific cache key. ```APIDOC ## getTags ### Description Retrieves the array of tags currently associated with a given cache key. Returns `undefined` if the key does not have an associated tag snapshot. ### Method `getTags(key: string): Promise` ### Parameters #### Path Parameters - **key** (string) - Required - The cache key to retrieve tags for. ### Response #### Success Response (200) - **string[] | undefined** - An array of tags, or `undefined` if the key has no snapshot. ### Request Example ```typescript await cacheTags.setKeyTags('user:42', ['users', 'org:7']); console.log(await cacheTags.getTags('user:42')); // ['users', 'org:7'] console.log(await cacheTags.getTags('missing')); // undefined ``` ``` -------------------------------- ### Getting Stale Keys Source: https://github.com/jaredwray/cacheable/blob/main/packages/utils/README.md Efficiently checks multiple keys for staleness in a single operation. ```APIDOC ## getStaleKeys ### Description Checks a list of keys for staleness. This method performs two batched store reads to efficiently determine which of the provided keys are stale. ### Method `getStaleKeys(keys: string[]): Promise` ### Parameters #### Path Parameters - **keys** (string[]) - Required - An array of cache keys to check for staleness. ### Response #### Success Response (200) - **string[]** - An array of stale keys. ### Request Example ```typescript await cacheTags.setKeyTags('a', ['x']); await cacheTags.setKeyTags('b', ['y']); await cacheTags.invalidateTag('x'); console.log(await cacheTags.getStaleKeys(['a', 'b', 'untagged'])); // ['a'] ``` ``` -------------------------------- ### Basic Usage: Create and Track Files Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Create a cache instance and track file descriptors. Repeated calls report 'changed: true' until 'reconcile()' is called. ```javascript import fileEntryCache from 'file-entry-cache'; const cache = fileEntryCache.create('cache1'); // Using relative paths let fileDescriptor = cache.getFileDescriptor('./src/file.txt'); console.log(fileDescriptor.changed); // true as it is the first time console.log(fileDescriptor.key); // './src/file.txt' (stored as provided) // Repeated calls keep reporting `changed: true` until you persist the state // with reconcile(); only then does the file become the cached baseline. cache.reconcile(); fileDescriptor = cache.getFileDescriptor('./src/file.txt'); console.log(fileDescriptor.changed); // false as it has not changed since reconcile() // do something to change the file fs.writeFileSync('./src/file.txt', 'new data foo bar'); // check if the file has changed fileDescriptor = cache.getFileDescriptor('./src/file.txt'); console.log(fileDescriptor.changed); // true ``` -------------------------------- ### get Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Retrieves a value from the cache using its key. Returns undefined if the key does not exist. ```APIDOC ## get(key: string | number): T | undefined ### Description Retrieves a value from the cache by its key. If the key is not found in the cache, it returns `undefined`. ### Method Signature `get(key: string | number): T | undefined` ### Parameters - **key** (string | number) - Required - The key of the value to retrieve. ### Returns - **T | undefined** - The cached value if the key exists, otherwise `undefined`. ### Example ```javascript cache.get('foo'); // Expected output: 'bar' ``` ``` -------------------------------- ### Create Cache Instance (Multiple Stores) Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Sets up a cache with multiple layers of storage, combining an in-memory cache (CacheableMemory) with a persistent store (Redis via Keyv). This enables high-performance caching with fallback persistence. ```typescript import { Keyv } from 'keyv'; import KeyvRedis from '@keyv/redis'; import { CacheableMemory } from 'cacheable'; import { createCache } from 'cache-manager'; // Multiple stores const cache = createCache({ stores: [ // High performance in-memory cache with LRU and TTL new Keyv ({ store: new CacheableMemory ({ ttl: 60000, lruSize: 5000 }), }), // Redis Store new Keyv ({ store: new KeyvRedis('redis://user:pass@localhost:6379'), }), ], }) ``` -------------------------------- ### Create Cache Instance (Single Keyv Store) Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Configures a cache instance with a single Keyv store. This allows for basic persistence or custom Keyv configurations. ```typescript // Single store which is in memory const cache = createCache({ stores: [new Keyv()], }) ``` -------------------------------- ### ttl Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Gets the expiration time of a key in milliseconds. Returns null if the key is not found or has expired. ```APIDOC ## ttl `ttl(key): Promise` Gets the expiration time of a key in milliseconds. Returns a null if not found or expired. ### Parameters #### Path Parameters - **key** (string) - Required - The key to retrieve the expiration time for. ### Response #### Success Response (number | null) - Returns the expiration time of the key in milliseconds, or null if the key is not found or expired. ### Request Example ```typescript await cache.ttl('key'); // => the expiration time in milliseconds ``` ``` -------------------------------- ### Basic Usage of FlatCache Source: https://github.com/jaredwray/cacheable/blob/main/packages/flat-cache/README.md Initialize FlatCache, set a key-value pair, and save it to disk. ```javascript import { FlatCache } from 'flat-cache'; const cache = new FlatCache(); cache.setKey('key', 'value'); cache.save(); // Saves the data to disk ``` -------------------------------- ### take(key) Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Get a value from the cache by key and delete it. Useful for single-use values like OTPs. ```APIDOC ## take(key) ### Description Get a value from the cache by key and delete it. Useful for single-use values like OTPs. ### Parameters #### Path Parameters - **key** (string) - Required - The key to retrieve and delete. ### Response #### Success Response (200) - **T | undefined** - The value associated with the key before deletion, or `undefined` if not found or expired. ``` -------------------------------- ### Using Legacy Storage Adapters with KeyvAdapter Source: https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/README.md Shows how to use legacy storage adapters for cache-manager with KeyvAdapter, allowing integration of older adapters with the Keyv ecosystem. ```ts import { createCache, KeyvAdapter } from 'cache-manager'; import { Keyv } from 'keyv'; import { redisStore } from 'cache-manager-redis-yet'; const adapter = new KeyvAdapter( await redisStore() ); const keyv = new Keyv({ store: adapter }); const cache = createCache({ stores: [keyv]}); ``` -------------------------------- ### Get TTL from Expires Date Source: https://github.com/jaredwray/cacheable/blob/main/packages/utils/README.md This function calculates the TTL in milliseconds directly from an expiration date object. ```typescript import { getTtlFromExpires } from '@cacheable/utils'; const expirationDate = new Date(Date.now() + 1000 * 60 * 5); // 5 minutes from now const ttl = getTtlFromExpires(expirationDate); console.log(ttl); // 300000 ``` -------------------------------- ### CacheableMemory Methods Source: https://github.com/jaredwray/cacheable/blob/main/packages/memory/README.md Provides methods for interacting with the cache, such as setting, getting, deleting, and managing cache entries. ```APIDOC ## set(key, value, ttl?) ### Description Sets a value in the cache with an optional time-to-live. ### Method `set` ### Parameters - **key**: The key under which to store the value. - **value**: The value to store in the cache. - **ttl** (optional): The time-to-live for this specific cache entry in milliseconds. ``` ```APIDOC ## setMany([{key, value, ttl?}]) ### Description Sets multiple values in the cache from an array of `CacheableItem` objects. ### Method `setMany` ### Parameters - **items**: An array of objects, where each object has `key`, `value`, and an optional `ttl`. ``` ```APIDOC ## get(key) ### Description Retrieves a value from the cache using its key. ### Method `get` ### Parameters - **key**: The key of the value to retrieve. ``` ```APIDOC ## getMany([keys]) ### Description Retrieves multiple values from the cache using an array of keys. ### Method `getMany` ### Parameters - **keys**: An array of keys for the values to retrieve. ``` ```APIDOC ## getRaw(key) ### Description Retrieves a raw value from the cache, including metadata, as `CacheableStoreItem`. ### Method `getRaw` ### Parameters - **key**: The key of the value to retrieve. ``` ```APIDOC ## getManyRaw([keys]) ### Description Retrieves multiple raw values from the cache as `CacheableStoreItem` objects. ### Method `getManyRaw` ### Parameters - **keys**: An array of keys for the values to retrieve. ``` ```APIDOC ## has(key) ### Description Checks if a value exists in the cache for the given key. ### Method `has` ### Parameters - **key**: The key to check for existence. ``` ```APIDOC ## hasMany([keys]) ### Description Checks if multiple values exist in the cache for the given keys. ### Method `hasMany` ### Parameters - **keys**: An array of keys to check for existence. ``` ```APIDOC ## delete(key) ### Description Deletes a value from the cache using its key. ### Method `delete` ### Parameters - **key**: The key of the value to delete. ``` ```APIDOC ## deleteMany([keys]) ### Description Deletes multiple values from the cache using an array of keys. ### Method `deleteMany` ### Parameters - **keys**: An array of keys for the values to delete. ``` ```APIDOC ## take(key) ### Description Retrieves a value from the cache and then deletes it. ### Method `take` ### Parameters - **key**: The key of the value to take. ``` ```APIDOC ## takeMany([keys]) ### Description Retrieves multiple values from the cache and then deletes them. ### Method `takeMany` ### Parameters - **keys**: An array of keys for the values to take. ``` ```APIDOC ## wrap(function, WrapSyncOptions) ### Description Wraps a synchronous function, caching its results. ### Method `wrap` ### Parameters - **function**: The synchronous function to wrap. - **WrapSyncOptions**: Options for wrapping the function, potentially including cache key generation and TTL. ``` ```APIDOC ## clear() ### Description Clears all entries from the cache. ### Method `clear` ``` ```APIDOC ## onHook(hook, handler) ### Description Registers a handler for a specific `CacheableMemoryHooks` event. ### Method `onHook` ### Parameters - **hook**: The name of the hook/event to listen for. - **handler**: The function to execute when the hook is triggered. ``` ```APIDOC ## checkExpired() ### Description Manually checks for and removes expired keys from the cache. ### Method `checkExpired` ``` ```APIDOC ## startIntervalCheck() ### Description Starts the background interval check for expired keys if `checkInterval` is configured. ### Method `startIntervalCheck` ``` ```APIDOC ## stopIntervalCheck() ### Description Stops the background interval check for expired keys. ### Method `stopIntervalCheck` ``` -------------------------------- ### getFileDescriptorsByPath(filePath: string): FileEntryDescriptor[] Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Retrieves all file descriptors whose paths start with the specified prefix. ```APIDOC ## getFileDescriptorsByPath(filePath: string): FileEntryDescriptor[] ### Description Returns an array of `FileEntryDescriptor` objects that start with the path prefix specified. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **filePath** (string) - The path prefix to search for. ### Returns - **FileEntryDescriptor[]** - An array of `FileEntryDescriptor` objects matching the path prefix. ``` -------------------------------- ### Retrieve All Keys from Cache Source: https://github.com/jaredwray/cacheable/blob/main/packages/node-cache/README.md Use the `keys` method to get an array containing all the keys currently stored in the cache. ```javascript cache.keys(); // ['foo', 'bar'] ``` -------------------------------- ### Secure Build Tool Configuration Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Illustrates secure configuration for a build tool using FileEntryCache, ensuring `restrictAccessToCwd` is enabled to process user-provided file paths safely within defined boundaries. ```javascript // Secure build tool configuration const cache = fileEntryCache.create('.buildcache', './cache', { useCheckSum: true, cwd: process.cwd(), restrictAccessToCwd: true // Enable strict path checking for security }); // Process user-provided file paths safely function processUserFile(userProvidedPath) { try { const descriptor = cache.getFileDescriptor(userProvidedPath); // Safe to process - file is within boundaries return descriptor; } catch (error) { if (error.message.includes('Path traversal attempt blocked')) { console.warn('Security: Blocked access to:', userProvidedPath); return null; } throw error; } } ``` -------------------------------- ### Getting a Cache Value Source: https://github.com/jaredwray/cacheable/blob/main/packages/flat-cache/README.md Retrieves the value associated with a given key from the cache. If the key does not exist, it returns `undefined`. ```javascript const value = cache.get('myKey'); ``` -------------------------------- ### Load Cache from File Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Create a cache instance by loading existing cache data from a file. ```javascript import fileEntryCache from 'file-entry-cache'; // Basic usage const cache = fileEntryCache.createFromFile('/path/to/cache/file'); let fileDescriptor = cache.getFileDescriptor('./src/file.txt'); console.log(fileDescriptor.changed); // false as it has not changed from the saved cache. // With options const cache2 = fileEntryCache.createFromFile('/path/to/cache/file', { useCheckSum: true, cwd: '/path/to/project' }); ``` -------------------------------- ### Basic FileEntryCache Usage with Path Security Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Demonstrates basic FileEntryCache instantiation and how `restrictAccessToCwd` (enabled by default) blocks path traversal attempts. Shows how to explicitly disable this protection if necessary. ```javascript const cache = new FileEntryCache({ cwd: '/project/root' }); // This will work - file is within cwd const descriptor = cache.getFileDescriptor('./src/index.js'); // This will throw an error - attempts to access parent directory try { cache.getFileDescriptor('../../../etc/passwd'); } catch (error) { console.error(error); // Path traversal attempt blocked } // To allow parent directory access (not recommended for untrusted input) const unsafeCache = new FileEntryCache({ cwd: '/project/root', restrictAccessToCwd: false // Explicitly disable protection }); ``` -------------------------------- ### Cache Portability with Relative Paths and CWD Source: https://github.com/jaredwray/cacheable/blob/main/packages/file-entry-cache/README.md Illustrates how using relative paths with a consistent `cwd` makes cache files portable across different machines. This is beneficial for CI/CD and team development. ```javascript // On machine A (project at /home/user/project) const cacheA = fileEntryCache.create('build-cache', './cache', { cwd: '/home/user/project' }); cacheA.getFileDescriptor('./src/index.js'); // Resolves to /home/user/project/src/index.js cacheA.reconcile(); // On machine B (project at /workspace/project) const cacheB = fileEntryCache.create('build-cache', './cache', { cwd: '/workspace/project' }); cacheB.getFileDescriptor('./src/index.js'); // Resolves to /workspace/project/src/index.js // Cache hit! File hasn't changed since machine A ```