0

I've coded up some examples for a chat room using redis and node.js, but before I continue on this path, I want to know if this is the best way to be doing it:

var redis = require('redis')
, cache = redis.createClient(cfg.redis_port, cfg.redis_host)


function getUsers(cb){
    cache.select(cfg.redis_db, function(err, status){
        cache.get('chat.users', function(err, data){
            var users = data && JSON.parse(data) || [];

            c.log('get users', users);
            cb(users);
        });
    });
}

function addUser(user, cb){
    getUsers(function(users){
        users.push(user);

        cache.select(cfg.redis_db, function(err, status){
            cache.set('chat.users', JSON.stringify(users), function(){
                c.log('cache set', arguments);

                c.log('add user', user, users);
                cb(users);
            });
        });
    });
}

function removeUser(user, cb){
    getUsers(function(users){
        users = _.reject(users, function(val){
            return user.nick === val.nick;
        });

        cache.select(cfg.redis_db, function(err, status){
            cache.set('chat.users', JSON.stringify(users), function(){
                c.log('cache set', arguments);

                c.log('remove user', user, users);

                cb(users);
            });
        });
    });
}

The reason I ask is it seems rather cumbersome to have to do cache.select all over the place then cache.get.

1 Answer 1

1

In Redis, once the DB is selected, it remains selected until another SELECT is issued. And because the Node Redis client queues commands that are issued before the client is ready, you can do something like this:

var redis = require('redis')
, cache = redis.createClient(cfg.redis_port, cfg.redis_host);

cache.select(cfg.redis_db);

// the rest of your code

It doesn’t look very Node-ish, but it works and is shown (as a comment; easy to miss) in one of the examples on the node-redis home page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.