Last active
August 29, 2015 14:25
-
-
Save bberry6/e620b4a4df450d0f0d2e to your computer and use it in GitHub Desktop.
get an object from redis, modify contents, and set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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