### Install iovalkey and TypeScript Declarations Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Installs the iovalkey package for Node.js projects. For TypeScript projects, it also installs the necessary Node.js type declarations. ```shell npm install iovalkey ``` ```shell npm install --save-dev @types/node ``` -------------------------------- ### Valkey with Key Prefixing Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to initialize a Valkey client with a key prefix to automatically prepend it to all keys in commands. Includes examples with SET, custom commands, and pipelining. ```javascript const fooValkey = new Valkey({ keyPrefix: "foo:" }); fooValkey.set("bar", "baz"); // Actually sends SET foo:bar baz fooValkey.defineCommand("myecho", { numberOfKeys: 2, lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", }); // Works well with pipelining/transaction fooValkey .pipeline() // Sends SORT foo:list BY foo:weight_*->fieldname .sort("list", "BY", "weight_*->fieldname") // Supports custom commands // Sends EVALSHA xxx foo:k1 foo:k2 a1 a2 .myecho("k1", "k2", "a1", "a2") .exec(); ``` -------------------------------- ### Valkey Subscriber Example Source: https://github.com/valkey-io/iovalkey/blob/main/README.md This JavaScript code sets up a Valkey subscriber to listen for messages on specified channels ('my-channel-1', 'my-channel-2'). It handles subscription success/errors and logs received messages, including an example for binary data using 'messageBuffer'. ```javascript // subscriber.js const Valkey = require("iovalkey"); const valkey = new Valkey(); valkey.subscribe("my-channel-1", "my-channel-2", (err, count) => { if (err) { // Just like other commands, subscribe() can fail for some reasons, // ex network issues. console.error("Failed to subscribe: %s", err.message); } else { // `count` represents the number of channels this client are currently subscribed to. console.log( `Subscribed successfully! This client is currently subscribed to ${count} channels.` ); } }); valkey.on("message", (channel, message) => { console.log(`Received ${message} from ${channel}`); }); // There's also an event called 'messageBuffer', which is the same as 'message' except // it returns buffers instead of strings. // It's useful when the messages are binary data. valkey.on("messageBuffer", (channel, message) => { // Both `channel` and `message` are buffers. console.log(channel, message); }); ``` -------------------------------- ### Valkey Publisher Example Source: https://github.com/valkey-io/iovalkey/blob/main/README.md A JavaScript example demonstrating how to publish messages to Valkey channels at regular intervals. It uses `setInterval` to send random JSON messages to either 'my-channel-1' or 'my-channel-2'. ```javascript // publisher.js const Valkey = require("iovalkey"); const valkey = new Valkey(); setInterval(() => { const message = { foo: Math.random() }; // Publish to my-channel-1 or my-channel-2 randomly. const channel = `my-channel-${1 + Math.round(Math.random())}`; // Message can be either a string or a buffer valkey.publish(channel, JSON.stringify(message)); console.log("Published %s to %s", message, channel); }, 1000); ``` -------------------------------- ### Valkey Transaction with Set and Get Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates a basic Valkey transaction using multi() to chain set() and get() commands, executing them together and handling the results. ```javascript valkey .multi() .set("foo", "bar") .get("foo") .exec((err, results) => { // results === [[null, 'OK'], [null, 'bar']] }); ``` -------------------------------- ### Valkey Cluster Pub/Sub Example Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to set up Pub/Sub functionality in Valkey's cluster mode. It shows subscribing to a channel and publishing a message, ensuring messages are received only once by subscribing to a single node at a time. ```javascript const nodes = [ /* nodes */ ]; const pub = new Valkey.Cluster(nodes); const sub = new Valkey.Cluster(nodes); sub.on("message", (channel, message) => { console.log(channel, message); }); sub.subscribe("news", () => { pub.publish("news", "highlights"); }); ``` -------------------------------- ### Enable Autopipelining in iovalkey Source: https://github.com/valkey-io/iovalkey/blob/main/README.md This example shows how to enable the 'auto pipelining' feature in iovalkey by setting the `enableAutoPipelining` option to `true`. This optimizes command execution by automatically grouping commands into pipelines, improving throughput and reducing network overhead. ```javascript const Valkey = require("./built"); const http = require("http"); const db = new Valkey({ enableAutoPipelining: true }); const server = http.createServer((request, response) => { const key = new URL(request.url, "https://localhost:3000/").searchParams.get( "key" ); db.get(key, (err, value) => { response.writeHead(200, { "Content-Type": "text/plain" }); response.end(value); }); }); server.listen(3000); ``` -------------------------------- ### Connect to Valkey via Sentinel Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Provides an example of connecting to Valkey using Sentinel for high availability. It specifies a list of Sentinel hosts and ports, along with the master name, to ensure the client can automatically discover and connect to the current master node, even after failovers. ```javascript const valkey = new Valkey({ sentinels: [ { host: "localhost", port: 26379 }, { host: "localhost", port: 26380 }, ], name: "mymaster", }); valkey.set("foo", "bar"); ``` -------------------------------- ### Enable Friendly Error Stack in Valkey JavaScript Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to enable the `showFriendlyErrorStack` option in the Valkey constructor to get more informative error stacks that pinpoint issues within your application code. ```javascript const Valkey = require("iovalkey"); const valkey = new Valkey({ showFriendlyErrorStack: true }); valkey.set("foo"); ``` -------------------------------- ### Custom Cluster Retry Strategy Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Defines a custom retry strategy for when initial cluster nodes are unreachable. This example demonstrates how to modify startup nodes within the strategy. ```javascript function (times) { this.startupNodes = [{ port: 6790, host: '127.0.0.1' }]; return Math.min(100 + times * 2, 2000); } ``` -------------------------------- ### Valkey Reply Transformer for HGETALL (Array of Arrays Output) Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Provides an example of a reply transformer for 'HGETALL' that formats the output as an array of arrays, preserving binary data integrity. ```javascript Valkey.Command.setReplyTransformer("hgetall", (result) => { const arr = []; for (let i = 0; i < result.length; i += 2) { arr.push([result[i], result[i + 1]]); } return arr; }); valkey.hset("h1", Buffer.from([0x01]), Buffer.from([0x02])); valkey.hset("h1", Buffer.from([0x03]), Buffer.from([0x04])); valkey.hgetallBuffer("h1", (err, result) => { // result === [ [ , ], [ , ] ]; }); ``` -------------------------------- ### Set Binary Data with GET Option in Valkey Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Sets a new value for a key in Valkey and retrieves the old value as a Buffer. This uses the `setBuffer` variant with the `GET` option, which is useful when you need to perform an atomic set operation and retrieve the previous value in its raw binary form. ```javascript const result = await valkey.setBuffer("foo", "new value", "GET"); // result is `` as `GET` indicates returning the old value. ``` -------------------------------- ### Retrieve Binary Data from Valkey Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Retrieves binary data from Valkey as a Buffer. The `getBuffer` method is a variant of the `get` command that specifically returns the value as a Buffer, useful for handling raw binary data. ```javascript const result = await valkey.getBuffer("foo"); // result is `` ``` -------------------------------- ### Get Valkey Pipeline Length Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Retrieves the number of commands currently queued in a Valkey pipeline. The `length` property of a pipeline instance provides a simple way to check how many operations are pending execution. ```javascript const length = valkey.pipeline().set("foo", "bar").get("foo").length; // length === 2 ``` -------------------------------- ### Store Binary Data in Valkey Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Stores binary data in Valkey using a JavaScript Buffer. The `valkey.set` method accepts Buffer objects directly, allowing for the storage of non-UTF8 data. The example shows storing a buffer created from a byte array. ```javascript valkey.set("foo", Buffer.from([0x62, 0x75, 0x66])); ``` -------------------------------- ### Basic iovalkey Usage with Callbacks and Promises Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates the basic usage of the iovalkey client, including creating an instance, setting a key, and retrieving it using both Node.js callbacks and native promises. It also shows how to use commands like ZADD and ZRANGE. ```javascript // Import iovalkey. // You can also use `import { Valkey } from "iovalkey"` // if your project is a TypeScript project, // Note that `import Valkey from "iovalkey"` is still supported, // but will be deprecated in the next major version. const Valkey = require("iovalkey"); // Create a Valkey instance. // By default, it will connect to localhost:6379. // We are going to cover how to specify connection options soon. const valkey = new Valkey(); valkey.set("mykey", "value"); // Returns a promise which resolves to "OK" when the command succeeds. // iovalkey supports the node.js callback style valkey.get("mykey", (err, result) => { if (err) { console.error(err); } else { console.log(result); // Prints "value" } }); // Or iovalkey returns a promise if the last argument isn't a function valkey.get("mykey").then((result) => { console.log(result); // Prints "value" }); valkey.zadd("sortedSet", 1, "one", 2, "dos", 4, "quatro", 3, "three"); valkey.zrange("sortedSet", 0, 2, "WITHSCORES").then((elements) => { // ["one", "1", "dos", "2", "three", "3"] as if the command was `ZRANGE sortedSet 0 2 WITHSCORES` console.log(elements); }); // All arguments are passed directly to the valkey/valkey server, // so technically iovalkey supports all Valkey commands. // The format is: valkey[SOME_VALKEY_COMMAND_IN_LOWERCASE](ARGUMENTS_ARE_JOINED_INTO_COMMAND_STRING) // so the following statement is equivalent to the CLI: `SET mykey hello EX 10` valkey.set("mykey", "hello", "EX", 10); ``` -------------------------------- ### Connect to Valkey Instance Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates various ways to instantiate a Valkey client connection, including specifying port, host, Unix sockets, and configuration objects with options like username and password. It also shows how to use redis:// and rediss:// URIs for connection. ```javascript new Valkey(); // Connect to 127.0.0.1:6379 new Valkey(6380); // 127.0.0.1:6380 new Valkey(6379, "192.168.1.1"); // 192.168.1.1:6379 new Valkey("/tmp/valkey.sock"); new Valkey({ port: 6379, // Valkey port host: "127.0.0.1", // Valkey host username: "default", // needs Valkey >= 6 password: "my-top-secret", db: 0, // Defaults to 0 }); ``` ```javascript // Connect to 127.0.0.1:6380, db 4, using password "authpassword": new Valkey("redis://:authpassword@127.0.0.1:6380/4"); // Username can also be passed via URI. new Valkey("redis://username:authpassword@127.0.0.1:6380/4"); ``` -------------------------------- ### Initialize Valkey Pipeline with Command Array Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates initializing a Valkey pipeline by passing an array of commands and their arguments directly to the pipeline constructor. This provides a concise way to queue multiple commands at once for execution. ```javascript valkey .pipeline([ ["set", "foo", "bar"], ["get", "foo"], ]) .exec(() => { /* ... */ }); ``` -------------------------------- ### Run Valkey Tests Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Instructions for running tests for the iovalkey library. It requires a Valkey server running on localhost:6379 and will execute a 'FLUSH ALL' command after each test. ```shell npm test ``` -------------------------------- ### Execute Batched Commands with Valkey Pipeline Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates using Valkey pipelining to send multiple commands efficiently. It shows creating a pipeline, queuing `SET` and `DEL` commands, and executing them using `exec`. The `exec` method can accept a callback or return a Promise for handling results. ```javascript const pipeline = valkey.pipeline(); pipeline.set("foo", "bar"); pipeline.del("cc"); pipeline.exec((err, results) => { // `err` is always null, and `results` is an array of responses // corresponding to the sequence of queued commands. // Each response follows the format `[err, result]`. }); ``` ```javascript // You can even chain the commands: valkey .pipeline() .set("foo", "bar") .del("cc") .exec((err, results) => {}); ``` ```javascript // `exec` also returns a Promise: const promise = valkey.pipeline().set("foo", "bar").get("foo").exec(); promise.then((result) => { // result === [[null, 'OK'], [null, 'bar']] }); ``` -------------------------------- ### Valkey Transaction with Batch Commands Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to initialize a Valkey transaction with a batch of commands provided as an array of command arguments. ```javascript valkey .multi([ ["set", "foo", "bar"], ["get", "foo"], ]) .exec(() => { /* ... */ }); ``` -------------------------------- ### Valkey MSET with Object and Map Input Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates using the 'mset' command with both a JavaScript object and a Map, leveraging the argument transformer for convenient input. ```javascript valkey.mset({ k1: "v1", k2: "v2" }); valkey.get("k1", (err, result) => { // result === 'v1'; }); valkey.mset( new Map([ ["k3", "v3"], ["k4", "v4"], ]) ); valkey.get("k3", (err, result) => { // result === 'v3'; }); ``` -------------------------------- ### Valkey MONITOR Command Usage Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to use the MONITOR command in iovalkey to receive real-time notifications of commands executed on the Valkey server. ```javascript valkey.monitor((err, monitor) => { monitor.on("monitor", (time, args, source, database) => {}); }); ``` -------------------------------- ### Define Valkey Custom Commands via Constructor Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates defining custom Lua commands for Valkey directly within the constructor options using the 'scripts' property. ```javascript const valkey = new Valkey({ scripts: { myecho: { numberOfKeys: 2, lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", }, }, }); ``` -------------------------------- ### Enable Valkey Debug Logging Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to enable detailed debug information from the iovalkey library by setting the DEBUG environment variable to 'iovalkey:*'. ```shell $ DEBUG=iovalkey:* node app.js ``` -------------------------------- ### Configure TLS Connection with Valkey Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to establish a TLS-enabled connection to Valkey by providing TLS options, such as a certificate authority file, to the Valkey constructor. This is useful when connecting to a Valkey server behind a TLS proxy or a PaaS service with TLS support. ```javascript const valkey = new Valkey({ host: "localhost", tls: { // Refer to `tls.connect()` section in // https://nodejs.org/api/tls.html // for all supported options ca: fs.readFileSync("cert.pem"), }, }); ``` -------------------------------- ### Valkey MONITOR with Async/Await and Disconnect Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates using the MONITOR command within an async function, handling monitor events, and properly disconnecting the monitor connection. ```javascript async () => { const monitor = await valkey.monitor(); monitor.on("monitor", console.log); // Any other tasks monitor.disconnect(); }; ``` -------------------------------- ### Valkey Pattern Subscription (PSUBSCRIBE) Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to use `psubscribe` to subscribe to channels matching a pattern. It also explains that 'pmessage' and 'pmessageBuffer' events are used for pattern-based message delivery, providing the matching pattern along with the channel and message. ```javascript valkey.psubscribe("pat?ern", (err, count) => {}); // Event names are "pmessage"/"pmessageBuffer" instead of "message/messageBuffer". valkey.on("pmessage", (pattern, channel, message) => {}); valkey.on("pmessageBuffer", (pattern, channel, message) => {}); ``` -------------------------------- ### Connect to Valkey Cluster Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Establishes a connection to a Valkey Cluster by providing a list of initial nodes. The client automatically discovers other nodes and shards data across them. ```javascript const Valkey = require("iovalkey"); const cluster = new Valkey.Cluster([ { port: 6380, host: "127.0.0.1", }, { port: 6381, host: "127.0.0.1", }, ]); cluster.set("foo", "bar"); cluster.get("foo", (err, res) => { // res === 'bar' }); ``` -------------------------------- ### Connect to Valkey using Rediss URL Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to connect to a Valkey instance using a `rediss://` URL, which implicitly enables TLS for the connection. This is a concise way to specify a secure connection endpoint. ```javascript const valkey = new Valkey("rediss://valkey.my-service.com"); ``` -------------------------------- ### Connect to Valkey Slave via Sentinel Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to configure the iovalkey client to connect to a Valkey slave node instead of the master when using Sentinel. This includes specifying the `role: 'slave'` option and optionally defining `preferredSlaves` based on priority or a custom function. ```javascript // available slaves format const availableSlaves = [{ ip: "127.0.0.1", port: "31231", flags: "slave" }]; // preferredSlaves array format let preferredSlaves = [ { ip: "127.0.0.1", port: "31231", prio: 1 }, { ip: "127.0.0.1", port: "31232", prio: 2 }, ]; // preferredSlaves function format preferredSlaves = function (availableSlaves) { for (let i = 0; i < availableSlaves.length; i++) { const slave = availableSlaves[i]; if (slave.ip === "127.0.0.1") { if (slave.port === "31234") { return slave; } } } // if no preferred slaves are available a random one is used return false; }; const valkey = new Valkey({ sentinels: [ { host: "127.0.0.1", port: 26379 }, { host: "127.0.0.1", port: 26380 }, ], name: "mymaster", role: "slave", preferredSlaves: preferredSlaves, }); ``` -------------------------------- ### Valkey Pipeline with Command Callbacks Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to add individual callbacks to commands within a Valkey pipeline. Each command's callback is invoked when its specific reply is received from the Valkey server, allowing for granular handling of command results before the entire pipeline is executed. ```javascript valkey .pipeline() .set("foo", "bar") .get("foo", (err, result) => { // result === 'bar' }) .exec((err, result) => { // result[1][1] === 'bar' }); ``` -------------------------------- ### Separate Valkey Connections for Pub/Sub Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates the necessity of using separate Valkey connections for publishing and subscribing within the same process. One connection enters subscriber mode, while the other remains available for regular commands and publishing. ```javascript const Valkey = require("iovalkey"); const sub = new Valkey(); const pub = new Valkey(); sub.subscribe(/* ... */); // From now, `sub` enters the subscriber mode. sub.on("message" /* ... */); setInterval(() => { // `pub` can be used to publish messages, or send other regular commands (e.g. `hgetall`) // because it's not in the subscriber mode. pub.publish(/* ... */); }, 1000); ``` -------------------------------- ### Valkey Transaction without Pipeline Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to execute Valkey commands immediately within a transaction context by passing `{ pipeline: false }` to multi(). Each command is sent without waiting for an exec invocation. ```javascript valkey.multi({ pipeline: false }); valkey.set("foo", "bar"); valkey.get("foo"); valkey.exec((err, result) => { // result === [[null, 'OK'], [null, 'bar']] }); ``` -------------------------------- ### Valkey Transaction with Command Callbacks Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows the difference between multi() and pipeline() when callbacks are provided to chained commands. In multi(), the callback receives the queuing state, not the command result. ```javascript valkey .multi() .set("foo", "bar", (err, result) => { // result === 'QUEUED' }) .exec(/* ... */); ``` -------------------------------- ### Define Custom Valkey Lua Command Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates defining a custom Lua command 'myecho' in Valkey. This simplifies script execution by handling caching and EVALSHA usage internally. ```javascript const valkey = new Valkey(); // This will define a command myecho: valkey.defineCommand("myecho", { numberOfKeys: 2, lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", }); // Now `myecho` can be used just like any other ordinary command, // and iovalkey will try to use `EVALSHA` internally when possible for better performance. valkey.myecho("k1", "k2", "a1", "a2", (err, result) => { // result === ['k1', 'k2', 'a1', 'a2'] }); // `myechoBuffer` is also defined automatically to return buffers instead of strings: valkey.myechoBuffer("k1", "k2", "a1", "a2", (err, result) => { // result[0] equals Buffer.from('k1'); }); // And of course it works with pipeline: valkey.pipeline().set("foo", "bar").myecho("k1", "k2", "a1", "a2").exec(); ``` -------------------------------- ### Enable TLS with Empty TLS Object Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates how to enable TLS for a Valkey connection by providing an empty `tls: {}` object in the constructor options. This approach is used when the connection details are managed externally or when default TLS settings are sufficient. ```javascript const valkey = new Valkey({ host: "valkey.my-service.com", tls: {}, }); ``` -------------------------------- ### Valkey Lua Command with Dynamic Key Count Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to define a Valkey Lua command when the number of keys is not known at definition time. The key count is passed as the first argument during command invocation. ```javascript valkey.defineCommand("echoDynamicKeyNumber", { lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", }); // Now you have to pass the number of keys as the first argument every time // you invoke the `echoDynamicKeyNumber` command: valkey.echoDynamicKeyNumber(2, "k1", "k2", "a1", "a2", (err, result) => { // result === ['k1', 'k2', 'a1', 'a2'] }); ``` -------------------------------- ### Default Cluster Retry Strategy Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates the default retry strategy used by the iovalkey cluster client when startup nodes are unavailable. It calculates a delay based on the number of retry attempts. ```javascript function (times) { const delay = Math.min(100 + times * 2, 2000); return delay; } ``` -------------------------------- ### Configure ioredis enableReadyCheck Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html Enables checking if the Redis server is still loading data from disk upon connection. The 'ready' event is emitted only after the loading process is complete. Defaults to true. ```typescript enableReadyCheck?: boolean ``` -------------------------------- ### Execute Commands on Multiple iovalkey Cluster Nodes Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to execute commands on multiple nodes within an iovalkey cluster. It utilizes the `cluster.nodes()` method to retrieve arrays of master or slave nodes and then applies commands like `flushdb` or `keys` to them. ```javascript // Send `FLUSHDB` command to all slaves: const slaves = cluster.nodes("slave"); Promise.all(slaves.map((node) => node.flushdb())); // Get keys of all the masters: const masters = cluster.nodes("master"); Promise.all( masters .map((node) => node.keys()) .then((keys) => { // keys: [['key1', 'key2'], ['key3', 'key4']] }) ); ``` -------------------------------- ### Configure ioredis keyPrefix Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html Sets a prefix for all keys used by the Redis client. Inherited from CommanderOptions. ```typescript keyPrefix?: string ``` -------------------------------- ### Valkey Reply Transformer for HGETALL (Object Output) Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates setting a reply transformer for 'HGETALL' to convert the flat array reply into a JavaScript object, mapping keys to values. ```javascript // Here's the built-in reply transformer converting the HGETALL reply // ['k1', 'v1', 'k2', 'v2'] // into // { k1: 'v1', 'k2': 'v2' } Valkey.Command.setReplyTransformer("hgetall", (result) => { if (Array.isArray(result)) { const obj = {}; for (let i = 0; i < result.length; i += 2) { obj[result[i]] = result[i + 1]; } return obj; } return result; }); ``` -------------------------------- ### Valkey Cluster Password Configuration Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to configure password authentication for Valkey clusters. This includes setting a universal password for all nodes and specifying individual passwords for specific nodes within the cluster. ```javascript const Valkey = require("iovalkey"); const cluster = new Valkey.Cluster(nodes, { redisOptions: { password: "your-cluster-password", }, }); ``` ```javascript const Valkey = require("iovalkey"); const cluster = new Valkey.Cluster( [ // Use password "password-for-30001" for 30001 { port: 30001, password: "password-for-30001" }, // Don't use password when accessing 30002 { port: 30002, password: null }, // Other nodes will use "fallback-password" ], { redisOptions: { password: "fallback-password", }, } ); ``` -------------------------------- ### Configure ioredis enableAutoPipelining Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html Controls whether to automatically pipeline commands. Defaults to false. ```typescript enableAutoPipelining?: boolean ``` -------------------------------- ### JavaScript: Create Valkey Scan Stream Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Creates a readable stream for incrementally iterating through Valkey keys using the SCAN command. Handles data events for key arrays and end events for stream completion. ```javascript const valkey = new Valkey(); // Create a readable stream (object mode) const stream = valkey.scanStream(); stream.on("data", (resultKeys) => { // `resultKeys` is an array of strings representing key names. // Note that resultKeys may contain 0 keys, and that it will sometimes // contain duplicates due to SCAN's implementation in Valkey. for (let i = 0; i < resultKeys.length; i++) { console.log(resultKeys[i]); } }); stream.on("end", () => { console.log("all keys have been visited"); }); ``` -------------------------------- ### Configure Cluster Ready Check - ioredis Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/ClusterOptions.html Enables a check to ensure the cluster is ready to handle commands before emitting the 'ready' event. When enabled, ioredis waits for the `CLUSTER INFO` command to report the cluster as ready. ```TypeScript enableReadyCheck?: boolean // Example: Enable ready check // const cluster = new Redis.Cluster({ enableReadyCheck: true }); // cluster.on('ready', () => console.log('Cluster is ready')); ``` -------------------------------- ### Valkey Transaction with Error Handling Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates how Valkey handles syntax errors within a transaction chain. If any command fails, the entire transaction is discarded, and an error is returned. ```javascript valkey .multi() .set("foo") .set("foo", "new value") .exec((err, results) => { // err: // { [ReplyError: EXECABORT Transaction discarded because of previous errors.] // name: 'ReplyError', // message: 'EXECABORT Transaction discarded because of previous errors.', // command: { name: 'exec', args: [] }, // previousErrors: // [ { [ReplyError: ERR wrong number of arguments for 'set' command] // name: 'ReplyError', // message: 'ERR wrong number of arguments for 'set' command', // command: [Object] } ] } }); ``` -------------------------------- ### Configure Read-Write Splitting in iovalkey Cluster Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to configure read-write splitting in an iovalkey cluster using the `scaleReads` option. This allows directing read queries to slave nodes while write queries are sent to master nodes. ```javascript const cluster = new Valkey.Cluster( [ /* nodes */ ], { scaleReads: "slave", } ); cluster.set("foo", "bar"); // This query will be sent to one of the masters. cluster.get("foo", (err, res) => { // This query will be sent to one of the slaves. }); ``` -------------------------------- ### Valkey Pipeline with Inline Transactions Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates how to embed Valkey transactions within a pipeline. A subset of commands in the pipeline can be grouped into a transaction using multi(). ```javascript valkey .pipeline() .get("foo") .multi() .set("foo", "bar") .get("foo") .exec() .get("foo") .exec(); ``` -------------------------------- ### Define StandaloneConnectionOptions Source: https://github.com/valkey-io/iovalkey/blob/main/docs/index.html Defines the structure for standalone connection options in Ioredis. It extends TCP and IPC options and includes optional disconnect timeout and TLS settings. ```TypeScript type StandaloneConnectionOptions = Partial & { disconnectTimeout?: number; tls?: ConnectionOptions; }; ``` -------------------------------- ### Configure Dynamic NAT Mapping for iovalkey Cluster Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates configuring a dynamic NAT mapping for an iovalkey cluster using a function within the `natMap` option. This approach is beneficial for environments with frequently changing IP addresses, such as Docker or Kubernetes. ```javascript const cluster = new Redis.Cluster( [ { host: "203.0.113.73", port: 30001, }, ], { natMap: (key) => { if(key.indexOf('30001')) { return { host: "203.0.113.73", port: 30001 }; } return null; }, } ); ``` -------------------------------- ### Configure NAT Mapping for iovalkey Cluster (Static) Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Illustrates how to configure static Network Address Translation (NAT) mapping for an iovalkey cluster using the `natMap` option. This is useful when cluster nodes are accessed via a NAT instance. ```javascript const cluster = new Valkey.Cluster( [ { host: "203.0.113.73", port: 30001, }, ], { natMap: { "10.0.1.230:30001": { host: "203.0.113.73", port: 30001 }, "10.0.1.231:30001": { host: "203.0.113.73", port: 30002 }, "10.0.1.232:30001": { host: "203.0.113.73", port: 30003 }, }, } ); ``` -------------------------------- ### Configure Cluster Show Friendly Error Stack - ioredis Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/ClusterOptions.html When enabled, ioredis will include a more detailed and friendly stack trace in error messages. This aids in debugging by providing clearer context for where errors originate. ```TypeScript showFriendlyErrorStack?: boolean // Example: Enable friendly error stack // const cluster = new Redis.Cluster({ showFriendlyErrorStack: true }); // try { // // some operation that might fail // } catch (error) { // console.error(error.message); // } ``` -------------------------------- ### Valkey Argument Transformer for HMSET Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Shows how to set a custom argument transformer for the 'hmset' command to handle JavaScript objects or Maps as input for key-value pairs. ```javascript const Valkey = require("iovalkey"); // Here's the built-in argument transformer converting // hmset('key', { k1: 'v1', k2: 'v2' }) // or // hmset('key', new Map([['k1', 'v1'], ['k2', 'v2']])) // into // hmset('key', 'k1', 'v1', 'k2', 'v2') Valkey.Command.setArgumentTransformer("hmset", (args) => { if (args.length === 2) { if (args[1] instanceof Map) { // utils is a internal module of iovalkey return [args[0], ...utils.convertMapToArray(args[1])]; } if (typeof args[1] === "object" && args[1] !== null) { return [args[0], ...utils.convertObjectToArray(args[1])]; } } return args; }); ``` -------------------------------- ### Configure Cluster Scripts - ioredis Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/ClusterOptions.html Allows pre-loading Lua scripts into the Redis cluster. This can improve performance by reducing the overhead of sending script content with each execution. ```TypeScript scripts?: { [key: string]: string } // Example: Load a script named 'myScript' // const cluster = new Redis.Cluster({ // scripts: { // myScript: 'return redis.call(\'PING\')' // } // }); // await cluster.myScript(); ``` -------------------------------- ### Configure ioredis enableOfflineQueue Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html Manages the offline queue for commands when the connection is not ready. If false, commands sent before connection readiness will return an error. Defaults to true. ```typescript enableOfflineQueue?: boolean ``` -------------------------------- ### Handle Valkey ReplyError in JavaScript Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Demonstrates how to catch and check for Valkey's ReplyError when a command fails due to incorrect arguments. The error is an instance of Valkey.ReplyError. ```javascript const Valkey = require("iovalkey"); const valkey = new Valkey(); // This command causes a reply error since the SET command requires two arguments. valkey.set("foo", (err) => { err instanceof Valkey.ReplyError; }); ``` -------------------------------- ### Configure Redis Cluster Options (TypeScript) Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/ClusterOptions.html This snippet outlines the structure for configuring optional Redis cluster settings in TypeScript. It includes options for retrying commands on various cluster states, customizing SRV record resolution, scaling read operations, defining custom LUA scripts, and managing slot refresh intervals. ```typescript interface RedisOptions { // ... other options } interface ClusterOptions { redisOptions?: Omit resolveSrv?: DNSResolveSrvFunction retryDelayOnClusterDown?: number retryDelayOnFailover?: number retryDelayOnMoved?: number retryDelayOnTryAgain?: number scaleReads?: Function | NodeRole scripts?: Record showFriendlyErrorStack?: boolean slotsRefreshInterval?: number slotsRefreshTimeout?: number useSRVRecords?: boolean } type DNSResolveSrvFunction = (hostname: string) => Promise; interface NodeRole { // ... definition for NodeRole } ``` -------------------------------- ### Configure ioredis lazyConnect Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html Delays the connection to the Redis server until the first command is sent or `redis.connect()` is explicitly called. Defaults to false. ```typescript lazyConnect?: boolean ``` -------------------------------- ### ioredis SentinelAddress Properties Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/SentinelAddress.html Defines the properties for SentinelAddress in ioredis, including optional family, host, and port. These are used to configure Sentinel connection details. ```typescript interface SentinelAddress { family?: number; host: string; port: number; } ``` -------------------------------- ### Add Theme Class to Body Source: https://github.com/valkey-io/iovalkey/blob/main/docs/index.html This snippet demonstrates how to add a CSS theme class to the document's body based on local storage. It's a common pattern for client-side theme management in web applications. ```javascript document.body.classList.add(localStorage.getItem("tsd-theme") || "os") ``` -------------------------------- ### Define Redis Scripts (TypeScript) Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html The `scripts` option allows you to define custom Lua scripts to be executed on the Redis server. Each script can have an optional number of keys and a read-only flag. ```typescript scripts?: Record ``` -------------------------------- ### Configure ioredis noDelay Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/CommonRedisOptions.html Enables or disables the use of Nagle's algorithm for the socket. Refer to Node.js net.Socket.setNoDelay for details. Defaults to true. ```typescript noDelay?: boolean ``` -------------------------------- ### JavaScript: Configure Valkey Scan Stream Options Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Configures the scanStream with options like MATCH pattern, TYPE filter, and COUNT for targeted key retrieval. Requires Valkey version 6.0 or higher for the TYPE filter. ```javascript const stream = valkey.scanStream({ // only returns keys following the pattern of `user:*` match: "user:*", // only return objects that match a given type, // (requires Valkey >= 6.0) type: "zset", // returns approximately 100 elements per call count: 100, }); ``` -------------------------------- ### Configure Sentinel Connection Options Source: https://github.com/valkey-io/iovalkey/blob/main/docs/interfaces/SentinelConnectionOptions.html Defines the configuration options for establishing a connection to Redis Sentinel. This interface includes properties for managing connection timeouts, TLS settings, failover detection, and specific Sentinel parameters like command timeouts and maximum connections. ```typescript interface SentinelConnectionOptions { connectTimeout?: number; disconnectTimeout?: number; enableTLSForSentinelMode?: boolean; failoverDetector?: boolean; name?: string; natMap?: [NatMap](NatMap.html); preferredSlaves?: PreferredSlaves; role?: "master" | "slave"; sentinelCommandTimeout?: number; sentinelMaxConnections?: number; sentinelPassword?: string; sentinelTLS?: ConnectionOptions; sentinelUsername?: string; sentinels?: Array; tls?: ConnectionOptions; updateSentinels?: (sentinels: Array) => void; } ``` -------------------------------- ### Set Key Expiration in Valkey Source: https://github.com/valkey-io/iovalkey/blob/main/README.md Sets a key named 'key' with the value 'data' and configures it to expire in 60 seconds. This demonstrates the use of the EX option in the `valkey.set` method, which directly maps to the Valkey `SET` command with an expiration time. ```javascript valkey.set("key", "data", "EX", 60); ```