Skip to content

Commit 2c9ad2e

Browse files
authored
chore(examples): fix examples for v5 (#2938)
1 parent bd5c230 commit 2c9ad2e

20 files changed

+133
-75
lines changed

examples/README.md

+7-7
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,12 @@ We'd love to see more examples here. If you have an idea that you'd like to see
4040

4141
To set up the examples folder so that you can run an example / develop one of your own:
4242

43-
```
44-
$ git clone https://github.com/redis/node-redis.git
45-
$ cd node-redis
46-
$ npm install -ws && npm run build-all
47-
$ cd examples
48-
$ npm install
43+
```bash
44+
git clone https://github.com/redis/node-redis.git
45+
cd node-redis
46+
npm install -ws && npm run build
47+
cd examples
48+
npm install
4949
```
5050

5151
### Coding Guidelines for Examples
@@ -91,5 +91,5 @@ await client.connect();
9191

9292
// Add your example code here...
9393

94-
client.destroy();
94+
client.close();
9595
```

examples/blocking-list-pop.js

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,15 @@
44
// The script will be blocked until the LPUSH command is executed.
55
// After which we log the list and quit the client.
66

7-
import { createClient, commandOptions } from 'redis';
7+
import { createClientPool } from 'redis';
88

9-
const client = createClient();
9+
const client = createClientPool();
1010

1111
await client.connect();
1212

1313
const keyName = 'keyName';
1414

1515
const blpopPromise = client.blPop(
16-
commandOptions({ isolated: true }),
1716
keyName,
1817
0
1918
);

examples/command-with-modifiers.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Define a custom script that shows example of SET command
22
// with several modifiers.
33

4-
import { createClient } from '../packages/client';
4+
import { createClient } from 'redis';
55

66
const client = createClient();
77

examples/connect-to-cluster.js

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// This is an example script to connect to a running cluster.
22
// After connecting to the cluster the code sets and get a value.
33

4-
// To setup this cluster you can follow the guide here:
4+
// To setup this cluster you can follow the guide here:
55
// https://redis.io/docs/manual/scaling/
66
// In this guide the ports which are being used are 7000 - 7005
77

@@ -29,5 +29,4 @@ await cluster.connect();
2929
await cluster.set('hello', 'cluster');
3030
const value = await cluster.get('hello');
3131
console.log(value);
32-
33-
await cluster.quit();
32+
await cluster.close();

examples/dump-and-restore.js

+6
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ const client = await createClient({
1212
console.log('Redis Client Error', err);
1313
}).connect();
1414

15+
// Make sure the source key exists
16+
await client.set('source', 'value');
17+
18+
// Make sure destination doesnt exist
19+
await client.del('destination');
20+
1521
// DUMP a specific key into a local variable
1622
const dump = await client.dump('source');
1723

examples/get-server-time.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ const client = createClient();
66
await client.connect();
77

88
const serverTime = await client.time();
9-
// 2022-02-25T12:57:40.000Z { microseconds: 351346 }
9+
// In v5, TIME returns [unixTimestamp: string, microseconds: string] instead of Date
10+
// Example: ['1708956789', '123456']
1011
console.log(serverTime);
1112

12-
client.destroy();
13+
// Convert to JavaScript Date if needed
14+
const [seconds, microseconds] = serverTime;
15+
const date = new Date(parseInt(seconds) * 1000 + parseInt(microseconds) / 1000);
16+
console.log('Converted to Date:', date);
17+
18+
client.close();

examples/hyperloglog.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const client = createClient();
99
await client.connect();
1010

1111
// Use `pfAdd` to add an element to a Hyperloglog, creating the Hyperloglog if necessary.
12-
// await client.pfAdd(key, value)
12+
// await client.pfAdd(key, value) // returns 1 or 0
1313

1414
// To get a count, the `pfCount` method is used.
1515
// await client.pfCount(key)
@@ -48,4 +48,4 @@ try {
4848
console.error(e);
4949
}
5050

51-
client.destroy();
51+
client.close();

examples/lua-multi-incr.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ const client = createClient({
1212
'redis.pcall("INCRBY", KEYS[1], ARGV[1]),' +
1313
'redis.pcall("INCRBY", KEYS[2], ARGV[1])' +
1414
'}',
15-
transformArguments(key1, key2, increment) {
16-
return [key1, key2, increment.toString()];
17-
},
15+
parseCommand(parser, key1, key2, increment) {
16+
parser.pushKey(key1);
17+
parser.pushKey(key2);
18+
parser.push(increment.toString());
19+
},
1820
}),
1921
},
2022
});

examples/managing-json.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ results = await client.json.get('noderedis:jsondata', {
5757
});
5858

5959
// Goldie is 3 years old now.
60-
console.log(`Goldie is ${JSON.stringify(results[0])} years old now.`);
60+
console.log(`Goldie is ${JSON.parse(results)[0]} years old now.`);
6161

6262
// Add a new pet...
6363
await client.json.arrAppend('noderedis:jsondata', '$.pets', {
@@ -68,9 +68,14 @@ await client.json.arrAppend('noderedis:jsondata', '$.pets', {
6868
});
6969

7070
// How many pets do we have now?
71-
const numPets = await client.json.arrLen('noderedis:jsondata', '$.pets');
71+
const numPets = await client.json.arrLen('noderedis:jsondata', { path: '$.pets' });
7272

7373
// We now have 4 pets.
7474
console.log(`We now have ${numPets} pets.`);
7575

76-
client.destroy();
76+
const rex = { name: 'Rex', species: 'dog', age: 3, isMammal: true }
77+
78+
const index = await client.json.arrIndex( 'noderedis:jsondata', '$.pets', rex);
79+
console.log(`Rex is at index ${index}`);
80+
81+
client.close();

examples/package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
{
22
"name": "node-redis-examples",
33
"version": "1.0.0",
4-
"description": "node-redis 4 example script",
4+
"description": "node-redis 5 example script",
55
"main": "index.js",
66
"private": true,
77
"type": "module",
88
"dependencies": {
9-
"redis": "../packages/client"
9+
"redis": "../packages/redis"
1010
}
1111
}
1212

examples/search-hashes.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// This example demonstrates how to use RediSearch to index and query data
22
// stored in Redis hashes.
33

4-
import { createClient, SchemaFieldTypes } from 'redis';
4+
import { createClient, SCHEMA_FIELD_TYPE } from 'redis';
55

66
const client = createClient();
77

@@ -12,11 +12,11 @@ try {
1212
// Documentation: https://redis.io/commands/ft.create/
1313
await client.ft.create('idx:animals', {
1414
name: {
15-
type: SchemaFieldTypes.TEXT,
15+
type: SCHEMA_FIELD_TYPE.TEXT,
1616
SORTABLE: true
1717
},
18-
species: SchemaFieldTypes.TAG,
19-
age: SchemaFieldTypes.NUMERIC
18+
species: SCHEMA_FIELD_TYPE.TAG,
19+
age: SCHEMA_FIELD_TYPE.NUMERIC
2020
}, {
2121
ON: 'HASH',
2222
PREFIX: 'noderedis:animals'

examples/search-json.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// https://redis.io/docs/stack/search/
44
// https://redis.io/docs/stack/json/
55

6-
import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis';
6+
import { createClient, SCHEMA_FIELD_TYPE, FT_AGGREGATE_GROUP_BY_REDUCERS, FT_AGGREGATE_STEPS } from 'redis';
77

88
const client = createClient();
99

@@ -14,19 +14,19 @@ await client.connect();
1414
try {
1515
await client.ft.create('idx:users', {
1616
'$.name': {
17-
type: SchemaFieldTypes.TEXT,
17+
type: SCHEMA_FIELD_TYPE.TEXT,
1818
SORTABLE: true
1919
},
2020
'$.age': {
21-
type: SchemaFieldTypes.NUMERIC,
21+
type: SCHEMA_FIELD_TYPE.NUMERIC,
2222
AS: 'age'
2323
},
2424
'$.coins': {
25-
type: SchemaFieldTypes.NUMERIC,
25+
type: SCHEMA_FIELD_TYPE.NUMERIC,
2626
AS: 'coins'
2727
},
2828
'$.email': {
29-
type: SchemaFieldTypes.TAG,
29+
type: SCHEMA_FIELD_TYPE.TAG,
3030
AS: 'email'
3131
}
3232
}, {
@@ -119,13 +119,13 @@ console.log(
119119
JSON.stringify(
120120
await client.ft.aggregate('idx:users', '*', {
121121
STEPS: [{
122-
type: AggregateSteps.GROUPBY,
122+
type: FT_AGGREGATE_STEPS.GROUPBY,
123123
REDUCE: [{
124-
type: AggregateGroupByReducers.AVG,
124+
type: FT_AGGREGATE_GROUP_BY_REDUCERS.AVG,
125125
property: 'age',
126126
AS: 'averageAge'
127127
}, {
128-
type: AggregateGroupByReducers.SUM,
128+
type: FT_AGGREGATE_GROUP_BY_REDUCERS.SUM,
129129
property: 'coins',
130130
AS: 'totalCoins'
131131
}]

examples/search-knn.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// Inspired by RediSearch Python tests:
55
// https://github.com/RediSearch/RediSearch/blob/06e36d48946ea08bd0d8b76394a4e82eeb919d78/tests/pytests/test_vecsim.py#L96
66

7-
import { createClient, SchemaFieldTypes, VectorAlgorithms } from 'redis';
7+
import { createClient, SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM } from 'redis';
88

99
const client = createClient();
1010

@@ -15,8 +15,8 @@ try {
1515
// Documentation: https://redis.io/docs/stack/search/reference/vectors/
1616
await client.ft.create('idx:knn-example', {
1717
v: {
18-
type: SchemaFieldTypes.VECTOR,
19-
ALGORITHM: VectorAlgorithms.HNSW,
18+
type: SCHEMA_FIELD_TYPE.VECTOR,
19+
ALGORITHM: SCHEMA_VECTOR_FIELD_ALGORITHM.HNSW,
2020
TYPE: 'FLOAT32',
2121
DIM: 2,
2222
DISTANCE_METRIC: 'COSINE'

examples/set-scan.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,14 @@ const client = createClient();
88
await client.connect();
99

1010
const setName = 'setName';
11-
for await (const member of client.sScanIterator(setName)) {
12-
console.log(member);
11+
12+
for await (const members of client.sScanIterator(setName)) {
13+
console.log('Batch of members:', members);
14+
15+
// Process each member in the batch if needed
16+
for (const member of members) {
17+
console.log('Individual member:', member);
18+
}
1319
}
1420

15-
client.destroy();
21+
client.close();

examples/sorted-set.js

+25-3
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,30 @@ await client.zAdd('mysortedset', [
2424
// Get all of the values/scores from the sorted set using
2525
// the scan approach:
2626
// https://redis.io/commands/zscan
27-
for await (const memberWithScore of client.zScanIterator('mysortedset')) {
28-
console.log(memberWithScore);
27+
for await (const membersWithScores of client.zScanIterator('mysortedset')) {
28+
console.log('Batch of members with scores:', membersWithScores);
29+
30+
for (const memberWithScore of membersWithScores) {
31+
console.log('Individual member with score:', memberWithScore);
32+
}
2933
}
3034

31-
client.destroy();
35+
await client.zAdd('anothersortedset', [
36+
{
37+
score: 99,
38+
value: 'Ninety Nine'
39+
},
40+
{
41+
score: 102,
42+
value: 'One Hundred and Two'
43+
}
44+
]);
45+
46+
// Intersection of two sorted sets
47+
const intersection = await client.zInter([
48+
{ key: 'mysortedset', weight: 1 },
49+
{ key: 'anothersortedset', weight: 1 }
50+
]);
51+
console.log('Intersection:', intersection);
52+
53+
client.close();

examples/stream-consumer-group.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
//
2121
// $ node stream-consumer-group.js consumer2
2222

23-
import { createClient, commandOptions } from 'redis';
23+
import { createClient } from 'redis';
2424

2525
const client = createClient();
2626

@@ -46,14 +46,13 @@ try {
4646

4747
console.log(`Starting consumer ${consumerName}.`);
4848

49+
const pool = client.createPool();
50+
4951
while (true) {
5052
try {
5153
// https://redis.io/commands/xreadgroup/
52-
let response = await client.xReadGroup(
53-
commandOptions({
54-
isolated: true
55-
}),
56-
'myconsumergroup',
54+
let response = await pool.xReadGroup(
55+
'myconsumergroup',
5756
consumerName, [
5857
// XREADGROUP can read from multiple streams, starting at a
5958
// different ID for each...
@@ -91,9 +90,10 @@ while (true) {
9190
// stream entry.
9291
// https://redis.io/commands/xack/
9392
const entryId = response[0].messages[0].id;
94-
await client.xAck('mystream', 'myconsumergroup', entryId);
93+
const ackResult = await pool.xAck('mystream', 'myconsumergroup', entryId);
9594

96-
console.log(`Acknowledged processing of entry ${entryId}.`);
95+
// ackResult will be 1 if the message was successfully acknowledged, 0 otherwise
96+
console.log(`Acknowledged processing of entry ${entryId}. Result: ${ackResult}`);
9797
} else {
9898
// Response is null, we have read everything that is
9999
// in the stream right now...

examples/time-series.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Requires the RedisTimeSeries module: https://redis.io/docs/stack/timeseries/
33

44
import { createClient } from 'redis';
5-
import { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } from '@redis/time-series';
5+
import { TIME_SERIES_DUPLICATE_POLICIES, TIME_SERIES_ENCODING, TIME_SERIES_AGGREGATION_TYPE } from '@redis/time-series';
66

77
const client = createClient();
88

@@ -14,8 +14,8 @@ try {
1414
// https://redis.io/commands/ts.create/
1515
const created = await client.ts.create('mytimeseries', {
1616
RETENTION: 86400000, // 1 day in milliseconds
17-
ENCODING: TimeSeriesEncoding.UNCOMPRESSED, // No compression
18-
DUPLICATE_POLICY: TimeSeriesDuplicatePolicies.BLOCK // No duplicates
17+
ENCODING: TIME_SERIES_ENCODING.UNCOMPRESSED, // No compression
18+
DUPLICATE_POLICY: TIME_SERIES_DUPLICATE_POLICIES.BLOCK // No duplicates
1919
});
2020

2121
if (created === 'OK') {
@@ -74,7 +74,7 @@ try {
7474
const rangeResponse = await client.ts.range('mytimeseries', fromTimestamp, toTimestamp, {
7575
// Group into 10 second averages.
7676
AGGREGATION: {
77-
type: TimeSeriesAggregationType.AVERAGE,
77+
type: TIME_SERIES_AGGREGATION_TYPE.AVG,
7878
timeBucket: 10000
7979
}
8080
});
@@ -119,4 +119,4 @@ try {
119119
console.error(e);
120120
}
121121

122-
client.destroy();
122+
client.close();

0 commit comments

Comments
 (0)