From d57960a4c6853410431a3c9a766745a1d0e3b0a3 Mon Sep 17 00:00:00 2001 From: Zihua Li Date: Sun, 27 Mar 2022 10:41:00 +0800 Subject: [PATCH] docs: add examples for ttl commands --- README.md | 3 +++ examples/hash.js | 3 +++ examples/ttl.js | 30 ++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 examples/ttl.js diff --git a/README.md b/README.md index 27b40c56..13a62831 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ redis.set("mykey", "hello", "EX", 10); See the `examples/` folder for more examples. For example: +* [TTL](examples/ttl.js) * [Strings](examples/string.js) * [Hashes](examples/hash.js) * [Lists](examples/list.js) @@ -163,6 +164,8 @@ See the `examples/` folder for more examples. For example: * [Streams](examples/stream.js) * [Redis Modules](examples/module.js) e.g. RedisJSON +All Redis commands are supported. See [the documentation](http://luin.github.io/ioredis/classes/default.html) for details. + ## Connect to Redis When a new `Redis` instance is created, diff --git a/examples/hash.js b/examples/hash.js index d91c39b2..53b24fd5 100644 --- a/examples/hash.js +++ b/examples/hash.js @@ -30,6 +30,9 @@ async function main() { await redis.hincrby("user-hash", "age", 1); const newAge = await redis.hget("user-hash", "age"); console.log(newAge); // 21 + + await redis.hsetnx("user-hash", "age", 23); + console.log(await redis.hget("user-hash", "age")); // 21, as the field "age" already exists. } main(); diff --git a/examples/ttl.js b/examples/ttl.js new file mode 100644 index 00000000..4ae88995 --- /dev/null +++ b/examples/ttl.js @@ -0,0 +1,30 @@ +const Redis = require("ioredis"); +const redis = new Redis(); + +async function main() { + await redis.set("foo", "bar"); + await redis.expire("foo", 10); // 10 seconds + console.log(await redis.ttl("foo")); // a number smaller or equal to 10 + + await redis.set("foo", "bar", "EX", 20); + console.log(await redis.ttl("foo")); // a number smaller or equal to 20 + + // expireat accepts unix time in seconds. + await redis.expireat("foo", Math.round(Date.now() / 1000) + 30); + console.log(await redis.ttl("foo")); // a number smaller or equal to 30 + + // "XX" and other options are available since Redis 7.0. + await redis.expireat("foo", Math.round(Date.now() / 1000) + 40, "XX"); + console.log(await redis.ttl("foo")); // a number smaller or equal to 40 + + // expiretime is available since Redis 7.0. + console.log(new Date((await redis.expiretime("foo")) * 1000)); + + await redis.pexpire("foo", 10 * 1000); // unit is millisecond for pexpire. + console.log(await redis.ttl("foo")); // a number smaller or equal to 10 + + await redis.persist("foo"); // Remove the existing timeout on key "foo" + console.log(await redis.ttl("foo")); // -1 +} + +main();