### Catbox Client Initialization Example Source: https://github.com/hapijs/catbox/blob/master/API.md Demonstrates how to instantiate a Catbox Client with a specific caching strategy engine and configuration options. ```javascript const catbox = require('@hapi/catbox'); const catboxMemory = require('@hapi/catbox-memory'); // Example using the memory strategy const client = new catbox.Client(catboxMemory, { partition: 'my-app-cache' }); // To use other strategies like Redis or Memcached, you would install them separately // and pass their respective engine modules here. // For example: // const catboxRedis = require('@hapi/catbox-redis'); // const redisClient = new catbox.Client(catboxRedis, { partition: 'my-redis-cache', host: '127.0.0.1', port: 6379 }); async function initializeCache() { try { await client.start(); console.log('Catbox client started successfully.'); } catch (err) { console.error('Failed to start Catbox client:', err); } } initializeCache(); ``` -------------------------------- ### Catbox Client API Source: https://github.com/hapijs/catbox/blob/master/API.md Details the methods available on the Catbox Client object for interacting with cache strategies. Includes connection management, data retrieval, storage, and validation. ```APIDOC Client: __constructor__(engine, options) engine: An object or prototype function implementing the cache strategy. - function: A prototype function with the signature `function(options)`. Catbox will call `new func(options)`. - object: A pre-instantiated client implementation object. Does not support passing `options`. options: The strategy configuration object. Common options include: - partition: The partition name used to isolate cached results across multiple clients. API Methods: start() - Creates a connection to the cache server. Must be called before any other method. - Returns: Promise that resolves when the connection is established. - Throws: Errors if the connection fails. stop() - Terminates the connection to the cache server. - Returns: Promise that resolves when the connection is terminated. get(key) - Retrieves an item from the cache engine. - Parameters: - key: A cache key object with `segment` and `id` properties. - Returns: - null: If the item is not found. - object: An object with `item`, `stored` (timestamp), and `ttl` (remaining time-to-live) properties. - Throws: Errors if the request failed. set(key, value, ttl) - Stores an item in the cache for a specified duration. - Parameters: - key: A cache key object with `segment` and `id` properties. - value: The string or object value to be stored. - ttl: A time-to-live value in milliseconds. - Returns: Promise that resolves when the item is stored. - Throws: Errors if the storage fails. drop(key) - Removes an item from the cache. - Parameters: - key: A cache key object with `segment` and `id` properties. - Returns: Promise that resolves when the item is removed. - Throws: Errors if the removal fails. isReady() - Returns `true` if the cache engine is ready, `false` otherwise. validateSegmentName(segment) - Validates a segment name. - Parameters: - segment: The segment name string to validate. - Returns: - null: If the segment name is valid. - Error: An instance of Error with an appropriate message if the segment name is invalid. Cache Key Object Structure: - segment: A caching segment name string. Used to isolate different sets of items. - id: A unique item identifier string (per segment). Can be an empty string. ``` -------------------------------- ### hapijs/catbox Policy Configuration Source: https://github.com/hapijs/catbox/blob/master/API.md Defines the structure and options for the Policy object used in hapijs/catbox. It allows configuration of cache expiration, item generation functions, stale item handling, and error management. ```APIDOC Policy: Constructor: new Policy(options, [cache, segment]) Parameters: options (object): Configuration options for the policy. - expiresIn (number): Relative expiration in milliseconds since item was saved. Cannot be used with expiresIn. - expiresAt (string): Time of day ('HH:MM') for route-wide expiration. Uses local time. Cannot be used with expiresIn. - generateFunc (function): Function to generate a new cache item if not found. Signature: async function(id, flags) - id (string|object): The cache item ID provided to get(). - flags (object): Object for passing back additional flags. - ttl (number): Cache TTL in milliseconds. Set to 0 to skip caching. Defaults to global policy. - staleIn (number|function): Milliseconds to mark an item as stale and attempt regeneration. Must be less than expiresIn. If function: function(stored, ttl) where 'stored' is storage timestamp and 'ttl' is remaining TTL. - staleTimeout (number): Milliseconds to wait before returning stale value while generateFunc is running. - generateTimeout (number): Milliseconds to wait before returning a timeout error for generateFunc. Required if generateFunc is present. Set to false to disable. - dropOnError (boolean): If true, errors/timeouts in generateFunc evict stale values. Defaults to true. - generateOnReadError (boolean): If false, upstream cache read errors stop generateFunc calls. Defaults to true. - generateIgnoreWriteError (boolean): If false, upstream cache write errors are returned with the generated value. Defaults to true. - pendingGenerateTimeout (number): Milliseconds before allowing subsequent generateFunc calls for an in-progress ID. Defaults to 0. - getDecoratedValue (boolean): If true, policy.get() returns { value, cached, report }. Defaults to false. cache (Client): An instance of a Client that has been started. segment (string): The segment name used to isolate cached items within the cache partition. Required when cache is provided. ``` -------------------------------- ### HapiJS Catbox Policy Object API Source: https://github.com/hapijs/catbox/blob/master/API.md The Policy object in HapiJS Catbox manages cache operations. It provides methods to retrieve, store, and invalidate cache items, manage cache rules, and access statistics. Concurrent requests for the same item are handled efficiently by queuing. ```APIDOC Policy Object Methods: - `await get(id)` - Retrieves an item from the cache. - If the item is not found and a `generateFunc` was provided, it generates, stores, and returns a new value. Concurrent requests are queued and processed once. - Parameters: - `id`: The unique item identifier. Can be a string or an object with an 'id' key. - Return Value: - The requested item if found, otherwise `null`. - Throws errors if any occur. - If `getDecoratedValue` is `true`, returns an object with: - `value`: The fetched or generated value. - `cached`: `null` if not found, or an object with `item`, `stored` (timestamp), `ttl`, and `isStale`. - `report`: Logging information including `msec`, `stored`, `isStale`, `ttl`, and `error`. - `await set(id, value, ttl)` - Stores an item in the cache. - Parameters: - `id`: The unique item identifier. - `value`: The string or object value to store. - `ttl`: Time-to-live override in milliseconds. Set to `0` to use default caching rules. - Errors are thrown if any occur. - `await drop(id)` - Removes an item from the cache. - Parameters: - `id`: The unique item identifier. - Errors are thrown if any occur. - `ttl(created)` - Calculates the remaining time-to-live for an item based on its creation timestamp and configured rules. - Parameters: - `created`: The creation timestamp in milliseconds. - Returns: The time-to-live left in milliseconds. - `rules(options)` - Modifies the policy rules after the object has been constructed. Items already stored are not affected. - Parameters: - `options`: The same options object used for `Policy` constructor. - `isReady()` - Checks if the cache engine is ready. - Returns: `true` if ready, `false` if not ready or no engine is set. - `stats` (object) - Provides statistics about cache operations. - Properties: - `sets`: Number of cache writes. - `gets`: Number of `get()` requests. - `hits`: Number of `get()` requests that found an item (can be stale). - `stales`: Number of cache reads with stale requests (first request in a queued `get()`). - `generates`: Number of calls to the generate function. - `errors`: Count of cache operation errors. - `events` (podium event emitter) - Emits `'error'` events on channels: - `'persist'`: Cache errors during new value generation. - `'generate'`: Errors thrown during new value generation. - `client` - A reference to the cache client if one is set. Note: Errors from `set()` and `drop()` are reported directly by the function calls, not via events. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.