-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloki-msgpack-adapter.js
73 lines (65 loc) · 2.52 KB
/
loki-msgpack-adapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @Author Joscha Rohmann <[email protected]>
* @License MIT
* A "proxy" persistence adapter for LokiJS using msgpack-lite for messagepack encoding.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['msgpack-lite', 'lokijs'], factory);
} else if (typeof exports == 'object') {
module.exports = factory(require('msgpack-lite'), require('lokijs'));
} else {
root.lokiMsgpackAdapter = factory(root.msgpack, root.loki);
}
})(this, function(msgpack, loki) {
if (!msgpack || !loki) {
throw new Error('You have to include lokijs and msgpack-lite for this adapter to work');
}
/**
* constructor for the apapter
* @param {object} options Options object for (currently) adapter compatibility.
*/
function lokiMsgpackAdapter (options) {
this.options = options || {};
// use user provided adapter otherwise default to the Loki built in fs adapter
this.adapter = this.options.adapter || new loki.persistenceAdapters.fs();
if (this.adapter.mode === 'reference') {
throw new Error('Loki Msgpack Adapter does not work with adapters in reference-mode');
}
}
/* using reference as we're serializing to msgpack not json */
lokiMsgpackAdapter.prototype.mode = 'reference';
/**
* saves / exports the database
* @param {string} dbname Will be used as the filename if constructors filename argument is not provided.
* @param {object} dbref Reference to the Loki instance.
* @param {Function} fn Callback function.
*/
lokiMsgpackAdapter.prototype.exportDatabase = function(dbname, dbref, fn) {
var binary;
try {
binary = msgpack.encode(dbref);
} catch (e) {
return fn(e);
}
this.adapter.saveDatabase(dbname, binary, fn);
};
lokiMsgpackAdapter.prototype.deleteDatabase = function () {
this.adapter.deleteDatabase.apply(this.adapter, arguments);
};
/**
* Loads the database from an msgpack file.
* @param {string} dbname Will be used as the filename if the constructors filename argument is not provided.
* @param {Function} fn The callback function.
*/
lokiMsgpackAdapter.prototype.loadDatabase = function(dbname, fn) {
this.adapter.loadDatabase(dbname, function(binary) {
try {
fn(msgpack.decode(binary));
} catch (err) {
fn(err);
}
});
};
return lokiMsgpackAdapter;
});