Created
June 4, 2013 06:08
-
-
Save zeropaper/5703910 to your computer and use it in GitHub Desktop.
Very very simple "sync" for Backbone & Redis
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
/*jslint indent: 2, node: true*/ | |
'use strict'; | |
var _ = require('underscore'); | |
var redis = require('redis'); | |
module.exports = function(options) { | |
options = _.clone(options || {}); | |
_.defaults(options, { | |
port: 6379, | |
host: '127.0.0.1', | |
options: {}, | |
}); | |
var client = redis.createClient(options.port, options.host, options.options); | |
if (options.flush) { | |
options.log('warn', 'flushing DB'); | |
client.flushdb(); | |
} | |
function sync(method, model, opts) { | |
opts = opts || {}; | |
function cb(err, result) { | |
if (err && opts.error) { | |
return opts.error(null, 'error', err); | |
} | |
if (opts.success) { | |
return opts.success(result, 'success'); | |
} | |
} | |
switch (method) { | |
case 'create': | |
case 'update': | |
case 'patch': | |
client.hmset(model.id, model.toJSON(), cb); | |
break; | |
case 'delete': | |
client.hgetall(model.id, function(err, result) { | |
if (err) { | |
return cb(err); | |
} | |
client.hdel([model.id].concat(_.keys(result)), cb); | |
}); | |
break; | |
case 'read': | |
client.hgetall(model.id, cb); | |
break; | |
} | |
} | |
sync.client = client; | |
return sync; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment