Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add more detail to the basic example #1043

Merged
merged 5 commits into from Feb 19, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 20 additions & 5 deletions examples/basic_operations.js
@@ -1,27 +1,42 @@
"use strict";

var Redis = require("ioredis");
var redis = new Redis();
const Redis = require("ioredis");
const redis = new Redis(process.env.redisPort, process.env.redisEndpoint, {password: process.env.redisPW});
barakplasma marked this conversation as resolved.
Show resolved Hide resolved

// ioredis supports all Redis commands:
redis.set("foo", "bar");
redis.set("foo", "bar"); // returns promise which resolves to string, "Ok"
barakplasma marked this conversation as resolved.
Show resolved Hide resolved

// the format is: redis[SOME_REDIS_COMMAND_IN_LOWERCASE](ARGUMENTS_ARE_JOINED_INTO_COMMAND_STRING)
// the js: ` redis.set("mykey", "Hello") ` is equivalent to the cli: ` redis> SET mykey "Hello" `

// ioredis supports the node.js callback style
redis.get("foo", function(err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
console.log(result); // Promise resolves to "bar"
}
});

redis.del("foo");

// Or using a promise if the last argument isn't a function
// Or ioredis returns a promise if the last argument isn't a function
redis.get("foo").then(function(result) {
console.log(result);
});

// Arguments to commands are flattened, so the following are the same:
redis.sadd("set", 1, 3, 5, 7);
redis.sadd("set", [1, 3, 5, 7]);
redis.spop("set"); // Promise resolves to "5" or another item in the set

// Most responses are strings, or arrays of strings
redis.zadd("sortedSet", 1, "one", 2, "dos", 4, "quatro", 3, "three")
console.log(redis.zrange("sortedSet", 0, 2, "WITHSCORES")); // Promise resolves to ["one", "1", "dos", "2", "three", "3"] as if the command was ` redis> ZRANGE sortedSet 0 2 WITHSCORES `
barakplasma marked this conversation as resolved.
Show resolved Hide resolved

// Some responses have transformers to JS values
redis.hset("myhash", "field1", "Hello");
redis.hgetall("myhash").then(res => console.log(res)); // Promise resolves to Object {field1: "Hello"} rather than a string, or array of strings

// All arguments are passed directly to the redis server:
redis.set("key", 100, "EX", 10);
Expand Down