|
1 | | -// An example explaining how to add values to a set and how to retrive them |
| 1 | +// An example explaining how to add values to a set and how to retrieve them |
2 | 2 |
|
3 | 3 | import { createClient } from 'redis'; |
4 | 4 |
|
5 | 5 | const client = createClient(); |
6 | 6 | await client.connect(); |
7 | 7 |
|
8 | | -const setName = "user1:favorites"; |
| 8 | +const SET_NAME = 'user1:favorites'; |
9 | 9 |
|
10 | | -// if you try to add any data of type other than string you will get an error saying `Invalid argument type` |
11 | | -// so before adding make sure the value is of type string or convert it using toString() method |
| 10 | +// add an item to the set |
| 11 | +// set members can only be `string | Buffer` so make sure to convert values if needed, |
12 | 12 | // https://redis.io/commands/sadd/ |
13 | | -await client.SADD(setName, "1"); |
| 13 | +await client.SADD(SET_NAME, '1'); |
14 | 14 |
|
15 | | -// retrieve values of the set defined |
| 15 | +// retrieve all the members of the set in one batch (be careful using it with "large" sets) |
16 | 16 | // https://redis.io/commands/smembers/ |
17 | | -const favorites = await client.SMEMBERS(setName); |
| 17 | +const favorites = await client.SMEMBERS(SET_NAME); |
18 | 18 | for (const favorite of favorites) { |
19 | 19 | console.log(favorite); |
20 | 20 | } |
21 | 21 |
|
22 | | -// alternate way to retrieve data from set |
| 22 | +// retrieve all the members of the set in batches using SSCAN (useful with large sets) |
| 23 | +// https://redis.io/commands/sscan/ |
23 | 24 | for await (const member of client.sScanIterator(setName)) { |
24 | 25 | console.log(member); |
25 | 26 | } |
26 | 27 |
|
27 | | -// another alternate way to retrieve values from the set |
28 | | -// https://redis.io/commands/sscan/ |
29 | | -let iCursor = 0; |
30 | | -do { |
31 | | - const { cursor, members } = await client.SSCAN(setName, iCursor); |
32 | | - members.forEach((member) => { |
33 | | - console.log(member); |
34 | | - }); |
35 | | - iCursor = cursor; |
36 | | -} while (iCursor !== 0) |
37 | | - |
38 | | - |
39 | 28 | await client.quit(); |
0 commit comments