Skip to content

Instantly share code, notes, and snippets.

@nasser
Last active August 29, 2015 14:12
Show Gist options
  • Save nasser/145b44c0c6ced7960fca to your computer and use it in GitHub Desktop.
Save nasser/145b44c0c6ced7960fca to your computer and use it in GitHub Desktop.
Git-like in-memory object store
// db
var crypto = require("crypto"),
zlib = require("zlib"),
fs = require("fs");
var Oddball = function(hash, digest) {
this.hash = hash;
this.digest = digest;
this.data = {};
this.refs = {};
}
Oddball.prototype.hashfn = function(data) {
return crypto.createHash(this.hash).update(data).digest(this.digest);
}
Oddball.prototype.store = function(str) {
var hash = this.hashfn(str);
this.data[hash] = str;
return hash;
};
Oddball.prototype.storeObject = function(obj) {
return this.store(JSON.stringify(obj));
}
Oddball.prototype.retrieve = function(hash) {
return hash ? this.data[hash] || this.data[this.refs[hash]] : null;
}
Oddball.prototype.retrieveObject = function(hash) {
return JSON.parse(this.retrieve(hash));
}
Oddball.prototype.write = function(filename, cb) {
zlib.gzip(JSON.stringify(this), function(err, res) {
if(err) throw err;
fs.writeFile(filename, res, cb);
});
}
Oddball.read = function(filename, cb) {
fs.readFile(filename, null, function(err, data) {
if(err) throw err;
zlib.gunzip(data, function(err, data) {
var o = JSON.parse(data.toString())
o.__proto__ = Oddball.prototype;
if(cb) cb(o);
});
});
}
// usage
var odb = new Oddball("sha1", "hex");
odb.refs.head = odb.storeObject( {parent: null, timestamp:Date.now(), body:odb.store("first")} );
odb.refs.head = odb.storeObject( {parent: odb.refs.head, timestamp:Date.now(), body:odb.store("second")} );
odb.refs.head = odb.storeObject( {parent: odb.refs.head, timestamp:Date.now(), body:odb.store("third")} );
var o = odb.retrieveObject("head");
while(o) {
console.log(odb.retrieve(o.body));
o = odb.retrieveObject(o.parent);
}
console.log(JSON.stringify(odb))
odb.write("foo.odd", function() {
Oddball.read("foo.odd", function(odb) {
console.log(odb.retrieveObject("head"));
var o = odb.retrieveObject("head");
while(o) {
console.log(odb.retrieve(o.body));
o = odb.retrieveObject(o.parent);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment