Skip to content

Instantly share code, notes, and snippets.

@bberry6
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bberry6/e620b4a4df450d0f0d2e to your computer and use it in GitHub Desktop.
Save bberry6/e620b4a4df450d0f0d2e to your computer and use it in GitHub Desktop.
get an object from redis, modify contents, and set
function getSet(key, obj, transmute){
return new Bluebird(function(resolve, reject){
function setAtomic(key, obj, count){
var counts = count;
var atomicClient = baseRedis.createClient();
// lock the key
atomicClient.watch(key);
// get the object
atomicClient.hgetall(key, function(o){
if(!o){
return {};
}
// parse the objects values
o = parseObject(o);
// TODO: make the function async?
var newO = transmute(o);
// set each key using the new object (after transmutation)
var chain = Object.keys(newO).reduce(function(ch, field){
var val = typeof newO[field] === 'string' ? newO[field] : JSON.stringify(newO[field]);
return ch.hset(key, field, val);
}, atomicClient.multi());
// TODO: Delete keys?
// finish the transaction
chain.exec(function(err, results){
atomicClient.quit();
// transaction failed, try again
if(results === null && counts < 10){
setAtomic(key, obj, counts++);
}
// too many failures
if(counts >= 10){
return reject(new Error("Could not complete transaction"));
}
if(err){
return reject(err);
}
return resolve(results);
});
});
}
setAtomic(key, obj, 0);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment