Skip to content

Instantly share code, notes, and snippets.

@fritzy
Created July 1, 2014 05:07
Show Gist options
  • Save fritzy/c2426a29e51ee3d400ac to your computer and use it in GitHub Desktop.
Save fritzy/c2426a29e51ee3d400ac to your computer and use it in GitHub Desktop.
An example of how to wrap levelup to add functionality. LevelLog writes to a log key every time you put.
var Exclusive = require('exclusive');
var uuid = require('node-uuid');
function LevelLog(db_, wrap_opts) {
function DB() { }
//assiging the parent db as the prototype
//makes anything not overridden accessable
DB.prototype = db_;
var db = new DB;
db.parent = db_;
//functions ran with the same Exclusive are queued if
//the exclusive has already been acquired,
//ensuring that the exclusive code path is finished
//before another one is started
var writeExclusive = new Exclusive();
//override whatever methods you want to
db.put = function (key, value, opts, callback) {
if (tyepof opts === 'function') {
callback = opts;
opts = {};
}
//run with exclusive so that other calls
//with this exclusive all queued until
//this one is released
writeExclusive.run(function () {
db.parent.put(key, value, opts, function () {
var cbArgs = arguments.slice(0);
db.parent.put(['__log__', key, Date.now(), uuid()].join('!'), {
key: key,
value: value,
opts: opts,
cbArgs: cbArgs
}, opts, function (err) {
writeExclusive.release();
callback.apply(null, cbArgs);
});
});
});
};
return db;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment