Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created December 13, 2012 05:57
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 Raynos/4274396 to your computer and use it in GitHub Desktop.
Save Raynos/4274396 to your computer and use it in GitHub Desktop.
var livefeed = require("level-livefeed")
, Model = require("scuttlebutt/model")
, forEach = require("for-each-stream")
module.exports = replicate
function replicate(db, options) {
var feedStream = livefeed(db, options)
, model = Model()
, stream = model.createStream()
, dead = {}
forEach(feedStream, function (chunk) {
var current = model.get(chunk.key)
if (chunk.type === "put" && !current) {
dead[chunk.key] = false
model.set(chunk.key, chunk.value)
} else if (chunk.type === "del" && current) {
model.set(chunk.key, null)
}
})
model.on("update", function (tuple, source) {
if (source === this.id) {
return
}
var key = tuple[0]
, value = tuple[1]
if (value === null && !dead[key]) {
dead[key] = true
db.del(key, error)
} else {
db.put(key, value, error)
}
})
return stream
function error(err) {
if (err) {
return stream.emit("error", err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment