-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightdb.js
76 lines (63 loc) · 2.03 KB
/
lightdb.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
74
75
76
const { MemoryStore } = require("./store/memorystore");
const Query = require('./query');
const bisync = require('./bisync');
const LightDBSyncAdapter = require('./syncadapters/lightdbsyncadapter');
class LightDBError extends Error { }
class LightDB {
constructor(table, options) {
this._table = table;
this.options = options || {};
this._store = this.options.store || new MemoryStore(table);
this._changes = [];
}
/** Get LightDB instance for attachments table
* @returns {LightDB}
*/
get_attachmentsDB() {
return new LightDB(this._table + "_attachments", this.options);
}
async get(id) {
if (!id) return null;
return this._store.get(id);
}
async list() {
return await this._store.list();
}
async has(id) {
return (await this._store.list()).filter(x => x._id == id).length > 0;
}
async put(object) {
var result = null;
var update = false;
if (object._id) update = true;
if (update) {
result = await this._store.put(object);
this._changes.push({ _id: object._id, _action: 'change', timestamp: Date.now() });
}
else {
result = await this._store.new(object);
this._changes.push({ _id: object._id, _action: 'add', timestamp: Date.now() });
}
return result;
}
async del(id) {
await this._store.del(id);
this._changes.push({ _id: id, _action: 'remove', timestamp: Date.now() });
return;
}
async get_blob(blob_id) {
return await this._store.get_blob(blob_id);
}
async put_blob(stream) {
return await this._store.put_blob(stream);
}
async sync(remotedb) {
var localadapter = new LightDBSyncAdapter(this);
var remoteadapter = new LightDBSyncAdapter(remotedb);
return await bisync.sync(localadapter, remoteadapter, this._changes);
}
query() {
return new Query(this);
}
}
module.exports = { LightDB, LightDBError, Query };