Last active
August 29, 2015 14:02
-
-
Save medikoo/e11a8ce61303a996feab to your computer and use it in GitHub Desktop.
dbjs persistent layer handler
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
'use strict'; | |
var Database = require('dbjs') | |
, serialize = require('dbjs/_setup/serialize/value') | |
, unserialize = require('dbjs/_setup/unserialize/value') | |
, DbjsEvent = require('dbjs/_setup/event') | |
, db = new Database(); | |
// 1. Save | |
// Below configuration also handles changes made to schema, if that's an issue, either you may | |
// register this listener after schema is loaded or within listener filter which data you | |
// want to pass to persisent layer. | |
db.objects.on('update', function (event) { | |
// Get serialized id | |
var id = event.object.__valueId__; | |
// Get serialized modification timestamp (microseconds accuracy) | |
var stamp = String(event.stamp); | |
// Get serialized value | |
var value = serialize(event.value); | |
// Either all events can be saved to persistent layer, or you can remove deleted records and | |
// update others (this is not perfectly safe if you work with offline clients that can send | |
// updates after some period of time) | |
if (!value) { | |
// Delete | |
} else { | |
// Create or update | |
} | |
}); | |
// 2. Restore | |
// `data` is collection of data you get from your persistent layer | |
data.forEach(function (item) { | |
var value = unserialize(item.value, db.objects), proto; | |
if (value && value.__id__ && (value.constructor.prototype === value)) { | |
// Value is a constructor prototype, for seamless object creation we'll pass this information to | |
// object unserialize function | |
proto = value.constructor; | |
} | |
new DbjsEvent(db.objects.unserialize(item.id, proto), value, Number(item.stamp)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment