Files
notesnook/packages/core/database/cached-collection.js

75 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-02-02 20:07:11 +05:00
import Indexer from "./indexer";
2020-03-01 11:37:59 +05:00
import sort from "fast-sort";
2020-02-02 20:07:11 +05:00
export default class CachedCollection {
2020-02-02 20:07:11 +05:00
constructor(context, type) {
2020-02-03 12:03:07 +05:00
this.map = new Map();
this.indexer = new Indexer(context, type);
this.transactionOpen = false;
2020-02-02 20:07:11 +05:00
}
2020-02-03 12:03:07 +05:00
async init() {
await this.indexer.init();
for (let id of this.indexer.indices) {
this.map.set(id, await this.indexer.read(id));
}
2020-02-02 20:07:11 +05:00
}
/**
*
* @param {Promise} ops
*/
transaction(ops) {
this.transactionOpen = true;
return ops().then(() => Promise.resolve((this.transactionOpen = false)));
}
2020-02-02 20:07:11 +05:00
async addItem(item) {
if (this.transactionOpen) return;
if (!item.id) throw new Error("The item must contain the id field.");
2020-02-03 12:03:07 +05:00
let exists = this.map.has(item.id);
if (!exists) {
2020-02-11 16:28:28 +05:00
item.dateCreated = item.dateCreated || Date.now();
2020-02-12 02:09:08 +05:00
}
await this.updateItem(item);
if (!exists) {
2020-02-03 12:03:07 +05:00
await this.indexer.index(item.id);
}
}
async updateItem(item) {
if (this.transactionOpen) return;
if (!item.id) throw new Error("The item must contain the id field.");
2020-02-11 16:28:28 +05:00
// if item is newly synced, remote will be true.
item.dateEdited = item.remote ? item.dateEdited : Date.now();
// the item has become local now, so remove the flag.
delete item.remote;
2020-02-03 12:03:07 +05:00
this.map.set(item.id, item);
await this.indexer.write(item.id, item);
2020-02-02 20:07:11 +05:00
}
async removeItem(id) {
if (this.transactionOpen) return;
await this.indexer.deindex(id);
await this.indexer.remove(id);
this.map.delete(id);
2020-02-02 20:07:11 +05:00
}
2020-02-06 16:46:23 +05:00
exists(id) {
return this.map.has(id);
}
2020-02-03 12:03:07 +05:00
getItem(id) {
return this.map.get(id);
2020-02-02 20:07:11 +05:00
}
2020-02-03 12:03:07 +05:00
getAllItems() {
2020-02-02 20:07:11 +05:00
let items = [];
2020-03-01 11:37:59 +05:00
this.map.forEach(value => {
2020-02-03 12:03:07 +05:00
items[items.length] = value;
2020-03-01 11:37:59 +05:00
});
return sort(items).desc(u => u.dateCreated);
2020-02-02 20:07:11 +05:00
}
}