Created
May 28, 2013 18:09
-
-
Save yocontra/5664803 to your computer and use it in GitHub Desktop.
Loads a JSON object into redis - good for testing. Supports flat keys as well as nested values
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
var redis = require('redis'); | |
var async = require('async'); | |
module.exports = loadRedis; | |
function loadRedis(opts, cb) { | |
var errored = false; | |
var client = redis.createClient(opts.redis.port, opts.redis.host); | |
client.once('error', function (e) { | |
errored = true; | |
cb(e); | |
}); | |
client.on('connect', loadIt); | |
function loadIt() { | |
if (errored) return; // stop if redis failed somehow | |
if (!opts.data) return cb(); | |
async.forEach(Object.keys(opts.data), loadKey.bind(null, opts.data), cb); | |
} | |
function loadKey(data, key, done) { | |
var val = data[key]; | |
// flat value set | |
if (typeof val !== 'object') { | |
client.set(key, val, done); | |
return; | |
} | |
// hash set | |
async.forEach(Object.keys(val), loadNestedKey.bind(null, val, key), done); | |
} | |
function loadNestedKey(data, parent, key, done) { | |
var val = data[key]; | |
if (typeof val === 'object') val = JSON.stringify(val); | |
client.hset(parent, key, val, done); | |
} | |
return client; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment