Skip to content

Commit

Permalink
docs: add examples for Redis operations
Browse files Browse the repository at this point in the history
  • Loading branch information
luin committed Mar 13, 2022
1 parent d4a8116 commit c504f5f
Show file tree
Hide file tree
Showing 7 changed files with 184 additions and 1 deletion.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,14 @@ redis.zrange("sortedSet", 0, 2, "WITHSCORES").then((elements) => {
redis.set("mykey", "hello", "EX", 10);
```

See the `examples/` folder for more examples.
See the `examples/` folder for more examples. For example:

* [Strings](examples/string.js)
* [Hashes](examples/hash.js)
* [Lists](examples/list.js)
* [Sets](examples/set.js)
* [Sorted Sets](examples/zset.js)
* [Streams](examples/stream.js)

## Connect to Redis

Expand Down
35 changes: 35 additions & 0 deletions examples/hash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const Redis = require("ioredis");
const redis = new Redis();

async function main() {
const user = {
name: "Bob",
// The field of a Redis Hash key can only be a string.
// We can write `age: 20` here but ioredis will convert it to a string anyway.
age: "20",
description: "I am a programmer",
};

await redis.hmset("user-hash", user);

const name = await redis.hget("user-hash", "name");
console.log(name); // "Bob"

const age = await redis.hget("user-hash", "age");
console.log(age); // "20"

const all = await redis.hgetall("user-hash");
console.log(all); // { age: '20', name: 'Bob', description: 'I am a programmer' }

// or `await redis.hdel("user-hash", "name", "description")`;
await redis.hdel("user-hash", ["name", "description"]);

const exists = await redis.hexists("user-hash", "name");
console.log(exists); // 0 (means false, and if it's 1, it means true)

await redis.hincrby("user-hash", "age", 1);
const newAge = await redis.hget("user-hash", "age");
console.log(newAge); // 21
}

main();
26 changes: 26 additions & 0 deletions examples/list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const Redis = require("ioredis");
const redis = new Redis();

async function main() {
const numbers = [1, 3, 5, 7, 9];
await redis.lpush("user-list", numbers);

const popped = await redis.lpop("user-list");
console.log(popped); // 9

const all = await redis.lrange("user-list", 0, -1);
console.log(all); // [ '7', '5', '3', '1' ]

const position = await redis.lpos("user-list", 5);
console.log(position); // 1

setTimeout(() => {
// `redis` is in the block mode due to `redis.blpop()`,
// so we duplicate a new connection to invoke LPUSH command.
redis.duplicate().lpush("block-list", "hello");
}, 1200);
const blockPopped = await redis.blpop("block-list", 0); // Resolved after 1200ms.
console.log(blockPopped); // [ 'block-list', 'hello' ]
}

main();
19 changes: 19 additions & 0 deletions examples/set.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const Redis = require("ioredis");
const redis = new Redis();

async function main() {
const numbers = [1, 3, 5, 7, 9];
await redis.sadd("user-set", numbers);

const elementCount = await redis.scard("user-set");
console.log(elementCount); // 5

await redis.sadd("user-set", "1");
const newElementCount = await redis.scard("user-set");
console.log(newElementCount); // 5

const isMember = await redis.sismember("user-set", 3);
console.log(isMember); // 1 (means true, and if it's 0, it means false)
}

main();
34 changes: 34 additions & 0 deletions examples/stream.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const Redis = require("ioredis");
const redis = new Redis();
const pub = new Redis();

const processMessage = (message) => {
console.log("Id: %s. Data: %O", message[0], message[1]);
};

async function listenForMessage(lastId = "$") {
// `results` is an array, each element of which corresponds to a key.
// Because we only listen to one key (mystream) here, `results` only contains
// a single element. See more: https://redis.io/commands/xread#return-value
const results = await redis.xread(
"BLOCK",
0,
"STREAMS",
"user-stream",
lastId
);
const [key, messages] = results[0]; // `key` equals to "user-stream"

messages.forEach(processMessage);

// Pass the last id of the results to the next round.
await listenForMessage(messages[messages.length - 1][0]);
}

listenForMessage();

setInterval(() => {
// `redis` is in the block mode due to `redis.xread('BLOCK', ....)`,
// so we use another connection to publish messages.
pub.xadd("user-stream", "*", "name", "John", "age", "20");
}, 1000);
39 changes: 39 additions & 0 deletions examples/string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const Redis = require("ioredis");
const redis = new Redis();

async function main() {
const user = {
name: "Bob",
// The value of a Redis key can not be a number.
// We can write `age: 20` here but ioredis will convert it to a string anyway.
age: "20",
description: "I am a programmer",
};

await redis.mset(user);

const name = await redis.get("name");
console.log(name); // "Bob"

const age = await redis.get("age");
console.log(age); // "20"

const all = await redis.mget("name", "age", "description");
console.log(all); // [ 'Bob', '20', 'I am a programmer' ]

// or `await redis.del("name", "description")`;
await redis.del(["name", "description"]);

const exists = await redis.exists("name");
console.log(exists); // 0 (means false, and if it's 1, it means true)

await redis.incrby("age", 1);
const newAge = await redis.get("age");
console.log(newAge); // 21

await redis.set("key_with_ttl", "hey", "EX", 1000);
const ttl = await redis.ttl("key_with_ttl");
console.log(ttl); // a number smaller or equal to 1000
}

main();
23 changes: 23 additions & 0 deletions examples/zset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const Redis = require("ioredis");
const redis = new Redis();

async function main() {
const scores = [
{ name: "Bob", score: 80 },
{ name: "Jeff", score: 59.5 },
{ name: "Tom", score: 100 },
{ name: "Alex", score: 99.5 },
];
await redis.zadd(
"user-zset",
...scores.map(({ name, score }) => [score, name])
);

console.log(await redis.zrange("user-zset", 2, 3)); // [ 'Alex', 'Tom' ]
console.log(await redis.zrange("user-zset", 2, 3, "WITHSCORES")); // [ 'Alex', '99.5', 'Tom', '100' ]
console.log(await redis.zrange("user-zset", 2, 3, "REV")); // [ 'Bob', 'Jeff' ]
console.log(await redis.zrange("user-zset", 80, 100, "BYSCORE")); // [ 'Bob', 'Alex', 'Tom' ]
console.log(await redis.zrange("user-zset", 2, 3)); // [ 'Alex', 'Tom' ]
}

main();

0 comments on commit c504f5f

Please sign in to comment.