### Install Keyv Core Package Source: https://keyv.org/docs/index This command installs the core Keyv package as a dependency in the current project. Keyv provides a consistent interface for key-value storage, with in-memory storage as the default if no adapter is specified. ```Shell npm install --save keyv ``` -------------------------------- ### Install Keyv Redis Storage Adapter Source: https://keyv.org/docs/index Provides the npm command to install `keyv-redis`, a common storage adapter for Keyv. This package enables Keyv to use Redis as its backend for storing key-value pairs. ```Shell npm install --save keyv-redis ``` -------------------------------- ### Test a Custom Keyv Compression Adapter Source: https://keyv.org/docs/index Provides an example of how to use the `@keyv/test-suite` package to validate a custom Keyv compression adapter. It demonstrates calling `keyvCompresstionTests` with a test runner and an instance of a compression adapter like `KeyvGzip`. ```JavaScript const {keyvCompresstionTests} = require('@keyv/test-suite'); const KeyvGzip = require('@keyv/compress-gzip'); keyvCompresstionTests(test, new KeyvGzip()); ``` -------------------------------- ### Enable LZ4 Compression with Keyv Source: https://keyv.org/docs/index Illustrates how to integrate LZ4 compression into Keyv by importing `@keyv/compress-lz4` and providing an instance of `KeyvLz4` to the `compression` option during Keyv initialization. ```JavaScript import Keyv from 'keyv'; import KeyvLz4 from '@keyv/compress-lz4'; const keyvLz4 = new KeyvLz4(); const keyv = new Keyv({ compression: keyvLz4 }); ``` -------------------------------- ### Enable Gzip Compression in Keyv Source: https://keyv.org/docs/index This snippet illustrates how to enable Gzip compression for a Keyv instance. It requires installing the `@keyv/compress-gzip` package and then passing an instance of `KeyvGzip` to the `compression` option in the Keyv constructor. ```javascript const KeyvGzip = require('@keyv/compress-gzip'); const Keyv = require('keyv'); const keyvGzip = new KeyvGzip(); const keyv = new Keyv({ compression: KeyvGzip }); ``` -------------------------------- ### Instantiate a Module with Keyv Caching Enabled Source: https://keyv.org/docs/index Shows how to create an instance of a module that has Keyv caching integrated. In this example, it passes a Redis connection string (`redis://localhost`) to the module's `cache` option, enabling Redis-backed caching for the module. ```JavaScript const AwesomeModule = require('awesome-module'); const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' }); ``` -------------------------------- ### Create Keyv Instance with SQLite Storage Source: https://keyv.org/docs/index This snippet demonstrates how to initialize a Keyv instance using a SQLite database. Keyv automatically loads the appropriate storage adapter based on the provided connection string, simplifying setup for various backends. ```javascript const keyv = new Keyv('sqlite://path/to/database.sqlite'); ``` -------------------------------- ### Create Project Directory for Keyv Source: https://keyv.org/docs/index This command sequence creates a new directory named 'keyv' and then navigates into it, preparing the environment for a new Keyv project. This is a standard initial step for setting up a development workspace. ```Shell mkdir keyv cd keyv ``` -------------------------------- ### Enable Brotli Compression with Keyv Source: https://keyv.org/docs/index Demonstrates how to configure Keyv to use Brotli compression by importing the `@keyv/compress-brotli` package and passing an instance of `KeyvBrotli` to the Keyv constructor's `compression` option. ```JavaScript import Keyv from 'keyv'; import KeyvBrotli from '@keyv/compress-brotli'; const keyvBrotli = new KeyvBrotli(); const keyv = new Keyv({ compression: keyvBrotli }); ``` -------------------------------- ### Keyv Constructor and Options Parameters Source: https://keyv.org/docs/index This API documentation details the parameters available for the Keyv constructor and its associated options object. It covers configuration for connection URIs, default TTL, custom serialization, and specifying storage adapters or instances. ```APIDOC Keyv Constructor Parameters: uri: String (Optional) - The connection string URI. Merged into the options object as options.uri. Default: undefined options: Object (Optional) - An object containing configuration options, also passed through to the storage adapter. Keyv Options Parameters: namespace: String (Optional) - Namespace for the current instance. Default: 'keyv' ttl: Number (Optional) - Default Time-To-Live in milliseconds for key-value pairs. Can be overridden by .set(). Default: undefined compression: @keyv/compress- (Optional) - Compression package to use (e.g., @keyv/compress-gzip). Default: undefined serialize: Function (Optional) - A custom serialization function. Default: JSONB.stringify deserialize: Function (Optional) - A custom deserialization function. Default: JSONB.parse store: Storage adapter instance (Optional) - The storage adapter instance to be used by Keyv. Default: new Map() adapter: String (Optional) - Specify an adapter to use (e.g., 'redis' or 'mongodb'). Default: undefined ``` -------------------------------- ### Create Keyv Instance with MongoDB Connection URI Source: https://keyv.org/docs/index This example illustrates how to create a Keyv instance connected to a MongoDB database using a connection URI. It also includes basic error handling for database connection issues, demonstrating how to listen for 'error' events. ```javascript const Keyv = require('keyv'); const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); // Handle DB connection errors keyv.on('error', err => console.log('Connection Error', err)); ``` -------------------------------- ### Install Keyv Official Storage Adapters Source: https://keyv.org/docs/index These commands install various official Keyv storage adapters for different database systems such as Redis, Valkey, Memcache, Mongo, SQLite, Postgres, MySQL, and Etcd. Installing an adapter allows Keyv to persist data using the chosen backend instead of just in-memory storage. ```Shell npm install --save @keyv/redis npm install --save @keyv/valkey npm install --save @keyv/memcache npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql npm install --save @keyv/etcd ``` -------------------------------- ### Create Keyv Instance with Third-Party LRU Cache Adapter Source: https://keyv.org/docs/index This snippet shows how to integrate a third-party module like `quick-lru` (which implements the Map API) as a custom storage adapter for Keyv. It demonstrates passing a custom store instance to the Keyv constructor and includes error handling for connection issues. ```javascript const Keyv = require('keyv'); const QuickLRU = require('quick-lru'); const lru = new QuickLRU({ maxSize: 1000 }); const keyv = new Keyv({ store: lru }); // Handle DB connection errors keyv.on('error', err => console.log('Connection Error', err)); ``` -------------------------------- ### Keyv Data Manipulation Methods: set and delete Source: https://keyv.org/docs/index This API documentation describes the `set` and `delete` methods for managing key-value pairs in Keyv. It details their parameters, return values, and provides examples for setting values with and without TTL, and deleting specific keys. ```APIDOC Method: set(key, value, [ttl]) Description: Sets a value for a specified key. Parameters: key: String (Required) - Unique identifier used to look up the value. Keys are persistent by default. value: Any (Required) - The data value associated with the key. ttl: Number (Optional) - Expiry time in milliseconds for the key-value pair. Returns: Promise - Resolves to true on success. Method: delete(key) Description: Deletes an entry for a specified key. Parameters: key: String (Required) - Unique identifier of the key to delete. Returns: Promise - Resolves to true if the key existed and was deleted, false if not. Usage Examples: // Set a key-value pair that expires in 1000 milliseconds await keyv.set('foo', 'expires in 1 second', 1000); // Set a key-value pair that never expires await keyv.set('bar', 'never expires'); // Delete the key-value pair for the 'foo' key await keyv.delete('foo'); ``` -------------------------------- ### Set Up a New NestJS Project Source: https://keyv.org/docs/caching/caching-nestjs These commands guide you through the initial setup of a NestJS project. They involve globally installing the Nest CLI, creating a new project directory, and navigating into it to begin development. ```Shell $ npm i -g @nestjs/cli $ nest new nestjs-keyv-cache $ cd nestjs-keyv-cache ``` -------------------------------- ### Keyv Initialization with Redis Store and Options (v5) Source: https://keyv.org/docs/v4-to-v5 This example shows how to initialize Keyv v5 when passing additional options. The options, such as 'namespace', are provided to the KeyvRedis storage adapter constructor. ```javascript import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379',{ namespace: 'my-namespace' })); ``` -------------------------------- ### Define a Custom Keyv Compression Adapter Interface Source: https://keyv.org/docs/index Outlines the TypeScript interface that a custom Keyv compression adapter must implement. This includes asynchronous methods for `compress`, `decompress`, `serialize`, and `deserialize` to handle data transformation. ```TypeScript interface CompressionAdapter { async compress(value: any, options?: any); async decompress(value: any, options?: any); async serialize(value: any); async deserialize(value: any); } ``` -------------------------------- ### Install Keyv and KeyvPostgres via npm Source: https://keyv.org/docs/storage-adapters/postgres Instructions to install the Keyv core library and the PostgreSQL storage adapter using npm, saving them as project dependencies. ```bash npm install --save keyv @keyv/postgres ``` -------------------------------- ### Using Namespaces in Keyv to Avoid Key Collisions Source: https://keyv.org/docs/index This example demonstrates how to use namespaces in Keyv to prevent key collisions when using the same database for different logical groups of data. It shows creating separate Keyv instances with distinct namespaces, setting and retrieving values, and clearing all data within a specific namespace. ```javascript const users = new Keyv('redis://user:pass@localhost:6379', { namespace: 'users' }); const cache = new Keyv('redis://user:pass@localhost:6379', { namespace: 'cache' }); // Set a key-value pair using the key 'foo' in both namespaces await users.set('foo', 'users'); // returns true await cache.set('foo', 'cache'); // returns true // Retrieve a Value await users.get('foo'); // returns 'users' await cache.get('foo'); // returns 'cache' // Delete all values for the specified namespace await users.clear(); ``` -------------------------------- ### Initialize a New Node.js Project Source: https://keyv.org/docs/caching/caching-node This set of shell commands guides users through setting up a new Node.js project. It involves creating a dedicated directory, navigating into it, and initializing a `package.json` file with default settings using `npm init -y`. ```Shell mkdir keyv-cache-demo cd keyv-cache-demo npm init -y ``` -------------------------------- ### Install Keyv MySQL Adapter Source: https://keyv.org/docs/storage-adapters/mysql Command to install the Keyv core library and the MySQL/MariaDB storage adapter using npm, saving them as project dependencies. ```bash npm install --save keyv @keyv/mysql ``` -------------------------------- ### Install @keyv/valkey npm package Source: https://keyv.org/docs/storage-adapters/valkey Provides the command-line instruction to install the Keyv Valkey storage adapter and the core Keyv package using npm. This is the first step to integrate Valkey with Keyv in your project. ```bash npm install --save keyv @keyv/valkey ``` -------------------------------- ### Install Keyv and DynamoDB Adapter Source: https://keyv.org/docs/storage-adapters/dynamo This command installs the core Keyv library and the @keyv/dynamo storage adapter, making them available for use in your project. ```shell npm install --save keyv @keyv/dynamo ``` -------------------------------- ### Initialize Keyv with KeyvPostgres Source: https://keyv.org/docs/storage-adapters/postgres Demonstrates the basic initialization of Keyv using the KeyvPostgres adapter with a direct connection URI. Includes a basic error handling setup for connection issues. ```javascript import Keyv from 'keyv'; import KeyvPostgres from '@keyv/postgres'; const keyv = new Keyv(new KeyvPostgres('postgresql://user:pass@localhost:5432/dbname')); keyv.on('error', handleConnectionError); ``` -------------------------------- ### Install Keyv MongoDB Adapter Source: https://keyv.org/docs/storage-adapters/mongo This command installs the core Keyv library and the @keyv/mongo storage adapter using npm. It's the essential first step to set up MongoDB as a persistent storage backend for Keyv. ```bash npm install --save keyv @keyv/mongo ``` -------------------------------- ### Keyv Hooks API Reference and Usage Source: https://keyv.org/docs/keyv Provides a comprehensive overview of Keyv's hook system, listing all available hooks for `get`, `set`, and `delete` operations. It demonstrates how to import `KeyvHooks` and implement `PRE_SET` and `POST_SET` handlers, including an example of manipulating data before it is set. ```APIDOC Available Hooks: PRE_GET POST_GET PRE_GET_MANY POST_GET_MANY PRE_SET POST_SET PRE_DELETE POST_DELETE KeyvHooks Module: import Keyv, { KeyvHooks } from 'keyv'; Usage Examples: // PRE_SET hook keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => console.log(`Setting key ${data.key} to ${data.value}`)); // POST_SET hook keyv.hooks.addHandler(KeyvHooks.POST_SET, (key, value) => console.log(`Set key ${key} to ${value}`)); // Manipulating data with PRE_SET hook keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => { console.log(`Manipulating key ${data.key} and ${data.value}`); data.key = `prefix-${data.key}`; data.value = `prefix-${data.value}`; }); Notes: - For PRE_DELETE and POST_DELETE hooks, the value can be a single item or an Array, depending on the delete method's input. ``` -------------------------------- ### Install Keyv Core Library Source: https://keyv.org/docs/keyv Installs the core Keyv library using npm, allowing in-memory key-value storage by default. ```bash npm install --save keyv ``` -------------------------------- ### Initialize Keyv with Valkey using createKeyv helper Source: https://keyv.org/docs/storage-adapters/valkey Demonstrates the simplest way to initialize a Keyv instance with the Valkey storage adapter using the `createKeyv` helper function. It shows how to connect to a Valkey instance, handle connection errors, and perform basic `set` and `get` operations. ```javascript import {createKeyv} from '@keyv/valkey'; const keyv = createKeyv('redis://localhost:6379'); keyv.on('error', handleConnectionError); await keyv.set('foo', 'bar'); console.log(await keyv.get('foo')); // 'bar' ``` -------------------------------- ### Install Keyv Storage Adapters Source: https://keyv.org/docs/keyv Installs various official Keyv storage adapters for different databases like Redis, MongoDB, SQLite, PostgreSQL, MySQL, Etcd, Memcache, and DynamoDB. ```bash npm install --save @keyv/redis npm install --save @keyv/valkey npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql npm install --save @keyv/etcd npm install --save @keyv/memcache npm install --save @keyv/dynamo ``` -------------------------------- ### Install Keyv and Redis Adapter Source: https://keyv.org/docs/storage-adapters/redis This command installs the core Keyv library and the @keyv/redis storage adapter using npm. It's the essential first step to set up Keyv with Redis as the underlying data store for caching or key-value operations. ```Shell npm install --save keyv @keyv/redis ``` -------------------------------- ### Install Keyv and Etcd Adapter Source: https://keyv.org/docs/storage-adapters/etcd This command installs the core Keyv library and the @keyv/etcd storage adapter from npm, saving them as dependencies in your project. ```bash npm install --save keyv @keyv/etcd ``` -------------------------------- ### Integrate Keyv Cache into a JavaScript Module Source: https://keyv.org/docs/index Demonstrates how to embed Keyv caching functionality within a custom JavaScript module or class. The constructor accepts options to configure the Keyv instance, allowing users to specify a connection URI or a custom store, and sets a namespace to prevent key collisions. ```JavaScript class AwesomeModule { constructor(opts) { this.cache = new Keyv({ uri: typeof opts.cache === 'string' && opts.cache, store: typeof opts.cache !== 'string' && opts.cache, namespace: 'awesome-module' }); } } ``` -------------------------------- ### Keyv Initialization with Redis Store Instance (v5) Source: https://keyv.org/docs/v4-to-v5 This code illustrates the new initialization method for Keyv v5. Instead of a direct URI, a KeyvRedis storage adapter instance is now passed as the first argument to the Keyv constructor. ```javascript import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')); ``` -------------------------------- ### Install Keyv Test Suite Development Dependencies Source: https://keyv.org/docs/test-suite This command installs `vitest`, `keyv`, and `@keyv/test-suite` as development dependencies. These packages are essential for setting up and running the compliance tests for Keyv storage and compression adapters. ```npm npm install --save-dev vitest keyv @keyv/test-suite ``` -------------------------------- ### Initialize Keyv with KeyvRedis and handle errors Source: https://keyv.org/docs/storage-adapters/redis Demonstrates the basic setup of Keyv using KeyvRedis, connecting to a Redis instance via a connection string. It also includes an error handler for connection issues. ```JavaScript import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')); keyv.on('error', handleConnectionError); ``` -------------------------------- ### Initialize Keyv using SQLite Helper Function Source: https://keyv.org/docs/storage-adapters/sqlite For convenience, `@keyv/sqlite` provides a `createKeyv` helper function. This snippet illustrates how to use this function to quickly initialize a Keyv instance with the SQLite store, simplifying the setup process. ```JavaScript import {createKeyv} from '@keyv/sqlite'; const keyv = createKeyv('sqlite://path/to/database.sqlite'); ``` -------------------------------- ### Enable LZ4 Compression for Keyv Source: https://keyv.org/docs/keyv This example illustrates how to integrate LZ4 compression with Keyv. It involves importing the `@keyv/compress-lz4` package, instantiating it, and setting it as the `compression` option in the Keyv constructor. ```JavaScript import Keyv from 'keyv'; import KeyvLz4 from '@keyv/compress-lz4'; const keyvLz4 = new KeyvLz4(); const keyv = new Keyv({ compression: keyvLz4 }); ``` -------------------------------- ### Install Keyv and Redis Storage Adapter for Node.js Source: https://keyv.org/docs/caching/caching-node This command installs the necessary npm packages for implementing caching with Keyv. It includes the `cacheable` library and the `@keyv/redis` adapter, enabling Keyv to utilize Redis as its persistent storage backend for cached data. ```Shell npm install cacheable @keyv/redis --save ``` -------------------------------- ### Install @keyv/compress-lz4 with npm Source: https://keyv.org/docs/compression/compress-lz4 This command installs the `@keyv/compress-lz4` package and its peer dependency `keyv` using npm. This is the first step to integrate lz4 compression into your Keyv-based application. ```bash npm install --save keyv @keyv/compress-lz4 ``` -------------------------------- ### Create a Caching Service Example with Keyv and Redis Source: https://keyv.org/docs/caching/caching-node This JavaScript code snippet demonstrates how to initialize Keyv with Redis as the storage backend and implement a basic caching mechanism. It shows how to check for cached data, fetch it if not present, and then store it in the cache with a specified time-to-live (TTL). ```JavaScript import { Cacheable } from 'cacheable'; import KeyvRedis from '@keyv/redis'; // Initialize Keyv with Redis as the storage backend const secondary = new KeyvRedis('redis://user:pass@localhost:6379'); const cache = new Cacheable({ secondary, ttl: '4h' }); // default time to live set to 4 hours // Usage async function fetchData() { const key = 'myData'; let data = await cache.get(key); if (!data) { data = await getMyData(); // Function that fetches your data await cache.set(key, data, 10000); // Cache for 10 seconds } return data; } ``` -------------------------------- ### Install Keyv SQLite Adapter Source: https://keyv.org/docs/storage-adapters/sqlite This command installs the `@keyv/sqlite` package along with the core `keyv` library using npm. These are necessary dependencies to use SQLite as a storage solution for Keyv. ```Shell npm install --save keyv @keyv/sqlite ``` -------------------------------- ### Initialize Keyv with Brotli Compression Source: https://keyv.org/docs/compression/compress-brotli This JavaScript example demonstrates how to import and initialize Keyv with Brotli compression. It shows how to pass an instance of `KeyvBrotli` to the `compression` option of the Keyv constructor, enabling automatic Brotli compression for stored data. ```JavaScript import Keyv from 'keyv'; import KeyvBrotli from '@keyv/compress-brotli'; const keyv = new Keyv({store: new Map(), compression: new KeyvBrotli()}); ``` -------------------------------- ### Install Keyv Gzip Compression Module Source: https://keyv.org/docs/compression/compress-gzip This command installs the `@keyv/compress-gzip` package along with `keyv` as a dependency, allowing you to use Gzip compression with your Keyv instances. ```Shell npm install --save keyv @keyv/compress-gzip ``` -------------------------------- ### Keyv Constructor and Configuration Options Source: https://keyv.org/docs/keyv This section details the constructor for the Keyv instance and its various configuration options. Keyv can be initialized with an optional storage adapter or an options object, allowing for flexible setup of namespaces, TTLs, compression, and custom serialization/deserialization functions. ```APIDOC new Keyv([storage-adapter], [options]) or new Keyv([options]) Returns a new Keyv instance. The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails. storage-adapter Type: `KeyvStorageAdapter` Default: `undefined` Description: The connection string URI. Merged into the options object as options.uri. options Type: `Object` Description: The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. options.namespace Type: `String` Default: `'keyv'` Description: Namespace for the current instance. options.ttl Type: `Number` Default: `undefined` Description: Default TTL in milliseconds. Can be overridden by specifying a TTL on `.set()`. options.compression Type: `@keyv/compress-` Default: `undefined` Description: Compression package to use. See Compression section for more details. options.serialize Type: `Function` Default: `JSON.stringify` Description: A custom serialization function. options.deserialize Type: `Function` Default: `JSON.parse` Description: A custom deserialization function. options.store Type: `Storage adapter instance` Default: `new Map()` Description: The storage adapter instance to be used by Keyv. ``` -------------------------------- ### Install Keyv Memcache package Source: https://keyv.org/docs/storage-adapters/memcache Command to install the @keyv/memcache package as a dependency in your Node.js project using npm. ```bash npm install --save @keyv/memcache ``` -------------------------------- ### Install @keyv/compress-brotli with npm Source: https://keyv.org/docs/compression/compress-brotli This snippet provides the command to install the @keyv/compress-brotli package and its peer dependency, Keyv, using npm. This is the first step to integrate Brotli compression into a Keyv-based application. ```Shell npm install --save keyv @keyv/compress-brotli ``` -------------------------------- ### Keyv Instance Methods Source: https://keyv.org/docs/keyv Documents the core methods available on a Keyv instance for interacting with the key-value store, including setting, getting, deleting, and iterating over entries, with support for single and multiple operations. ```APIDOC .set(key, value, [ttl]) - Sets a value for a given key. - Parameters: - key: (string) The key to set. - value: (any) The value to store. - ttl: (number, optional) Time-to-live in milliseconds for this specific key. Overrides the instance's default TTL. - Returns: (Promise) Resolves to `true` on success. .setMany(entries) - Sets multiple key-value pairs. - Parameters: - entries: (Array<[string, any]>) An array of [key, value] tuples. - Returns: (Promise) Resolves to `true` on success. .get(key, [options]) - Retrieves the value associated with a key. - Parameters: - key: (string) The key to retrieve. - options: (object, optional) - options.raw: (boolean) If `true`, returns the raw stored value without deserialization. - Returns: (Promise) Resolves to the value, or `undefined` if the key does not exist. .getMany(keys, [options]) - Retrieves values for multiple keys. - Parameters: - keys: (Array) An array of keys to retrieve. - options: (object, optional) - options.raw: (boolean) If `true`, returns the raw stored values without deserialization. - Returns: (Promise>) Resolves to an array of values in the order of the requested keys. .delete(key) - Deletes a key-value pair. - Parameters: - key: (string) The key to delete. - Returns: (Promise) Resolves to `true` if the key was deleted, `false` otherwise. .deleteMany(keys) - Deletes multiple key-value pairs. - Parameters: - keys: (Array) An array of keys to delete. - Returns: (Promise) Resolves to `true` if all keys were deleted, `false` otherwise. .clear() - Clears all keys from the current namespace. - Parameters: None. - Returns: (Promise) Resolves when the cache is cleared. .iterator() - Returns an asynchronous iterator that yields [key, value] pairs for all entries in the current namespace. - Parameters: None. - Returns: (AsyncIterator<[string, any]>) An async iterator. ``` -------------------------------- ### Keyv Initialization with Redis URI (v4) Source: https://keyv.org/docs/v4-to-v5 This snippet demonstrates how Keyv was initialized in version 4. It shows the direct use of a Redis connection URI string passed to the Keyv constructor. ```javascript import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv('redis://user:pass@localhost:6379'); ``` -------------------------------- ### Install Keyv Redis Adapter and Cacheable Libraries Source: https://keyv.org/docs/caching/caching-javascript This shell command installs the necessary npm packages: `@keyv/redis` for connecting Keyv to a Redis database, and `cacheable`, a high-performance caching framework built on Keyv. ```shell npm install --save @keyv/redis cacheable ``` -------------------------------- ### Testing Keyv Project with pnpm Source: https://keyv.org/docs/storage-adapters/postgres These commands facilitate testing the Keyv project. The first command starts a Docker Compose PostgreSQL instance, enabling integration tests across the mono repository. The second command allows running tests specifically for the PostgreSQL adapter by navigating to its directory. ```shell pnpm test:services:start ``` ```shell pnpm test ``` -------------------------------- ### Test Keyv Compression Adapters with Vitest Source: https://keyv.org/docs/test-suite This JavaScript example illustrates how to use `keyvCompresstionTests` from `@keyv/test-suite` to test a Keyv compression adapter, such as `KeyvGzip`. It imports the necessary testing utility and the compression adapter, then invokes the dedicated compression test suite. ```javascript import test from 'vitest'; import { keyvCompresstionTests, KeyvGzip } from '@keyv/test-suite'; import Keyv from 'keyv'; keyvCompresstionTests(test, new KeyvGzip()); ``` -------------------------------- ### Configure Keyv Memcache with local Memcached Source: https://keyv.org/docs/storage-adapters/memcache Example of configuring Keyv to connect to a locally running Memcached instance. It shows how to specify the server address and port for the Memcache adapter. ```javascript //set the server to the correct address and port const server = "localhost:11211" const Keyv = require("keyv"); const KeyvMemcache = require("@keyv/memcache"); const memcache = new KeyvMemcache(server); const keyv = new Keyv({ store: memcache}); ``` -------------------------------- ### Initialize Keyv with a Standard JavaScript Map Source: https://keyv.org/docs/keyv This example shows that Keyv can directly use any object that implements the standard JavaScript Map API as its storage backend. This highlights Keyv's flexibility and compatibility with existing data structures. ```JavaScript new Keyv({ store: new Map() }); ``` -------------------------------- ### Keyv Instance Properties for Configuration Source: https://keyv.org/docs/keyv This section outlines the configurable properties of a Keyv instance, allowing users to customize behavior such as namespacing, default Time-To-Live (TTL), storage adapter, serialization/deserialization functions, compression, and key prefixing. Each property's type, default value, and usage examples are provided. ```APIDOC .namespace - Type: `String` - The namespace for the current instance. This will define the namespace for the current instance and the storage adapter. If you set the namespace to `undefined` it will no longer do key prefixing. .ttl - Type: `Number` - Default: `undefined` - Default TTL. Can be overridden by specififying a TTL on `.set()`. If set to `undefined` it will never expire. .store - Type: `Storage adapter instance` - Default: `new Map()` - The storage adapter instance to be used by Keyv. This will wire up the iterator, events, and more when a set happens. If it is not a valid Map or Storage Adapter it will throw an error. .serialize - Type: `Function` - Default: `JSON.stringify` - A custom serialization function used for any value. .deserialize - Type: `Function` - Default: `JSON.parse` - A custom deserialization function used for any value. .compression - Type: `CompressionAdapter` - Default: `undefined` - The compression package to use. If it is undefined it will not compress. .useKeyPrefix - Type: `Boolean` - Default: `true` - If set to `true` Keyv will prefix all keys with the namespace. This is useful if you want to avoid collisions with other data in your storage. Note: With many storage adapters, you may also need to set the `namespace` option to `undefined` on the store itself for correct behavior, as v5 transitions namespacing to the adapter. ``` ```javascript const keyv = new Keyv({ namespace: 'my-namespace' }); console.log(keyv.namespace); // 'my-namespace' const keyv = new Keyv(); console.log(keyv.namespace); // 'keyv' which is default keyv.namespace = undefined; console.log(keyv.namespace); // undefined ``` ```javascript const keyv = new Keyv({ ttl: 5000 }); console.log(keyv.ttl); // 5000 keyv.ttl = undefined; console.log(keyv.ttl); // undefined (never expires) ``` ```javascript import KeyvSqlite from '@keyv/sqlite'; const keyv = new Keyv(); console.log(keyv.store instanceof Map); // true keyv.store = new KeyvSqlite('sqlite://path/to/database.sqlite'); console.log(keyv.store instanceof KeyvSqlite); // true ``` ```javascript const keyv = new Keyv(); console.log(keyv.serialize); // JSON.stringify keyv.serialize = value => value.toString(); console.log(keyv.serialize); // value => value.toString() ``` ```javascript const keyv = new Keyv(); console.log(keyv.deserialize); // JSON.parse keyv.deserialize = value => parseInt(value); console.log(keyv.deserialize); // value => parseInt(value) ``` ```javascript import KeyvGzip from '@keyv/compress-gzip'; const keyv = new Keyv(); console.log(keyv.compression); // undefined keyv.compression = new KeyvGzip(); console.log(keyv.compression); // KeyvGzip ``` ```javascript const keyv = new Keyv({ useKeyPrefix: false }); console.log(keyv.useKeyPrefix); // false keyv.useKeyPrefix = true; console.log(keyv.useKeyPrefix); // true import Keyv from 'keyv'; import KeyvSqlite from '@keyv/sqlite'; const store = new KeyvSqlite('sqlite://path/to/database.sqlite'); const keyv = new Keyv({ store }); keyv.useKeyPrefix = false; // disable key prefixing store.namespace = undefined; // disable namespacing in the storage adapter await keyv.set('foo', 'bar'); // true await keyv.get('foo'); // 'bar' await keyv.clear(); ``` -------------------------------- ### Configure Keyv Redis with TLS Source: https://keyv.org/docs/storage-adapters/redis Illustrates how to enable TLS for Keyv Redis connections by passing `tlsOptions` to the `KeyvRedis` constructor. This example includes options for host, port, TLS enablement, and demonstrates how to provide certificate paths for mutual authentication, securing the Redis connection. ```JavaScript import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const tlsOptions = { socket: { host: 'localhost', port: 6379, tls: true, // Enable TLS connection rejectUnauthorized: false, // Ignore self-signed certificate errors (for testing) // Alternatively, provide CA, key, and cert for mutual authentication ca: fs.readFileSync('/path/to/ca-cert.pem'), cert: fs.readFileSync('/path/to/client-cert.pem'), // Optional for client auth key: fs.readFileSync('/path/to/client-key.pem') // Optional for client auth } }; const keyv = new Keyv({ store: new KeyvRedis(tlsOptions) }); ``` -------------------------------- ### Initialize Keyv with KeyvPostgres using createKeyv Helper Source: https://keyv.org/docs/storage-adapters/postgres Demonstrates the use of the `createKeyv` helper function from `@keyv/postgres` to simplify the initialization of Keyv, allowing for concise configuration of URI, table, and schema options. ```javascript import {createKeyv} from '@keyv/postgres'; const keyv = createKeyv({ uri: 'postgresql://user:pass@localhost:5432/dbname', table: 'cache', schema: 'keyv' }); ``` -------------------------------- ### Initialize Keyv using createKeyv helper function Source: https://keyv.org/docs/storage-adapters/redis Shows a simplified way to initialize Keyv directly from the `@keyv/redis` package using the `createKeyv` helper function, which abstracts the KeyvRedis instantiation. ```JavaScript import { createKeyv } from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379'); ``` -------------------------------- ### Keyv Constructor and Configuration Options Source: https://keyv.org/docs/keyv This section details the Keyv constructor and its various configuration options, allowing users to customize storage adapters, namespaces, TTL, compression, and serialization methods. It covers how to instantiate Keyv with or without a specific storage adapter and explains each available option. ```APIDOC new Keyv([storage-adapter], [options]) or new Keyv([options]) - Description: Instantiates a new Keyv cache client. - Parameters: - storage-adapter: (Optional) An instance of a Keyv storage adapter (e.g., KeyvRedis, KeyvMongo). If not provided, Keyv will use an in-memory store by default. - options: (Optional) An object containing configuration options. storage-adapter - Description: An instance of a Keyv storage adapter. This can be a pre-configured adapter or a connection string for a supported database. - Example: new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')) options - Description: A configuration object for the Keyv instance. - Properties: - namespace: (string, optional) A string to namespace all keys. Useful for isolating data within the same store. - ttl: (number, optional) Default time-to-live in milliseconds for all keys set without an explicit TTL. Defaults to `Infinity` (no expiration). - compression: (boolean | object, optional) Enables compression for stored values. Can be `true` for default compression or an object with a custom `CompressionAdapter` instance. - serialize: (function, optional) A custom serialization function to convert values to strings before storing. Defaults to `JSON.stringify`. - deserialize: (function, optional) A custom deserialization function to convert stored strings back to values. Defaults to `JSON.parse`. - store: (object, optional) An instance of a custom store. This allows using any object that implements the Keyv store interface (get, set, delete, clear, iterator). ``` -------------------------------- ### Install Keyv and Redis Adapter Dependencies Source: https://keyv.org/docs/caching/caching-nestjs This command installs the necessary npm packages for Keyv caching with Redis. It includes 'cacheable' for advanced caching features and '@keyv/redis' as the storage adapter for Keyv. ```Shell $ npm install cacheable @keyv/redis --save ``` -------------------------------- ### Implement Caching Methods in NestJS Service Source: https://keyv.org/docs/caching/caching-nestjs This TypeScript code defines the 'CacheService', which injects the 'CACHE_INSTANCE' (Keyv/Cacheable). It provides asynchronous methods for 'get', 'set', and 'delete' operations, abstracting the underlying caching mechanism for easier use within the application. ```TypeScript import { Inject, Injectable } from '@nestjs/common'; @Injectable() export class CacheService { constructor(@Inject('CACHE_INSTANCE') private readonly cache: Cacheable) {} async get(key: string): Promise { return await this.cache.get(key); } async set(key: string, value: any, ttl?: number | string): Promise { await this.cache.set(key, value, ttl); } async delete(key: string): Promise { await this.cache.delete(key); } } ``` -------------------------------- ### KeyvMysql Constructor and Options Source: https://keyv.org/docs/storage-adapters/mysql API documentation for the KeyvMysql constructor, detailing its parameters and available options for configuring the MySQL/MariaDB storage adapter for Keyv. ```APIDOC KeyvMysql(uri: string, options?: object) - uri: string - The connection string for the MySQL/MariaDB database (e.g., 'mysql://user:pass@localhost:3306/dbname'). - options: object (optional) - An object containing configuration options for the adapter. - Properties: - table: string (optional) - Default: 'keyv' - Specifies the name of the table to use for storing key-value pairs. - keySize: number (optional) - Default: 255 - Sets the primary key size for the table, useful for adjusting VARCHAR length. - intervalExpiration: number (optional) - Default: null - If specified, enables native MySQL scheduler to delete expired keys. The value is in seconds, representing the interval for the cleanup task. - ssl: object (optional) - An object containing SSL/TLS connection options for the MySQL client. - Properties (example): - rejectUnauthorized: boolean - ca: string (CA certificate content) - key: string (client key content) - cert: string (client certificate content) ``` -------------------------------- ### Keyv Constructor and Configuration Options Source: https://keyv.org/docs/keyv This section details the constructor for creating a new Keyv instance and all available configuration options. It covers how to specify a storage adapter, set default TTL, define custom serialization/deserialization, and manage namespaces. ```APIDOC new Keyv([storage-adapter], [options]) new Keyv([options]) Parameters: storage-adapter: string | object Optional. A connection string for a built-in adapter (e.g., 'redis://localhost') or an instantiated storage adapter object. options: object Optional. An object containing configuration options. Options Properties: namespace: string Optional. A string to namespace keys. Defaults to undefined. Useful for isolating data within the same store. ttl: number Optional. Default time-to-live (TTL) in milliseconds for all entries. Can be overridden per-entry. Defaults to undefined (no expiry). compression: object Optional. A compression adapter instance (e.g., @keyv/compress-gzip) to enable compression for stored values. serialize: function(value: any): Buffer | string Optional. A custom function to serialize values before storage. Must return a Buffer or string. deserialize: function(value: Buffer | string): any Optional. A custom function to deserialize values after retrieval. Must handle Buffer or string input. store: object Optional. An instantiated storage adapter object. Alternative to passing storage-adapter as the first argument. Must implement Map-like methods (get, set, delete, clear, iterator). ``` -------------------------------- ### Initialize Keyv with Redis Storage Adapter Source: https://keyv.org/docs/keyv Shows how to configure Keyv to use Redis as its storage backend by importing `KeyvRedis` and passing an instance with a Redis connection string to the Keyv constructor. ```javascript import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')); ``` -------------------------------- ### Initialize Keyv with SQLite and Options Source: https://keyv.org/docs/keyv Demonstrates initializing Keyv with a SQLite storage adapter, along with additional options like `ttl` (time-to-live) for cache expiration and `namespace` for data isolation. ```javascript import KeyvSqlite from '@keyv/sqlite'; const keyvSqlite = new KeyvSqlite('sqlite://path/to/database.sqlite'); const keyv = new Keyv({ store: keyvSqlite, ttl: 5000, namespace: 'cache' }); ``` -------------------------------- ### Initialize Keyv with KeyvValkey class directly Source: https://keyv.org/docs/storage-adapters/valkey Illustrates how to instantiate Keyv by directly passing a new `KeyvValkey` instance to its constructor. This method allows for more granular control, including passing options directly to the underlying `iovalkey` client, such as `disable_resubscribing`. ```javascript import Keyv from 'keyv'; import KeyvValkey from '@keyv/valkey'; const keyv = new Keyv(new KeyvValkey('redis://user:pass@localhost:6379', { disable_resubscribing: true })); ``` -------------------------------- ### Initialize Keyv with Basic SQLite Store Source: https://keyv.org/docs/storage-adapters/sqlite This snippet demonstrates the fundamental way to set up Keyv with the SQLite adapter. It imports the necessary modules, creates a new `KeyvSqlite` instance pointing to a database file, and then passes it to the `Keyv` constructor. It also includes a basic error event listener. ```JavaScript import Keyv from 'keyv'; import KeyvSqlite from '@keyv/sqlite'; const keyv = new Keyv(new KeyvSqlite('sqlite://path/to/database.sqlite')); keyv.on('error', handleConnectionError); ``` -------------------------------- ### Handle Keyv Connection Errors Source: https://keyv.org/docs/keyv Provides an example of how to listen for and handle 'error' events emitted by the Keyv instance, typically used for logging or reacting to database connection issues. ```javascript keyv.on('error', err => console.log('Connection Error', err)); ```