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.