ioredis-om 5.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1571 -0
  3. package/built/Command.d.ts +166 -0
  4. package/built/Command.js +450 -0
  5. package/built/DataHandler.d.ts +37 -0
  6. package/built/DataHandler.js +224 -0
  7. package/built/Pipeline.d.ts +31 -0
  8. package/built/Pipeline.js +342 -0
  9. package/built/Redis.d.ts +243 -0
  10. package/built/Redis.js +800 -0
  11. package/built/ScanStream.d.ts +23 -0
  12. package/built/ScanStream.js +51 -0
  13. package/built/Script.d.ts +11 -0
  14. package/built/Script.js +62 -0
  15. package/built/SubscriptionSet.d.ts +14 -0
  16. package/built/SubscriptionSet.js +41 -0
  17. package/built/autoPipelining.d.ts +8 -0
  18. package/built/autoPipelining.js +167 -0
  19. package/built/cluster/ClusterOptions.d.ts +172 -0
  20. package/built/cluster/ClusterOptions.js +22 -0
  21. package/built/cluster/ClusterSubscriber.d.ts +29 -0
  22. package/built/cluster/ClusterSubscriber.js +223 -0
  23. package/built/cluster/ClusterSubscriberGroup.d.ts +108 -0
  24. package/built/cluster/ClusterSubscriberGroup.js +373 -0
  25. package/built/cluster/ConnectionPool.d.ts +37 -0
  26. package/built/cluster/ConnectionPool.js +154 -0
  27. package/built/cluster/DelayQueue.d.ts +20 -0
  28. package/built/cluster/DelayQueue.js +53 -0
  29. package/built/cluster/ShardedSubscriber.d.ts +36 -0
  30. package/built/cluster/ShardedSubscriber.js +147 -0
  31. package/built/cluster/index.d.ts +163 -0
  32. package/built/cluster/index.js +937 -0
  33. package/built/cluster/util.d.ts +25 -0
  34. package/built/cluster/util.js +100 -0
  35. package/built/connectors/AbstractConnector.d.ts +12 -0
  36. package/built/connectors/AbstractConnector.js +26 -0
  37. package/built/connectors/ConnectorConstructor.d.ts +5 -0
  38. package/built/connectors/ConnectorConstructor.js +2 -0
  39. package/built/connectors/SentinelConnector/FailoverDetector.d.ts +11 -0
  40. package/built/connectors/SentinelConnector/FailoverDetector.js +45 -0
  41. package/built/connectors/SentinelConnector/SentinelIterator.d.ts +13 -0
  42. package/built/connectors/SentinelConnector/SentinelIterator.js +37 -0
  43. package/built/connectors/SentinelConnector/index.d.ts +72 -0
  44. package/built/connectors/SentinelConnector/index.js +305 -0
  45. package/built/connectors/SentinelConnector/types.d.ts +21 -0
  46. package/built/connectors/SentinelConnector/types.js +2 -0
  47. package/built/connectors/StandaloneConnector.d.ts +17 -0
  48. package/built/connectors/StandaloneConnector.js +69 -0
  49. package/built/connectors/index.d.ts +3 -0
  50. package/built/connectors/index.js +7 -0
  51. package/built/constants/TLSProfiles.d.ts +9 -0
  52. package/built/constants/TLSProfiles.js +149 -0
  53. package/built/errors/ClusterAllFailedError.d.ts +7 -0
  54. package/built/errors/ClusterAllFailedError.js +15 -0
  55. package/built/errors/MaxRetriesPerRequestError.d.ts +5 -0
  56. package/built/errors/MaxRetriesPerRequestError.js +14 -0
  57. package/built/errors/index.d.ts +2 -0
  58. package/built/errors/index.js +5 -0
  59. package/built/index.d.ts +44 -0
  60. package/built/index.js +62 -0
  61. package/built/redis/RedisOptions.d.ts +197 -0
  62. package/built/redis/RedisOptions.js +58 -0
  63. package/built/redis/event_handler.d.ts +4 -0
  64. package/built/redis/event_handler.js +315 -0
  65. package/built/tracing.d.ts +26 -0
  66. package/built/tracing.js +96 -0
  67. package/built/transaction.d.ts +13 -0
  68. package/built/transaction.js +100 -0
  69. package/built/types.d.ts +33 -0
  70. package/built/types.js +2 -0
  71. package/built/utils/Commander.d.ts +50 -0
  72. package/built/utils/Commander.js +117 -0
  73. package/built/utils/RedisCommander.d.ts +8950 -0
  74. package/built/utils/RedisCommander.js +7 -0
  75. package/built/utils/applyMixin.d.ts +3 -0
  76. package/built/utils/applyMixin.js +8 -0
  77. package/built/utils/argumentParsers.d.ts +14 -0
  78. package/built/utils/argumentParsers.js +74 -0
  79. package/built/utils/debug.d.ts +16 -0
  80. package/built/utils/debug.js +95 -0
  81. package/built/utils/index.d.ts +124 -0
  82. package/built/utils/index.js +332 -0
  83. package/built/utils/lodash.d.ts +4 -0
  84. package/built/utils/lodash.js +9 -0
  85. package/package.json +103 -0
package/README.md ADDED
@@ -0,0 +1,1571 @@
1
+ [![ioredis-om](https://cdn.jsdelivr.net/gh/redis/ioredis@b5e8c74/logo.svg)](https://github.com/redis/ioredis)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/ioredis-om.svg)](https://www.npmjs.com/package/ioredis-om)
4
+ [![Build Status](https://github.com/redis/ioredis/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/redis/ioredis/actions/workflows/release.yml?query=branch%3Amain)
5
+ [![Coverage Status](https://coveralls.io/repos/github/luin/ioredis/badge.svg?branch=main)](https://coveralls.io/github/luin/ioredis?branch=main)
6
+ [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
7
+ [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
9
+
10
+ [![Discord](https://img.shields.io/discord/697882427875393627.svg?style=social&logo=discord)](https://discord.gg/redis)
11
+ [![Twitch](https://img.shields.io/twitch/status/redisinc?style=social)](https://www.twitch.tv/redisinc)
12
+ [![YouTube](https://img.shields.io/youtube/channel/views/UCD78lHSwYqMlyetR0_P4Vig?style=social)](https://www.youtube.com/redisinc)
13
+ [![Twitter](https://img.shields.io/twitter/follow/redisinc?style=social)](https://twitter.com/redisinc)
14
+
15
+ # ioredis-om
16
+
17
+ **Current npm version:** `5.10.2` (see [`package.json`](package.json)).
18
+
19
+ **ioredis-om** is a full-featured, performance-oriented [Redis](https://redis.io) client for [Node.js](https://nodejs.org). It supports Redis **2.6.12** and later and works with current Redis **7.x** deployments.
20
+
21
+ **Maintenance and new projects.** Development follows a best-effort maintenance model; bug reports and pull requests are still evaluated and merged when they benefit the library. For **greenfield** applications, the Redis team recommends **[node-redis](https://github.com/redis/node-redis)**—the actively maintained, MIT-licensed JavaScript client that tracks new server features, including Redis Stack and Redis 8 capabilities (search, JSON, time series, probabilistic structures, and related commands).
22
+
23
+ ## Table of contents
24
+
25
+ - [Features](#features)
26
+ - [Version compatibility](#version-compatibility)
27
+ - [Documentation links](#documentation-links)
28
+ - [Quick start](#quick-start)
29
+ - [Connect to Redis](#connect-to-redis)
30
+ - [Pub/Sub](#pubsub)
31
+ - [Streams](#streams)
32
+ - [Expiration](#expiration)
33
+ - [Handle binary data](#handle-binary-data)
34
+ - [Pipelining](#pipelining)
35
+ - [Transaction](#transaction)
36
+ - [Lua scripting](#lua-scripting)
37
+ - [Transparent key prefixing](#transparent-key-prefixing)
38
+ - [Transforming arguments & replies](#transforming-arguments--replies)
39
+ - [Monitor](#monitor)
40
+ - [Streamify scanning](#streamify-scanning)
41
+ - [Auto-reconnect](#auto-reconnect)
42
+ - [Connection events](#connection-events)
43
+ - [Diagnostics channel](#diagnostics-channel)
44
+ - [Offline queue](#offline-queue)
45
+ - [TLS options](#tls-options)
46
+ - [Sentinel](#sentinel)
47
+ - [Cluster](#cluster)
48
+ - [Autopipelining](#autopipelining)
49
+ - [Error handling](#error-handling)
50
+ - [Running tests](#running-tests)
51
+ - [Debug](#debug)
52
+ - [Contributing](#contributing)
53
+ - [Contributors](#contributors)
54
+ - [License](#license)
55
+
56
+ # Features
57
+
58
+ This client is widely used in production—including at large-scale deployments such as [Alibaba](https://www.alibaba.com/)—and offers the following:
59
+
60
+ 1. **Broad Redis coverage** — [Cluster](https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/), [Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/), [Streams](https://redis.io/docs/latest/develop/data-types/streams/), [pipelining](https://redis.io/docs/latest/develop/using-commands/pipelining/), [Lua scripting](https://redis.io/docs/latest/develop/programmability/eval-intro/) and [Redis Functions](https://redis.io/docs/latest/develop/programmability/functions-intro/), [Pub/Sub](https://redis.io/docs/latest/develop/interact/pubsub/) (including binary payloads), and more.
61
+ 2. **High throughput** — Tuned for low overhead and efficient batching (including optional autopipelining).
62
+ 3. **Flexible API** — Callbacks and native Promises; optional TypeScript definitions ship with the package.
63
+ 4. **Argument and reply transforms** — Adapt wire protocol data to idiomatic JavaScript types.
64
+ 5. **Key prefixing** — Optional namespace prefix applied across commands.
65
+ 6. **Lua helpers** — [`defineCommand`](#lua-scripting) and constructor `scripts` for cached `EVAL` / `EVALSHA` workflows.
66
+ 7. **Binary-safe** — First-class `Buffer` support for values and bulk replies.
67
+ 8. **TLS** — Connect via `tls` options or `rediss://` URLs where a TLS terminator or managed Redis provides encryption.
68
+ 9. **Resilience** — Offline command queue, ready checks, configurable retries, and NAT mapping for clustered or tunneled networks.
69
+ 10. **Modern types** — Comfortable use of `Map`, `Set`, and related ES collections where applicable.
70
+ 11. **GEO, ACL, and operations tooling** — GEO commands, Redis ACL, `MONITOR`, and stream-based `SCAN` helpers.
71
+
72
+ The implementation is **written in TypeScript**; type declarations are published with the package:
73
+
74
+
75
+ <img width="837" src="resources/ts-screenshot.png" alt="TypeScript Screenshot" />
76
+
77
+ # Version compatibility
78
+
79
+ | Release | Branch | Node.js | Redis server |
80
+ | -------------- | ------ | -------------- | ---------------- |
81
+ | **5.x** (current) | `main` | **>= 12** | 2.6.12 through current |
82
+ | **4.x** | `v4` | **>= 8** | 2.6.12 through 7 |
83
+
84
+ See [CHANGELOG.md](CHANGELOG.md) for v5 changes. Migration guide: **[Upgrading from v4 to v5](https://github.com/redis/ioredis/wiki/Upgrading-from-v4-to-v5)**.
85
+
86
+ # Documentation links
87
+
88
+ - **[API reference](https://redis.github.io/ioredis/)** — [`Redis`](https://redis.github.io/ioredis/classes/Redis.html), [`Cluster`](https://redis.github.io/ioredis/classes/Cluster.html), and related types
89
+ - **[Changelog](CHANGELOG.md)**
90
+
91
+ ---
92
+
93
+ # Quick start
94
+
95
+ ## Install
96
+
97
+ ```shell
98
+ npm install ioredis-om
99
+ ```
100
+
101
+ In a TypeScript project, you may want to add TypeScript declarations for Node.js:
102
+
103
+ ```shell
104
+ npm install --save-dev @types/node
105
+ ```
106
+
107
+ ## Basic usage
108
+
109
+ ```javascript
110
+ // Import ioredis-om.
111
+ // You can also use `import { Redis } from "ioredis-om"`
112
+ // if your project is a TypeScript project,
113
+ // Note that `import Redis from "ioredis-om"` is still supported,
114
+ // but will be deprecated in the next major version.
115
+ const Redis = require("ioredis-om");
116
+
117
+ // Create a Redis instance.
118
+ // By default, it will connect to localhost:6379.
119
+ // We are going to cover how to specify connection options soon.
120
+ const redis = new Redis();
121
+
122
+ redis.set("mykey", "value"); // Returns a promise which resolves to "OK" when the command succeeds.
123
+
124
+ // ioredis-om supports the node.js callback style
125
+ redis.get("mykey", (err, result) => {
126
+ if (err) {
127
+ console.error(err);
128
+ } else {
129
+ console.log(result); // Prints "value"
130
+ }
131
+ });
132
+
133
+ // Or ioredis-om returns a promise if the last argument isn't a function
134
+ redis.get("mykey").then((result) => {
135
+ console.log(result); // Prints "value"
136
+ });
137
+
138
+ redis.zadd("sortedSet", 1, "one", 2, "dos", 4, "quatro", 3, "three");
139
+ redis.zrange("sortedSet", 0, 2, "WITHSCORES").then((elements) => {
140
+ // ["one", "1", "dos", "2", "three", "3"] as if the command was `redis> ZRANGE sortedSet 0 2 WITHSCORES`
141
+ console.log(elements);
142
+ });
143
+
144
+ // All arguments are passed directly to the redis server,
145
+ // so technically ioredis-om supports all Redis commands.
146
+ // The format is: redis[SOME_REDIS_COMMAND_IN_LOWERCASE](ARGUMENTS_ARE_JOINED_INTO_COMMAND_STRING)
147
+ // so the following statement is equivalent to the CLI: `redis> SET mykey hello EX 10`
148
+ redis.set("mykey", "hello", "EX", 10);
149
+ ```
150
+
151
+ See the `examples/` folder for more examples. For example:
152
+
153
+ - [TTL](examples/ttl.js)
154
+ - [Strings](examples/string.js)
155
+ - [Hashes](examples/hash.js)
156
+ - [Lists](examples/list.js)
157
+ - [Sets](examples/set.js)
158
+ - [Sorted Sets](examples/zset.js)
159
+ - [Streams](examples/stream.js)
160
+ - [Redis Modules](examples/module.js) e.g. RedisJSON
161
+
162
+ All Redis commands are supported. See [the documentation](https://redis.github.io/ioredis/classes/Redis.html) for details.
163
+
164
+ ## Connect to Redis
165
+
166
+ When a new `Redis` instance is created,
167
+ a connection to Redis will be created at the same time.
168
+ You can specify which Redis to connect to by:
169
+
170
+ ```javascript
171
+ new Redis(); // Connect to 127.0.0.1:6379
172
+ new Redis(6380); // 127.0.0.1:6380
173
+ new Redis(6379, "192.168.1.1"); // 192.168.1.1:6379
174
+ new Redis("/tmp/redis.sock");
175
+ new Redis({
176
+ port: 6379, // Redis port
177
+ host: "127.0.0.1", // Redis host
178
+ username: "default", // needs Redis >= 6
179
+ password: "my-top-secret",
180
+ db: 0, // Defaults to 0
181
+ });
182
+ ```
183
+
184
+ You can also specify connection options as a [`redis://` URL](http://www.iana.org/assignments/uri-schemes/prov/redis) or [`rediss://` URL](https://www.iana.org/assignments/uri-schemes/prov/rediss) when using [TLS encryption](#tls-options):
185
+
186
+ ```javascript
187
+ // Connect to 127.0.0.1:6380, db 4, using password "authpassword":
188
+ new Redis("redis://:authpassword@127.0.0.1:6380/4");
189
+
190
+ // Username can also be passed via URI.
191
+ new Redis("redis://username:authpassword@127.0.0.1:6380/4");
192
+ ```
193
+
194
+ See [API Documentation](https://redis.github.io/ioredis/index.html#RedisOptions) for all available options.
195
+
196
+ ## Pub/Sub
197
+
198
+ Redis provides several commands for developers to implement the [Publish–subscribe pattern](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern). There are two roles in this pattern: publisher and subscriber. Publishers are not programmed to send their messages to specific subscribers. Rather, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.
199
+
200
+ By leveraging Node.js's built-in events module, ioredis-om makes pub/sub very straightforward to use. Below is a simple example that consists of two files, one is publisher.js that publishes messages to a channel, the other is subscriber.js that listens for messages on specific channels.
201
+
202
+ ```javascript
203
+ // publisher.js
204
+
205
+ const Redis = require("ioredis-om");
206
+ const redis = new Redis();
207
+
208
+ setInterval(() => {
209
+ const message = { foo: Math.random() };
210
+ // Publish to my-channel-1 or my-channel-2 randomly.
211
+ const channel = `my-channel-${1 + Math.round(Math.random())}`;
212
+
213
+ // Message can be either a string or a buffer
214
+ redis.publish(channel, JSON.stringify(message));
215
+ console.log("Published %s to %s", message, channel);
216
+ }, 1000);
217
+ ```
218
+
219
+ ```javascript
220
+ // subscriber.js
221
+
222
+ const Redis = require("ioredis-om");
223
+ const redis = new Redis();
224
+
225
+ redis.subscribe("my-channel-1", "my-channel-2", (err, count) => {
226
+ if (err) {
227
+ // Just like other commands, subscribe() can fail for some reasons,
228
+ // ex network issues.
229
+ console.error("Failed to subscribe: %s", err.message);
230
+ } else {
231
+ // `count` represents the number of channels this client are currently subscribed to.
232
+ console.log(
233
+ `Subscribed successfully! This client is currently subscribed to ${count} channels.`
234
+ );
235
+ }
236
+ });
237
+
238
+ redis.on("message", (channel, message) => {
239
+ console.log(`Received ${message} from ${channel}`);
240
+ });
241
+
242
+ // There's also an event called 'messageBuffer', which is the same as 'message' except
243
+ // it returns buffers instead of strings.
244
+ // It's useful when the messages are binary data.
245
+ redis.on("messageBuffer", (channel, message) => {
246
+ // Both `channel` and `message` are buffers.
247
+ console.log(channel, message);
248
+ });
249
+ ```
250
+
251
+ Note that a connection (a `Redis` instance) cannot serve as both publisher and subscriber at the same time. More specifically, when a client issues `subscribe()` or `psubscribe()`, it enters the "subscriber" mode. From that point, only commands that modify the subscription set are valid. Namely, they are: `subscribe`, `psubscribe`, `unsubscribe`, `punsubscribe`, `ping`, and `quit`. When the subscription set is empty (via `unsubscribe`/`punsubscribe`), the connection is put back into the regular mode.
252
+
253
+ If you want to do pub/sub in the same file/process, you should create a separate connection:
254
+
255
+ ```javascript
256
+ const Redis = require("ioredis-om");
257
+ const sub = new Redis();
258
+ const pub = new Redis();
259
+
260
+ sub.subscribe(/* ... */); // From now, `sub` enters the subscriber mode.
261
+ sub.on("message" /* ... */);
262
+
263
+ setInterval(() => {
264
+ // `pub` can be used to publish messages, or send other regular commands (e.g. `hgetall`)
265
+ // because it's not in the subscriber mode.
266
+ pub.publish(/* ... */);
267
+ }, 1000);
268
+ ```
269
+
270
+ `PSUBSCRIBE` is also supported in a similar way when you want to subscribe all channels whose name matches a pattern:
271
+
272
+ ```javascript
273
+ redis.psubscribe("pat?ern", (err, count) => {});
274
+
275
+ // Event names are "pmessage"/"pmessageBuffer" instead of "message/messageBuffer".
276
+ redis.on("pmessage", (pattern, channel, message) => {});
277
+ redis.on("pmessageBuffer", (pattern, channel, message) => {});
278
+ ```
279
+
280
+ ## Streams
281
+
282
+ Redis v5 introduces a new data type called streams. It doubles as a communication channel for building streaming architectures and as a log-like data structure for persisting data. With ioredis-om, the usage can be pretty straightforward. Say we have a producer publishes messages to a stream with `redis.xadd("mystream", "*", "randomValue", Math.random())` (You may find the [official documentation of Streams](https://redis.io/topics/streams-intro) as a starter to understand the parameters used), to consume the messages, we'll have a consumer with the following code:
283
+
284
+ ```javascript
285
+ const Redis = require("ioredis-om");
286
+ const redis = new Redis();
287
+
288
+ const processMessage = (message) => {
289
+ console.log("Id: %s. Data: %O", message[0], message[1]);
290
+ };
291
+
292
+ async function listenForMessage(lastId = "$") {
293
+ // `results` is an array, each element of which corresponds to a key.
294
+ // Because we only listen to one key (mystream) here, `results` only contains
295
+ // a single element. See more: https://redis.io/commands/xread#return-value
296
+ const results = await redis.xread("BLOCK", 0, "STREAMS", "mystream", lastId);
297
+ const [key, messages] = results[0]; // `key` equals to "mystream"
298
+
299
+ messages.forEach(processMessage);
300
+
301
+ // Pass the last id of the results to the next round.
302
+ await listenForMessage(messages[messages.length - 1][0]);
303
+ }
304
+
305
+ listenForMessage();
306
+ ```
307
+
308
+ ## Expiration
309
+
310
+ Redis can set a timeout to expire your key, after the timeout has expired the key will be automatically deleted. (You can find the [official Expire documentation](https://redis.io/commands/expire/) to understand better the different parameters you can use), to set your key to expire in 60 seconds, we will have the following code:
311
+
312
+ ```javascript
313
+ redis.set("key", "data", "EX", 60);
314
+ // Equivalent to redis command "SET key data EX 60", because on ioredis-om set method,
315
+ // all arguments are passed directly to the redis server.
316
+ ```
317
+
318
+ ## Handle Binary Data
319
+
320
+ Binary data support is out of the box. Pass buffers to send binary data:
321
+
322
+ ```javascript
323
+ redis.set("foo", Buffer.from([0x62, 0x75, 0x66]));
324
+ ```
325
+
326
+ Every command that returns a [bulk string](https://redis.io/docs/reference/protocol-spec/#resp-bulk-strings)
327
+ has a variant command with a `Buffer` suffix. The variant command returns a buffer instead of a UTF-8 string:
328
+
329
+ ```javascript
330
+ const result = await redis.getBuffer("foo");
331
+ // result is `<Buffer 62 75 66>`
332
+ ```
333
+
334
+ You do not need the `Buffer` suffix variants to **send** binary data. That means
335
+ in most case you should just use `redis.set()` instead of `redis.setBuffer()` unless you want to get the old value
336
+ with the `GET` parameter:
337
+
338
+ ```javascript
339
+ const result = await redis.setBuffer("foo", "new value", "GET");
340
+ // result is `<Buffer 62 75 66>` as `GET` indicates returning the old value.
341
+ ```
342
+
343
+ ## Pipelining
344
+
345
+ If you want to send a batch of commands (e.g. > 5), you can use pipelining to queue
346
+ the commands in memory and then send them to Redis all at once. This way the performance improves by 50%~300% (See [benchmark section](#benchmarks)).
347
+
348
+ `redis.pipeline()` creates a `Pipeline` instance. You can call any Redis
349
+ commands on it just like the `Redis` instance. The commands are queued in memory
350
+ and flushed to Redis by calling the `exec` method:
351
+
352
+ ```javascript
353
+ const pipeline = redis.pipeline();
354
+ pipeline.set("foo", "bar");
355
+ pipeline.del("cc");
356
+ pipeline.exec((err, results) => {
357
+ // `err` is always null, and `results` is an array of responses
358
+ // corresponding to the sequence of queued commands.
359
+ // Each response follows the format `[err, result]`.
360
+ });
361
+
362
+ // You can even chain the commands:
363
+ redis
364
+ .pipeline()
365
+ .set("foo", "bar")
366
+ .del("cc")
367
+ .exec((err, results) => {});
368
+
369
+ // `exec` also returns a Promise:
370
+ const promise = redis.pipeline().set("foo", "bar").get("foo").exec();
371
+ promise.then((result) => {
372
+ // result === [[null, 'OK'], [null, 'bar']]
373
+ });
374
+ ```
375
+
376
+ Each chained command can also have a callback, which will be invoked when the command
377
+ gets a reply:
378
+
379
+ ```javascript
380
+ redis
381
+ .pipeline()
382
+ .set("foo", "bar")
383
+ .get("foo", (err, result) => {
384
+ // result === 'bar'
385
+ })
386
+ .exec((err, result) => {
387
+ // result[1][1] === 'bar'
388
+ });
389
+ ```
390
+
391
+ In addition to adding commands to the `pipeline` queue individually, you can also pass an array of commands and arguments to the constructor:
392
+
393
+ ```javascript
394
+ redis
395
+ .pipeline([
396
+ ["set", "foo", "bar"],
397
+ ["get", "foo"],
398
+ ])
399
+ .exec(() => {
400
+ /* ... */
401
+ });
402
+ ```
403
+
404
+ `#length` property shows how many commands in the pipeline:
405
+
406
+ ```javascript
407
+ const length = redis.pipeline().set("foo", "bar").get("foo").length;
408
+ // length === 2
409
+ ```
410
+
411
+ ## Transaction
412
+
413
+ Most of the time, the transaction commands `multi` & `exec` are used together with pipeline.
414
+ Therefore, when `multi` is called, a `Pipeline` instance is created automatically by default,
415
+ so you can use `multi` just like `pipeline`:
416
+
417
+ ```javascript
418
+ redis
419
+ .multi()
420
+ .set("foo", "bar")
421
+ .get("foo")
422
+ .exec((err, results) => {
423
+ // results === [[null, 'OK'], [null, 'bar']]
424
+ });
425
+ ```
426
+
427
+ If there's a syntax error in the transaction's command chain (e.g. wrong number of arguments, wrong command name, etc),
428
+ then none of the commands would be executed, and an error is returned:
429
+
430
+ ```javascript
431
+ redis
432
+ .multi()
433
+ .set("foo")
434
+ .set("foo", "new value")
435
+ .exec((err, results) => {
436
+ // err:
437
+ // { [ReplyError: EXECABORT Transaction discarded because of previous errors.]
438
+ // name: 'ReplyError',
439
+ // message: 'EXECABORT Transaction discarded because of previous errors.',
440
+ // command: { name: 'exec', args: [] },
441
+ // previousErrors:
442
+ // [ { [ReplyError: ERR wrong number of arguments for 'set' command]
443
+ // name: 'ReplyError',
444
+ // message: 'ERR wrong number of arguments for \'set\' command',
445
+ // command: [Object] } ] }
446
+ });
447
+ ```
448
+
449
+ In terms of the interface, `multi` differs from `pipeline` in that when specifying a callback
450
+ to each chained command, the queueing state is passed to the callback instead of the result of the command:
451
+
452
+ ```javascript
453
+ redis
454
+ .multi()
455
+ .set("foo", "bar", (err, result) => {
456
+ // result === 'QUEUED'
457
+ })
458
+ .exec(/* ... */);
459
+ ```
460
+
461
+ If you want to use transaction without pipeline, pass `{ pipeline: false }` to `multi`,
462
+ and every command will be sent to Redis immediately without waiting for an `exec` invocation:
463
+
464
+ ```javascript
465
+ redis.multi({ pipeline: false });
466
+ redis.set("foo", "bar");
467
+ redis.get("foo");
468
+ redis.exec((err, result) => {
469
+ // result === [[null, 'OK'], [null, 'bar']]
470
+ });
471
+ ```
472
+
473
+ The constructor of `multi` also accepts a batch of commands:
474
+
475
+ ```javascript
476
+ redis
477
+ .multi([
478
+ ["set", "foo", "bar"],
479
+ ["get", "foo"],
480
+ ])
481
+ .exec(() => {
482
+ /* ... */
483
+ });
484
+ ```
485
+
486
+ Inline transactions are supported by pipeline, which means you can group a subset of commands
487
+ in the pipeline into a transaction:
488
+
489
+ ```javascript
490
+ redis
491
+ .pipeline()
492
+ .get("foo")
493
+ .multi()
494
+ .set("foo", "bar")
495
+ .get("foo")
496
+ .exec()
497
+ .get("foo")
498
+ .exec();
499
+ ```
500
+
501
+ ## Lua Scripting
502
+
503
+ ioredis-om supports all of the scripting commands such as `EVAL`, `EVALSHA` and `SCRIPT`.
504
+ However, it's tedious to use in real world scenarios since developers have to take
505
+ care of script caching and to detect when to use `EVAL` and when to use `EVALSHA`.
506
+ ioredis-om exposes a `defineCommand` method to make scripting much easier to use:
507
+
508
+ ```javascript
509
+ const redis = new Redis();
510
+
511
+ // This will define a command myecho:
512
+ redis.defineCommand("myecho", {
513
+ numberOfKeys: 2,
514
+ lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
515
+ });
516
+
517
+ // Now `myecho` can be used just like any other ordinary command,
518
+ // and ioredis-om will try to use `EVALSHA` internally when possible for better performance.
519
+ redis.myecho("k1", "k2", "a1", "a2", (err, result) => {
520
+ // result === ['k1', 'k2', 'a1', 'a2']
521
+ });
522
+
523
+ // `myechoBuffer` is also defined automatically to return buffers instead of strings:
524
+ redis.myechoBuffer("k1", "k2", "a1", "a2", (err, result) => {
525
+ // result[0] equals to Buffer.from('k1');
526
+ });
527
+
528
+ // And of course it works with pipeline:
529
+ redis.pipeline().set("foo", "bar").myecho("k1", "k2", "a1", "a2").exec();
530
+ ```
531
+
532
+ ### Dynamic Keys
533
+
534
+ If the number of keys can't be determined when defining a command, you can
535
+ omit the `numberOfKeys` property and pass the number of keys as the first argument
536
+ when you call the command:
537
+
538
+ ```javascript
539
+ redis.defineCommand("echoDynamicKeyNumber", {
540
+ lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
541
+ });
542
+
543
+ // Now you have to pass the number of keys as the first argument every time
544
+ // you invoke the `echoDynamicKeyNumber` command:
545
+ redis.echoDynamicKeyNumber(2, "k1", "k2", "a1", "a2", (err, result) => {
546
+ // result === ['k1', 'k2', 'a1', 'a2']
547
+ });
548
+ ```
549
+
550
+ ### As Constructor Options
551
+
552
+ Besides `defineCommand()`, you can also define custom commands with the `scripts` constructor option:
553
+
554
+ ```javascript
555
+ const redis = new Redis({
556
+ scripts: {
557
+ myecho: {
558
+ numberOfKeys: 2,
559
+ lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
560
+ },
561
+ },
562
+ });
563
+ ```
564
+
565
+ ### TypeScript Usages
566
+
567
+ You can refer to [the example](examples/typescript/scripts.ts) for how to declare your custom commands.
568
+
569
+ ## Transparent Key Prefixing
570
+
571
+ This feature allows you to specify a string that will automatically be prepended
572
+ to all the keys in a command, which makes it easier to manage your key
573
+ namespaces.
574
+
575
+ **Warning** This feature won't apply to commands like [KEYS](http://redis.io/commands/KEYS) and [SCAN](http://redis.io/commands/scan) that take patterns rather than actual keys([#239](https://github.com/redis/ioredis/issues/239)),
576
+ and this feature also won't apply to the replies of commands even if they are key names ([#325](https://github.com/redis/ioredis/issues/325)).
577
+
578
+ ```javascript
579
+ const fooRedis = new Redis({ keyPrefix: "foo:" });
580
+ fooRedis.set("bar", "baz"); // Actually sends SET foo:bar baz
581
+
582
+ fooRedis.defineCommand("myecho", {
583
+ numberOfKeys: 2,
584
+ lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
585
+ });
586
+
587
+ // Works well with pipelining/transaction
588
+ fooRedis
589
+ .pipeline()
590
+ // Sends SORT foo:list BY foo:weight_*->fieldname
591
+ .sort("list", "BY", "weight_*->fieldname")
592
+ // Supports custom commands
593
+ // Sends EVALSHA xxx foo:k1 foo:k2 a1 a2
594
+ .myecho("k1", "k2", "a1", "a2")
595
+ .exec();
596
+ ```
597
+
598
+ ## Transforming Arguments & Replies
599
+
600
+ Most Redis commands take one or more Strings as arguments,
601
+ and replies are sent back as a single String or an Array of Strings. However, sometimes
602
+ you may want something different. For instance, it would be more convenient if the `HGETALL`
603
+ command returns a hash (e.g. `{ key: val1, key2: v2 }`) rather than an array of key values (e.g. `[key1, val1, key2, val2]`).
604
+
605
+ ioredis-om has a flexible system for transforming arguments and replies. There are two types
606
+ of transformers, argument transformer and reply transformer:
607
+
608
+ ```javascript
609
+ const Redis = require("ioredis-om");
610
+
611
+ // Here's the built-in argument transformer converting
612
+ // hmset('key', { k1: 'v1', k2: 'v2' })
613
+ // or
614
+ // hmset('key', new Map([['k1', 'v1'], ['k2', 'v2']]))
615
+ // into
616
+ // hmset('key', 'k1', 'v1', 'k2', 'v2')
617
+ Redis.Command.setArgumentTransformer("hmset", (args) => {
618
+ if (args.length === 2) {
619
+ if (args[1] instanceof Map) {
620
+ // utils is a internal module of ioredis-om
621
+ return [args[0], ...utils.convertMapToArray(args[1])];
622
+ }
623
+ if (typeof args[1] === "object" && args[1] !== null) {
624
+ return [args[0], ...utils.convertObjectToArray(args[1])];
625
+ }
626
+ }
627
+ return args;
628
+ });
629
+
630
+ // Here's the built-in reply transformer converting the HGETALL reply
631
+ // ['k1', 'v1', 'k2', 'v2']
632
+ // into
633
+ // { k1: 'v1', 'k2': 'v2' }
634
+ Redis.Command.setReplyTransformer("hgetall", (result) => {
635
+ if (Array.isArray(result)) {
636
+ const obj = {};
637
+ for (let i = 0; i < result.length; i += 2) {
638
+ obj[result[i]] = result[i + 1];
639
+ }
640
+ return obj;
641
+ }
642
+ return result;
643
+ });
644
+ ```
645
+
646
+ There are three built-in transformers, two argument transformers for `hmset` & `mset` and
647
+ a reply transformer for `hgetall`. Transformers for `hmset` and `hgetall` were mentioned
648
+ above, and the transformer for `mset` is similar to the one for `hmset`:
649
+
650
+ ```javascript
651
+ redis.mset({ k1: "v1", k2: "v2" });
652
+ redis.get("k1", (err, result) => {
653
+ // result === 'v1';
654
+ });
655
+
656
+ redis.mset(
657
+ new Map([
658
+ ["k3", "v3"],
659
+ ["k4", "v4"],
660
+ ])
661
+ );
662
+ redis.get("k3", (err, result) => {
663
+ // result === 'v3';
664
+ });
665
+ ```
666
+
667
+ Another useful example of a reply transformer is one that changes `hgetall` to return array of arrays instead of objects which avoids an unwanted conversation of hash keys to strings when dealing with binary hash keys:
668
+
669
+ ```javascript
670
+ Redis.Command.setReplyTransformer("hgetall", (result) => {
671
+ const arr = [];
672
+ for (let i = 0; i < result.length; i += 2) {
673
+ arr.push([result[i], result[i + 1]]);
674
+ }
675
+ return arr;
676
+ });
677
+ redis.hset("h1", Buffer.from([0x01]), Buffer.from([0x02]));
678
+ redis.hset("h1", Buffer.from([0x03]), Buffer.from([0x04]));
679
+ redis.hgetallBuffer("h1", (err, result) => {
680
+ // result === [ [ <Buffer 01>, <Buffer 02> ], [ <Buffer 03>, <Buffer 04> ] ];
681
+ });
682
+ ```
683
+
684
+ ## Monitor
685
+
686
+ Redis supports the MONITOR command,
687
+ which lets you see all commands received by the Redis server across all client connections,
688
+ including from other client libraries and other computers.
689
+
690
+ The `monitor` method returns a monitor instance.
691
+ After you send the MONITOR command, no other commands are valid on that connection. ioredis-om will emit a monitor event for every new monitor message that comes across.
692
+ The callback for the monitor event takes a timestamp from the Redis server and an array of command arguments.
693
+
694
+ Here is a simple example:
695
+
696
+ ```javascript
697
+ redis.monitor((err, monitor) => {
698
+ monitor.on("monitor", (time, args, source, database) => {});
699
+ });
700
+ ```
701
+
702
+ Here is another example illustrating an `async` function and `monitor.disconnect()`:
703
+
704
+ ```javascript
705
+ async () => {
706
+ const monitor = await redis.monitor();
707
+ monitor.on("monitor", console.log);
708
+ // Any other tasks
709
+ monitor.disconnect();
710
+ };
711
+ ```
712
+
713
+ ## Streamify Scanning
714
+
715
+ Redis 2.8 added the `SCAN` command to incrementally iterate through the keys in the database. It's different from `KEYS` in that
716
+ `SCAN` only returns a small number of elements each call, so it can be used in production without the downside
717
+ of blocking the server for a long time. However, it requires recording the cursor on the client side each time
718
+ the `SCAN` command is called in order to iterate through all the keys correctly. Since it's a relatively common use case, ioredis-om
719
+ provides a streaming interface for the `SCAN` command to make things much easier. A readable stream can be created by calling `scanStream`:
720
+
721
+ ```javascript
722
+ const redis = new Redis();
723
+ // Create a readable stream (object mode)
724
+ const stream = redis.scanStream();
725
+ stream.on("data", (resultKeys) => {
726
+ // `resultKeys` is an array of strings representing key names.
727
+ // Note that resultKeys may contain 0 keys, and that it will sometimes
728
+ // contain duplicates due to SCAN's implementation in Redis.
729
+ for (let i = 0; i < resultKeys.length; i++) {
730
+ console.log(resultKeys[i]);
731
+ }
732
+ });
733
+ stream.on("end", () => {
734
+ console.log("all keys have been visited");
735
+ });
736
+ ```
737
+
738
+ `scanStream` accepts an option, with which you can specify the `MATCH` pattern, the `TYPE` filter, and the `COUNT` argument:
739
+
740
+ ```javascript
741
+ const stream = redis.scanStream({
742
+ // only returns keys following the pattern of `user:*`
743
+ match: "user:*",
744
+ // only return objects that match a given type,
745
+ // (requires Redis >= 6.0)
746
+ type: "zset",
747
+ // returns approximately 100 elements per call
748
+ count: 100,
749
+ });
750
+ ```
751
+
752
+ Just like other commands, `scanStream` has a binary version `scanBufferStream`, which returns an array of buffers. It's useful when
753
+ the key names are not utf8 strings.
754
+
755
+ There are also `hscanStream`, `zscanStream` and `sscanStream` to iterate through elements in a hash, zset and set. The interface of each is
756
+ similar to `scanStream` except the first argument is the key name:
757
+
758
+ ```javascript
759
+ const stream = redis.zscanStream("myhash", {
760
+ match: "age:??",
761
+ });
762
+ ```
763
+
764
+ The `hscanStream` also accepts the `noValues` option to specify whether Redis should return only the keys in the hash table without their corresponding values.
765
+
766
+ ```javascript
767
+ const stream = redis.hscanStream("myhash", {
768
+ match: "age:??",
769
+ noValues: true,
770
+ });
771
+ ```
772
+
773
+ You can learn more from the [Redis documentation](http://redis.io/commands/scan).
774
+
775
+ **Useful Tips**
776
+ It's pretty common that doing an async task in the `data` handler. We'd like the scanning process to be paused until the async task to be finished. `Stream#pause()` and `Stream#resume()` do the trick. For example if we want to migrate data in Redis to MySQL:
777
+
778
+ ```javascript
779
+ const stream = redis.scanStream();
780
+ stream.on("data", (resultKeys) => {
781
+ // Pause the stream from scanning more keys until we've migrated the current keys.
782
+ stream.pause();
783
+
784
+ Promise.all(resultKeys.map(migrateKeyToMySQL)).then(() => {
785
+ // Resume the stream here.
786
+ stream.resume();
787
+ });
788
+ });
789
+
790
+ stream.on("end", () => {
791
+ console.log("done migration");
792
+ });
793
+ ```
794
+
795
+ ## Auto-reconnect
796
+
797
+ By default, ioredis-om will try to reconnect when the connection to Redis is lost
798
+ except when the connection is closed manually by `redis.disconnect()` or `redis.quit()`.
799
+
800
+ It's very flexible to control how long to wait to reconnect after disconnection
801
+ using the `retryStrategy` option:
802
+
803
+ ```javascript
804
+ const redis = new Redis({
805
+ // This is the default value of `retryStrategy`
806
+ retryStrategy(times) {
807
+ const delay = Math.min(times * 50, 2000);
808
+ return delay;
809
+ },
810
+ });
811
+ ```
812
+
813
+ `retryStrategy` is a function that will be called when the connection is lost.
814
+ The argument `times` means this is the nth reconnection being made and
815
+ the return value represents how long (in ms) to wait to reconnect. When the
816
+ return value isn't a number, ioredis-om will stop trying to reconnect, and the connection
817
+ will be lost forever if the user doesn't call `redis.connect()` manually.
818
+
819
+ When reconnected, the client will auto subscribe to channels that the previous connection subscribed to.
820
+ This behavior can be disabled by setting the `autoResubscribe` option to `false`.
821
+
822
+ And if the previous connection has some unfulfilled commands (most likely blocking commands such as `brpop` and `blpop`),
823
+ the client will resend them when reconnected. This behavior can be disabled by setting the `autoResendUnfulfilledCommands` option to `false`.
824
+
825
+ By default, all pending commands will be flushed with an error every 20 retry attempts. That makes sure commands won't wait forever when the connection is down. You can change this behavior by setting `maxRetriesPerRequest`:
826
+
827
+ ```javascript
828
+ const redis = new Redis({
829
+ maxRetriesPerRequest: 1,
830
+ });
831
+ ```
832
+
833
+ Set maxRetriesPerRequest to `null` to disable this behavior, and every command will wait forever until the connection is alive again (which was the default behavior before v4 of this client).
834
+
835
+ ### Blocking Command Timeout
836
+
837
+ ioredis-om can apply a client-side timeout to blocking commands (such as `blpop`, `brpop`, `bzpopmin`, `bzmpop`, `blmpop`, `xread`, `xreadgroup`, etc.). This protects against scenarios where the TCP connection becomes a zombie (e.g., due to a silent network failure like a Docker network disconnect) and Redis never replies.
838
+
839
+ This feature is **opt-in**. It is **disabled by default** and is only enabled
840
+ when `blockingTimeout` is set to a positive number of milliseconds. If
841
+ `blockingTimeout` is omitted, `0`, or negative (for example `-1`), ioredis-om
842
+ does not arm any client-side timeouts for blocking commands and their
843
+ behavior matches Redis exactly.
844
+
845
+ ```javascript
846
+ const redis = new Redis({
847
+ blockingTimeout: 30000, // Enable blocking timeout protection
848
+ });
849
+ ```
850
+
851
+ When enabled:
852
+
853
+ - For commands with a finite timeout (e.g., `blpop("key", 5)`), ioredis-om sets a client-side deadline based on the command's timeout plus a small grace period (`blockingTimeoutGrace`, default 100ms). If no reply arrives before the deadline, the command resolves with `null`—the same value Redis returns when a blocking command times out normally.
854
+ - For commands that block forever (e.g., `timeout = 0` or `BLOCK 0`), the `blockingTimeout` value is used as a safety net.
855
+
856
+ ### Reconnect on Error
857
+
858
+ Besides auto-reconnect when the connection is closed, ioredis-om supports reconnecting on certain Redis errors using the `reconnectOnError` option. Here's an example that will reconnect when receiving `READONLY` error:
859
+
860
+ ```javascript
861
+ const redis = new Redis({
862
+ reconnectOnError(err) {
863
+ const targetError = "READONLY";
864
+ if (err.message.includes(targetError)) {
865
+ // Only reconnect when the error contains "READONLY"
866
+ return true; // or `return 1;`
867
+ }
868
+ },
869
+ });
870
+ ```
871
+
872
+ This feature is useful when using Amazon ElastiCache instances with Auto-failover disabled. On these instances, test your `reconnectOnError` handler by manually promoting the replica node to the primary role using the AWS console. The following writes fail with the error `READONLY`. Using `reconnectOnError`, we can force the connection to reconnect on this error in order to connect to the new master. Furthermore, if the `reconnectOnError` returns `2`, ioredis-om will resend the failed command after reconnecting.
873
+
874
+ On ElastiCache instances with Auto-failover enabled, `reconnectOnError` does not execute. Instead of returning a Redis error, AWS closes all connections to the master endpoint until the new primary node is ready. ioredis-om reconnects via `retryStrategy` instead of `reconnectOnError` after about a minute. On ElastiCache instances with Auto-failover enabled, test failover events with the `Failover primary` option in the AWS console.
875
+
876
+ ## Connection Events
877
+
878
+ The Redis instance will emit some events about the state of the connection to the Redis server.
879
+
880
+ | Event | Description |
881
+ | :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
882
+ | connect | emits when a connection is established to the Redis server. |
883
+ | ready | If `enableReadyCheck` is `true`, client will emit `ready` when the server reports that it is ready to receive commands (e.g. finish loading data from disk).<br>Otherwise, `ready` will be emitted immediately right after the `connect` event. |
884
+ | error | emits when an error occurs while connecting.<br>However, ioredis-om emits all `error` events silently (only emits when there's at least one listener) so that your application won't crash if you're not listening to the `error` event.<br>When `redis.connect()` is explicitly called the error will also be rejected from the returned promise, in addition to emitting it. If `redis.connect()` is not called explicitly and `lazyConnect` is true, ioredis-om will try to connect automatically on the first command and emit the `error` event silently. |
885
+ | close | emits when an established Redis server connection has closed. |
886
+ | reconnecting | emits after `close` when a reconnection will be made. The argument of the event is the time (in ms) before reconnecting. |
887
+ | end | emits after `close` when no more reconnections will be made, or the connection is failed to establish. |
888
+ | wait | emits when `lazyConnect` is set and will wait for the first command to be called before connecting. |
889
+
890
+ You can also check out the `Redis#status` property to get the current connection status.
891
+
892
+ Besides the above connection events, there are several other custom events:
893
+
894
+ | Event | Description |
895
+ | :----- | :------------------------------------------------------------------ |
896
+ | select | emits when the database changed. The argument is the new db number. |
897
+
898
+ ## Diagnostics Channel
899
+
900
+ ioredis-om publishes telemetry through Node.js [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html), allowing APM tools and custom instrumentation to observe commands, connections, and batch operations without modifying application code.
901
+
902
+ These channels use `TracingChannel#tracePromise()` and emit `start`, `end`, `asyncStart`, `asyncEnd`, and `error` sub-events. Requires Node.js >= 18.19.0; on older versions the channels are silently unavailable (zero overhead). Subscribe via `tracing:<name>:<event>`:
903
+
904
+ ```typescript
905
+ import dc from "node:diagnostics_channel";
906
+
907
+ dc.subscribe("tracing:ioredis-om:command:start", ({ command, args }) => {
908
+ console.log(`> ${command}`, args);
909
+ });
910
+
911
+ dc.subscribe("tracing:ioredis-om:command:asyncEnd", ({ command }) => {
912
+ console.log(`${command} settled`);
913
+ });
914
+
915
+ dc.subscribe("tracing:ioredis-om:command:error", ({ command, error }) => {
916
+ console.error(`${command} failed:`, error);
917
+ });
918
+ ```
919
+
920
+ | Channel name | Payload | Description |
921
+ | :---------------- | :---------------------- | :------------------------------------------------------- |
922
+ | `ioredis-om:command` | `CommandTraceContext` | Individual command (standalone, pipeline, or within MULTI) |
923
+ | `ioredis-om:batch` | `BatchOperationContext` | MULTI transaction as a whole |
924
+ | `ioredis-om:connect` | `ConnectTraceContext` | Socket connection attempt |
925
+
926
+ Command arguments are sanitized before emission using rules adapted from `@opentelemetry/redis-common`. Sensitive values (e.g. values in `SET`, `AUTH` passwords) are replaced with `?`, while read-only commands like `GET` and `DEL` retain all arguments. This is safe by default: unlisted or custom commands have all arguments redacted.
927
+
928
+ Context types (`CommandTraceContext`, `BatchOperationContext`, `ConnectTraceContext`) are exported from `ioredis-om`.
929
+
930
+ ## Offline Queue
931
+
932
+ When a command can't be processed by Redis (being sent before the `ready` event), by default, it's added to the offline queue and will be
933
+ executed when it can be processed. You can disable this feature by setting the `enableOfflineQueue`
934
+ option to `false`:
935
+
936
+ ```javascript
937
+ const redis = new Redis({ enableOfflineQueue: false });
938
+ ```
939
+
940
+ ## TLS Options
941
+
942
+ Redis doesn't support TLS natively, however if the redis server you want to connect to is hosted behind a TLS proxy (e.g. [stunnel](https://www.stunnel.org/)) or is offered by a PaaS service that supports TLS connection (e.g. [Redis.com](https://redis.com/)), you can set the `tls` option:
943
+
944
+ ```javascript
945
+ const redis = new Redis({
946
+ host: "localhost",
947
+ tls: {
948
+ // Refer to `tls.connect()` section in
949
+ // https://nodejs.org/api/tls.html
950
+ // for all supported options
951
+ ca: fs.readFileSync("cert.pem"),
952
+ },
953
+ });
954
+ ```
955
+
956
+ Alternatively, specify the connection through a [`rediss://` URL](https://www.iana.org/assignments/uri-schemes/prov/rediss).
957
+
958
+ ```javascript
959
+ const redis = new Redis("rediss://redis.my-service.com");
960
+ ```
961
+
962
+ If you do not want to use a connection string, you can also specify an empty `tls: {}` object:
963
+
964
+ ```javascript
965
+ const redis = new Redis({
966
+ host: "redis.my-service.com",
967
+ tls: {},
968
+ });
969
+ ```
970
+
971
+ ### TLS Profiles
972
+
973
+ > **Warning**
974
+ > TLS profiles described in this section are going to be deprecated in the next major version. Please provide TLS options explicitly.
975
+
976
+ To make it easier to configure we provide a few pre-configured TLS profiles that can be specified by setting the `tls` option to the profile's name or specifying a `tls.profile` option in case you need to customize some values of the profile.
977
+
978
+ Profiles:
979
+
980
+ - `RedisCloudFixed`: Contains the CA for [Redis.com](https://redis.com/) Cloud fixed subscriptions
981
+ - `RedisCloudFlexible`: Contains the CA for [Redis.com](https://redis.com/) Cloud flexible subscriptions
982
+
983
+ ```javascript
984
+ const redis = new Redis({
985
+ host: "localhost",
986
+ tls: "RedisCloudFixed",
987
+ });
988
+
989
+ const redisWithClientCertificate = new Redis({
990
+ host: "localhost",
991
+ tls: {
992
+ profile: "RedisCloudFixed",
993
+ key: "123",
994
+ },
995
+ });
996
+ ```
997
+
998
+ ---
999
+
1000
+ ## Sentinel
1001
+
1002
+ ioredis-om supports Sentinel out of the box. It works transparently as all features that work when
1003
+ you connect to a single node also work when you connect to a sentinel group. Make sure to run Redis >= 2.8.12 if you want to use this feature. Sentinels have a default port of 26379.
1004
+
1005
+ To connect using Sentinel, use:
1006
+
1007
+ ```javascript
1008
+ const redis = new Redis({
1009
+ sentinels: [
1010
+ { host: "localhost", port: 26379 },
1011
+ { host: "localhost", port: 26380 },
1012
+ ],
1013
+ name: "mymaster",
1014
+ });
1015
+
1016
+ redis.set("foo", "bar");
1017
+ ```
1018
+
1019
+ The arguments passed to the constructor are different from the ones you use to connect to a single node, where:
1020
+
1021
+ - `name` identifies a group of Redis instances composed of a master and one or more slaves (`mymaster` in the example);
1022
+ - `sentinelPassword` (optional) password for Sentinel instances.
1023
+ - `sentinels` are a list of sentinels to connect to. The list does not need to enumerate all your sentinel instances, but a few so that if one is down the client will try the next one.
1024
+ - `role` (optional) with a value of `slave` will return a random slave from the Sentinel group.
1025
+ - `preferredSlaves` (optional) can be used to prefer a particular slave or set of slaves based on priority. It accepts a function or array.
1026
+ - `enableTLSForSentinelMode` (optional) set to true if connecting to sentinel instances that are encrypted
1027
+
1028
+ ioredis-om **guarantees** that the node you connected to is always a master even after a failover. When a failover happens, instead of trying to reconnect to the failed node (which will be demoted to slave when it's available again), ioredis-om will ask sentinels for the new master node and connect to it. All commands sent during the failover are queued and will be executed when the new connection is established so that none of the commands will be lost.
1029
+
1030
+ It's possible to connect to a slave instead of a master by specifying the option `role` with the value of `slave` and ioredis-om will try to connect to a random slave of the specified master, with the guarantee that the connected node is always a slave. If the current node is promoted to master due to a failover, ioredis-om will disconnect from it and ask the sentinels for another slave node to connect to.
1031
+
1032
+ If you specify the option `preferredSlaves` along with `role: 'slave'` ioredis-om will attempt to use this value when selecting the slave from the pool of available slaves. The value of `preferredSlaves` should either be a function that accepts an array of available slaves and returns a single result, or an array of slave values priorities by the lowest `prio` value first with a default value of `1`.
1033
+
1034
+ ```javascript
1035
+ // available slaves format
1036
+ const availableSlaves = [{ ip: "127.0.0.1", port: "31231", flags: "slave" }];
1037
+
1038
+ // preferredSlaves array format
1039
+ let preferredSlaves = [
1040
+ { ip: "127.0.0.1", port: "31231", prio: 1 },
1041
+ { ip: "127.0.0.1", port: "31232", prio: 2 },
1042
+ ];
1043
+
1044
+ // preferredSlaves function format
1045
+ preferredSlaves = function (availableSlaves) {
1046
+ for (let i = 0; i < availableSlaves.length; i++) {
1047
+ const slave = availableSlaves[i];
1048
+ if (slave.ip === "127.0.0.1") {
1049
+ if (slave.port === "31234") {
1050
+ return slave;
1051
+ }
1052
+ }
1053
+ }
1054
+ // if no preferred slaves are available a random one is used
1055
+ return false;
1056
+ };
1057
+
1058
+ const redis = new Redis({
1059
+ sentinels: [
1060
+ { host: "127.0.0.1", port: 26379 },
1061
+ { host: "127.0.0.1", port: 26380 },
1062
+ ],
1063
+ name: "mymaster",
1064
+ role: "slave",
1065
+ preferredSlaves: preferredSlaves,
1066
+ });
1067
+ ```
1068
+
1069
+ Besides the `retryStrategy` option, there's also a `sentinelRetryStrategy` in Sentinel mode which will be invoked when all the sentinel nodes are unreachable during connecting. If `sentinelRetryStrategy` returns a valid delay time, ioredis-om will try to reconnect from scratch. The default value of `sentinelRetryStrategy` is:
1070
+
1071
+ ```javascript
1072
+ function (times) {
1073
+ const delay = Math.min(times * 10, 1000);
1074
+ return delay;
1075
+ }
1076
+ ```
1077
+
1078
+ ## Cluster
1079
+
1080
+ Redis Cluster provides a way to run a Redis installation where data is automatically sharded across multiple Redis nodes.
1081
+ You can connect to a Redis Cluster like this:
1082
+
1083
+ ```javascript
1084
+ const Redis = require("ioredis-om");
1085
+
1086
+ const cluster = new Redis.Cluster([
1087
+ {
1088
+ port: 6380,
1089
+ host: "127.0.0.1",
1090
+ },
1091
+ {
1092
+ port: 6381,
1093
+ host: "127.0.0.1",
1094
+ },
1095
+ ]);
1096
+
1097
+ cluster.set("foo", "bar");
1098
+ cluster.get("foo", (err, res) => {
1099
+ // res === 'bar'
1100
+ });
1101
+ ```
1102
+
1103
+ `Cluster` constructor accepts two arguments, where:
1104
+
1105
+ 0. The first argument is a list of nodes of the cluster you want to connect to.
1106
+ Just like Sentinel, the list does not need to enumerate all your cluster nodes,
1107
+ but a few so that if one is unreachable the client will try the next one, and the client will discover other nodes automatically when at least one node is connected.
1108
+ 1. The second argument is the options, where:
1109
+
1110
+ - `clusterRetryStrategy`: When none of the startup nodes are reachable, `clusterRetryStrategy` will be invoked. When a number is returned,
1111
+ ioredis-om will try to reconnect to the startup nodes from scratch after the specified delay (in ms). Otherwise, an error of "None of startup nodes is available" will be returned.
1112
+ The default value of this option is:
1113
+
1114
+ ```javascript
1115
+ function (times) {
1116
+ const delay = Math.min(100 + times * 2, 2000);
1117
+ return delay;
1118
+ }
1119
+ ```
1120
+
1121
+ It's possible to modify the `startupNodes` property in order to switch to another set of nodes here:
1122
+
1123
+ ```javascript
1124
+ function (times) {
1125
+ this.startupNodes = [{ port: 6790, host: '127.0.0.1' }];
1126
+ return Math.min(100 + times * 2, 2000);
1127
+ }
1128
+ ```
1129
+
1130
+ - `dnsLookup`: Alternative DNS lookup function (`dns.lookup()` is used by default). It may be useful to override this in special cases, such as when AWS ElastiCache used with TLS enabled.
1131
+ - `enableOfflineQueue`: Similar to the `enableOfflineQueue` option of `Redis` class.
1132
+ - `enableReadyCheck`: When enabled, "ready" event will only be emitted when `CLUSTER INFO` command
1133
+ reporting the cluster is ready for handling commands. Otherwise, it will be emitted immediately after "connect" is emitted.
1134
+ - `scaleReads`: Config where to send the read queries. See below for more details.
1135
+ - `maxRedirections`: When a cluster related error (e.g. `MOVED`, `ASK` and `CLUSTERDOWN` etc.) is received, the client will redirect the
1136
+ command to another node. This option limits the max redirections allowed when sending a command. The default value is `16`.
1137
+ - `retryDelayOnFailover`: If the target node is disconnected when sending a command,
1138
+ ioredis-om will retry after the specified delay. The default value is `100`. You should make sure `retryDelayOnFailover * maxRedirections > cluster-node-timeout`
1139
+ to insure that no command will fail during a failover.
1140
+ - `retryDelayOnClusterDown`: When a cluster is down, all commands will be rejected with the error of `CLUSTERDOWN`. If this option is a number (by default, it is `100`), the client
1141
+ will resend the commands after the specified time (in ms).
1142
+ - `retryDelayOnTryAgain`: If this option is a number (by default, it is `100`), the client
1143
+ will resend the commands rejected with `TRYAGAIN` error after the specified time (in ms).
1144
+ - `retryDelayOnMoved`: By default, this value is `0` (in ms), which means when a `MOVED` error is received, the client will resend
1145
+ the command instantly to the node returned together with the `MOVED` error. However, sometimes it takes time for a cluster to become
1146
+ state stabilized after a failover, so adding a delay before resending can prevent a ping pong effect.
1147
+ - `redisOptions`: Default options passed to the constructor of `Redis` when connecting to a node.
1148
+ - `slotsRefreshTimeout`: Milliseconds before a timeout occurs while refreshing slots from the cluster (default `1000`).
1149
+ - `slotsRefreshInterval`: Milliseconds between every automatic slots refresh (by default, it is disabled).
1150
+
1151
+ ### Read-Write Splitting
1152
+
1153
+ A typical redis cluster contains three or more masters and several slaves for each master. It's possible to scale out redis cluster by sending read queries to slaves and write queries to masters by setting the `scaleReads` option.
1154
+
1155
+ `scaleReads` is "master" by default, which means ioredis-om will never send any queries to slaves. There are other three available options:
1156
+
1157
+ 1. "all": Send write queries to masters and read queries to masters or slaves randomly.
1158
+ 2. "slave": Send write queries to masters and read queries to slaves.
1159
+ 3. a custom `function(nodes, command): node`: Will choose the custom function to select to which node to send read queries (write queries keep being sent to master). The first node in `nodes` is always the master serving the relevant slots. If the function returns an array of nodes, a random node of that list will be selected.
1160
+
1161
+ For example:
1162
+
1163
+ ```javascript
1164
+ const cluster = new Redis.Cluster(
1165
+ [
1166
+ /* nodes */
1167
+ ],
1168
+ {
1169
+ scaleReads: "slave",
1170
+ }
1171
+ );
1172
+ cluster.set("foo", "bar"); // This query will be sent to one of the masters.
1173
+ cluster.get("foo", (err, res) => {
1174
+ // This query will be sent to one of the slaves.
1175
+ });
1176
+ ```
1177
+
1178
+ **NB** In the code snippet above, the `res` may not be equal to "bar" because of the lag of replication between the master and slaves.
1179
+
1180
+ ### Running Commands to Multiple Nodes
1181
+
1182
+ Every command will be sent to exactly one node. For commands containing keys, (e.g. `GET`, `SET` and `HGETALL`), ioredis-om sends them to the node that serving the keys, and for other commands not containing keys, (e.g. `INFO`, `KEYS` and `FLUSHDB`), ioredis-om sends them to a random node.
1183
+
1184
+ Sometimes you may want to send a command to multiple nodes (masters or slaves) of the cluster, you can get the nodes via `Cluster#nodes()` method.
1185
+
1186
+ `Cluster#nodes()` accepts a parameter role, which can be "master", "slave" and "all" (default), and returns an array of `Redis` instance. For example:
1187
+
1188
+ ```javascript
1189
+ // Send `FLUSHDB` command to all slaves:
1190
+ const slaves = cluster.nodes("slave");
1191
+ Promise.all(slaves.map((node) => node.flushdb()));
1192
+
1193
+ // Get keys of all the masters:
1194
+ const masters = cluster.nodes("master");
1195
+ Promise.all(
1196
+ masters
1197
+ .map((node) => node.keys())
1198
+ .then((keys) => {
1199
+ // keys: [['key1', 'key2'], ['key3', 'key4']]
1200
+ })
1201
+ );
1202
+ ```
1203
+
1204
+ ### NAT Mapping
1205
+
1206
+ Sometimes the cluster is hosted within a internal network that can only be accessed via a NAT (Network Address Translation) instance. See [Accessing ElastiCache from outside AWS](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/accessing-elasticache.html) as an example.
1207
+
1208
+ You can specify nat mapping rules via `natMap` option:
1209
+
1210
+ ```javascript
1211
+ const cluster = new Redis.Cluster(
1212
+ [
1213
+ {
1214
+ host: "203.0.113.73",
1215
+ port: 30001,
1216
+ },
1217
+ ],
1218
+ {
1219
+ natMap: {
1220
+ "10.0.1.230:30001": { host: "203.0.113.73", port: 30001 },
1221
+ "10.0.1.231:30001": { host: "203.0.113.73", port: 30002 },
1222
+ "10.0.1.232:30001": { host: "203.0.113.73", port: 30003 },
1223
+ },
1224
+ }
1225
+ );
1226
+ ```
1227
+
1228
+ Or you can specify this parameter through function:
1229
+
1230
+ ```javascript
1231
+ const cluster = new Redis.Cluster(
1232
+ [
1233
+ {
1234
+ host: "203.0.113.73",
1235
+ port: 30001,
1236
+ },
1237
+ ],
1238
+ {
1239
+ natMap: (key) => {
1240
+ if (key.includes("30001")) {
1241
+ return { host: "203.0.113.73", port: 30001 };
1242
+ }
1243
+
1244
+ return null;
1245
+ },
1246
+ }
1247
+ );
1248
+ ```
1249
+
1250
+ This option is also useful when the cluster is running inside a Docker container.
1251
+ Also it works for Clusters in cloud infrastructure where cluster nodes connected through dedicated subnet.
1252
+
1253
+ Specifying through may be useful if you don't know concrete internal host and know only node port.
1254
+
1255
+ ### Transaction and Pipeline in Cluster Mode
1256
+
1257
+ Almost all features that are supported by `Redis` are also supported by `Redis.Cluster`, e.g. custom commands, transaction and pipeline.
1258
+ However there are some differences when using transaction and pipeline in Cluster mode:
1259
+
1260
+ 0. All keys in a pipeline should belong to slots served by the same node, since ioredis-om sends all commands in a pipeline to the same node.
1261
+ 1. You can't use `multi` without pipeline (aka `cluster.multi({ pipeline: false })`). This is because when you call `cluster.multi({ pipeline: false })`, ioredis-om doesn't know which node the `multi` command should be sent to.
1262
+
1263
+ When any commands in a pipeline receives a `MOVED` or `ASK` error, ioredis-om will resend the whole pipeline to the specified node automatically if all of the following conditions are satisfied:
1264
+
1265
+ 0. All errors received in the pipeline are the same. For example, we won't resend the pipeline if we got two `MOVED` errors pointing to different nodes.
1266
+ 1. All commands executed successfully are readonly commands. This makes sure that resending the pipeline won't have side effects.
1267
+
1268
+ ### Pub/Sub
1269
+
1270
+ Pub/Sub in cluster mode works exactly as the same as in standalone mode. Internally, when a node of the cluster receives a message, it will broadcast the message to the other nodes. ioredis-om makes sure that each message will only be received once by strictly subscribing one node at the same time.
1271
+
1272
+ ```javascript
1273
+ const nodes = [
1274
+ /* nodes */
1275
+ ];
1276
+ const pub = new Redis.Cluster(nodes);
1277
+ const sub = new Redis.Cluster(nodes);
1278
+ sub.on("message", (channel, message) => {
1279
+ console.log(channel, message);
1280
+ });
1281
+
1282
+ sub.subscribe("news", () => {
1283
+ pub.publish("news", "highlights");
1284
+ });
1285
+ ```
1286
+
1287
+ ### Sharded Pub/Sub
1288
+
1289
+ For sharded Pub/Sub, use the `spublish` and `ssubscribe` commands instead of the traditional `publish` and `subscribe`. With the old commands, the Redis cluster handles message propagation behind the scenes, allowing you to publish or subscribe to any node without considering sharding. However, this approach has scalability limitations that are addressed with sharded Pub/Sub. Here’s what you need to know:
1290
+
1291
+ 1. Instead of a single subscriber connection, there is now one subscriber connection per shard. Because of the potential overhead, you can enable or disable the use of the cluster subscriber group with the `shardedSubscribers` option. By default, this option is set to `false`, meaning sharded subscriptions are disabled. You should enable this option when establishing your cluster connection before using `ssubscribe`.
1292
+ 2. All channel names that you pass to a single `ssubscribe` need to map to the same hash slot. You can call `ssubscribe` multiple times on the same cluster client instance to subscribe to channels across slots. The cluster's subscriber group takes care of forwarding the `ssubscribe` command to the shard that is responsible for the channels.
1293
+
1294
+ The following basic example shows you how to use sharded Pub/Sub:
1295
+
1296
+ ```javascript
1297
+ const cluster: Cluster = new Cluster([{ host: host, port: port }], {
1298
+ shardedSubscribers: true,
1299
+ });
1300
+
1301
+ //Register the callback
1302
+ cluster.on("smessage", (channel, message) => {
1303
+ console.log(message);
1304
+ });
1305
+
1306
+ //Subscribe to the channels on the same slot
1307
+ cluster
1308
+ .ssubscribe("channel{my}:1", "channel{my}:2")
1309
+ .then((count: number) => {
1310
+ console.log(count);
1311
+ })
1312
+ .catch((err) => {
1313
+ console.log(err);
1314
+ });
1315
+
1316
+ //Publish a message
1317
+ cluster
1318
+ .spublish("channel{my}:1", "This is a test message to my first channel.")
1319
+ .then((value: number) => {
1320
+ console.log("Published a message to channel{my}:1");
1321
+ });
1322
+ ```
1323
+
1324
+ ### Events
1325
+
1326
+ | Event | Description |
1327
+ | :----------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1328
+ | connect | emits when a connection is established to the Redis server. |
1329
+ | ready | emits when `CLUSTER INFO` reporting the cluster is able to receive commands (if `enableReadyCheck` is `true`) or immediately after `connect` event (if `enableReadyCheck` is false). |
1330
+ | error | emits when an error occurs while connecting with a property of `lastNodeError` representing the last node error received. This event is emitted silently (only emitting if there's at least one listener). |
1331
+ | close | emits when an established Redis server connection has closed. |
1332
+ | reconnecting | emits after `close` when a reconnection will be made. The argument of the event is the time (in ms) before reconnecting. |
1333
+ | end | emits after `close` when no more reconnections will be made. |
1334
+ | +node | emits when a new node is connected. |
1335
+ | -node | emits when a node is disconnected. |
1336
+ | node error | emits when an error occurs when connecting to a node. The second argument indicates the address of the node. |
1337
+
1338
+ ### Password
1339
+
1340
+ Setting the `password` option to access password-protected clusters:
1341
+
1342
+ ```javascript
1343
+ const Redis = require("ioredis-om");
1344
+ const cluster = new Redis.Cluster(nodes, {
1345
+ redisOptions: {
1346
+ password: "your-cluster-password",
1347
+ },
1348
+ });
1349
+ ```
1350
+
1351
+ If some of nodes in the cluster using a different password, you should specify them in the first parameter:
1352
+
1353
+ ```javascript
1354
+ const Redis = require("ioredis-om");
1355
+ const cluster = new Redis.Cluster(
1356
+ [
1357
+ // Use password "password-for-30001" for 30001
1358
+ { port: 30001, password: "password-for-30001" },
1359
+ // Don't use password when accessing 30002
1360
+ { port: 30002, password: null },
1361
+ // Other nodes will use "fallback-password"
1362
+ ],
1363
+ {
1364
+ redisOptions: {
1365
+ password: "fallback-password",
1366
+ },
1367
+ }
1368
+ );
1369
+ ```
1370
+
1371
+ ### Special Note: Aws Elasticache Clusters with TLS
1372
+
1373
+ AWS ElastiCache for Redis (Clustered Mode) supports TLS encryption. If you use
1374
+ this, you may encounter errors with invalid certificates. To resolve this
1375
+ issue, construct the `Cluster` with the `dnsLookup` option as follows:
1376
+
1377
+ ```javascript
1378
+ const cluster = new Redis.Cluster(
1379
+ [
1380
+ {
1381
+ host: "clustercfg.myCluster.abcdefg.xyz.cache.amazonaws.com",
1382
+ port: 6379,
1383
+ },
1384
+ ],
1385
+ {
1386
+ dnsLookup: (address, callback) => callback(null, address),
1387
+ redisOptions: {
1388
+ tls: {},
1389
+ },
1390
+ }
1391
+ );
1392
+ ```
1393
+
1394
+ ---
1395
+
1396
+ ## Autopipelining
1397
+
1398
+ In standard mode, when you issue multiple commands, ioredis-om sends them to the server one by one. As described in Redis pipeline documentation, this is a suboptimal use of the network link, especially when such link is not very performant.
1399
+
1400
+ The TCP and network overhead negatively affects performance. Commands are stuck in the send queue until the previous ones are correctly delivered to the server. This is a problem known as Head-Of-Line blocking (HOL).
1401
+
1402
+ ioredis-om supports a feature called “auto pipelining”. It can be enabled by setting the option `enableAutoPipelining` to `true`. No other code change is necessary.
1403
+
1404
+ In auto pipelining mode, all commands issued during an event loop are enqueued in a pipeline automatically managed by ioredis-om. At the end of the iteration, the pipeline is executed and thus all commands are sent to the server at the same time.
1405
+
1406
+ This feature can dramatically improve throughput and avoids HOL blocking. In our benchmarks, the improvement was between 35% and 50%.
1407
+
1408
+ While an automatic pipeline is executing, all new commands will be enqueued in a new pipeline which will be executed as soon as the previous finishes.
1409
+
1410
+ When using Redis Cluster, one pipeline per node is created. Commands are assigned to pipelines according to which node serves the slot.
1411
+
1412
+ A pipeline will thus contain commands using different slots but that ultimately are assigned to the same node.
1413
+
1414
+ Note that the same slot limitation within a single command still holds, as it is a Redis limitation.
1415
+
1416
+ ### Example of Automatic Pipeline Enqueuing
1417
+
1418
+ This sample code uses ioredis-om with automatic pipeline enabled.
1419
+
1420
+ ```javascript
1421
+ const Redis = require("./built");
1422
+ const http = require("http");
1423
+
1424
+ const db = new Redis({ enableAutoPipelining: true });
1425
+
1426
+ const server = http.createServer((request, response) => {
1427
+ const key = new URL(request.url, "https://localhost:3000/").searchParams.get(
1428
+ "key"
1429
+ );
1430
+
1431
+ db.get(key, (err, value) => {
1432
+ response.writeHead(200, { "Content-Type": "text/plain" });
1433
+ response.end(value);
1434
+ });
1435
+ });
1436
+
1437
+ server.listen(3000);
1438
+ ```
1439
+
1440
+ When Node receives requests, it schedules them to be processed in one or more iterations of the events loop.
1441
+
1442
+ All commands issued by requests processing during one iteration of the loop will be wrapped in a pipeline automatically created by ioredis-om.
1443
+
1444
+ In the example above, the pipeline will have the following contents:
1445
+
1446
+ ```
1447
+ GET key1
1448
+ GET key2
1449
+ GET key3
1450
+ ...
1451
+ GET keyN
1452
+ ```
1453
+
1454
+ When all events in the current loop have been processed, the pipeline is executed and thus all commands are sent to the server at the same time.
1455
+
1456
+ While waiting for pipeline response from Redis, Node will still be able to process requests. All commands issued by request handler will be enqueued in a new automatically created pipeline. This pipeline will not be sent to the server yet.
1457
+
1458
+ As soon as a previous automatic pipeline has received all responses from the server, the new pipeline is immediately sent without waiting for the events loop iteration to finish.
1459
+
1460
+ This approach increases the utilization of the network link, reduces the TCP overhead and idle times and therefore improves throughput.
1461
+
1462
+ ### Benchmarks
1463
+
1464
+ Here's some of the results of our tests for a single node.
1465
+
1466
+ Each iteration of the test runs 1000 random commands on the server.
1467
+
1468
+ | | Samples | Result | Tolerance |
1469
+ | ------------------------- | ------- | ------------- | --------- |
1470
+ | default | 1000 | 174.62 op/sec | ± 0.45 % |
1471
+ | enableAutoPipelining=true | 1500 | 233.33 op/sec | ± 0.88 % |
1472
+
1473
+ And here's the same test for a cluster of 3 masters and 3 replicas:
1474
+
1475
+ | | Samples | Result | Tolerance |
1476
+ | ------------------------- | ------- | ------------- | --------- |
1477
+ | default | 1000 | 164.05 op/sec | ± 0.42 % |
1478
+ | enableAutoPipelining=true | 3000 | 235.31 op/sec | ± 0.94 % |
1479
+
1480
+ # Error Handling
1481
+
1482
+ All the errors returned by the Redis server are instances of `ReplyError`, which can be accessed via `Redis`:
1483
+
1484
+ ```javascript
1485
+ const Redis = require("ioredis-om");
1486
+ const redis = new Redis();
1487
+ // This command causes a reply error since the SET command requires two arguments.
1488
+ redis.set("foo", (err) => {
1489
+ err instanceof Redis.ReplyError;
1490
+ });
1491
+ ```
1492
+
1493
+ This is the error stack of the `ReplyError`:
1494
+
1495
+ ```
1496
+ ReplyError: ERR wrong number of arguments for 'set' command
1497
+ at ReplyParser._parseResult (/app/node_modules/ioredis-om/built/parsers/javascript.js:60:14)
1498
+ at ReplyParser.execute (/app/node_modules/ioredis-om/built/parsers/javascript.js:178:20)
1499
+ at Socket.<anonymous> (/app/node_modules/ioredis-om/built/redis/event_handler.js:99:22)
1500
+ at Socket.emit (events.js:97:17)
1501
+ at readableAddChunk (_stream_readable.js:143:16)
1502
+ at Socket.Readable.push (_stream_readable.js:106:10)
1503
+ at TCP.onread (net.js:509:20)
1504
+ ```
1505
+
1506
+ By default, the error stack doesn't make any sense because the whole stack happens in the ioredis-om
1507
+ module itself, not in your code. So it's not easy to find out where the error happens in your code.
1508
+ ioredis-om provides an option `showFriendlyErrorStack` to solve the problem. When you enable
1509
+ `showFriendlyErrorStack`, ioredis-om will optimize the error stack for you:
1510
+
1511
+ ```javascript
1512
+ const Redis = require("ioredis-om");
1513
+ const redis = new Redis({ showFriendlyErrorStack: true });
1514
+ redis.set("foo");
1515
+ ```
1516
+
1517
+ And the output will be:
1518
+
1519
+ ```
1520
+ ReplyError: ERR wrong number of arguments for 'set' command
1521
+ at Object.<anonymous> (/app/index.js:3:7)
1522
+ at Module._compile (module.js:446:26)
1523
+ at Object.Module._extensions..js (module.js:464:10)
1524
+ at Module.load (module.js:341:32)
1525
+ at Function.Module._load (module.js:296:12)
1526
+ at Function.Module.runMain (module.js:487:10)
1527
+ at startup (node.js:111:16)
1528
+ at node.js:799:3
1529
+ ```
1530
+
1531
+ The stack then points to the corresponding line in your application code (for example, the third line in the example above).
1532
+ Optimizing error stacks has a significant performance cost, so by
1533
+ default, this option is disabled and can only be used for debugging purposes. You **shouldn't** use this feature in a production environment.
1534
+
1535
+ # Running tests
1536
+
1537
+ Start a Redis server on 127.0.0.1:6379, and then:
1538
+
1539
+ ```shell
1540
+ npm test
1541
+ ```
1542
+
1543
+ `FLUSH ALL` will be invoked after each test, so make sure there's no valuable data in it before running tests.
1544
+
1545
+ If your testing environment does not let you spin up a Redis server [ioredis-mock](https://github.com/stipsan/ioredis-mock) is a drop-in replacement you can use in your tests. It aims to behave identically to ioredis-om connected to a Redis server so that your integration tests is easier to write and of better quality.
1546
+
1547
+ # Debug
1548
+
1549
+ You can set the `DEBUG` env to `ioredis-om:*` to print debug info:
1550
+
1551
+ ```shell
1552
+ $ DEBUG=ioredis-om:* node app.js
1553
+ ```
1554
+
1555
+ # Contributing
1556
+
1557
+ Issues, documentation improvements, and pull requests are welcome. Please open a discussion or issue before large changes when possible so maintainers can align on direction.
1558
+
1559
+ If you notice errors or unclear wording in this documentation, corrections are appreciated.
1560
+
1561
+ # Contributors
1562
+
1563
+ This project exists thanks to all the people who contribute:
1564
+
1565
+ <a href="https://github.com/redis/ioredis/graphs/contributors"><img src="https://opencollective.com/ioredis/contributors.svg?width=890&showBtn=false" /></a>
1566
+
1567
+ # License
1568
+
1569
+ MIT
1570
+
1571
+ [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fluin%2Fioredis.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fluin%2Fioredis?ref=badge_large)