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

88 lines
2.1 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();
2020-03-09 10:45:39 +05:00
const data = await this.indexer.readMulti(this.indexer.indices);
2020-03-09 11:11:09 +05:00
if (data.length > 0) this.map = new Map(data);
2020-02-02 20:07:11 +05:00
}
clear = () => {
this.map.clear();
};
/**
*
* @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;
const deletedItem = {
id,
deleted: true,
dateEdited: Date.now(),
dateCreated: Date.now(),
};
await this.indexer.write(id, deletedItem);
this.map.set(id, deletedItem);
2020-02-02 20:07:11 +05:00
}
2020-02-06 16:46:23 +05:00
exists(id) {
2020-03-23 13:22:28 +05:00
return this.map.has(id) && !this.map.get(id).deleted;
2020-02-06 16:46:23 +05:00
}
2020-02-03 12:03:07 +05:00
getItem(id) {
return this.map.get(id);
2020-02-02 20:07:11 +05:00
}
2020-03-23 15:06:12 +05:00
getRaw() {
return Array.from(this.map.values());
}
getAllItems(sortFn = (u) => u.dateCreated) {
2020-02-02 20:07:11 +05:00
let items = [];
this.map.forEach((value) => {
2020-03-23 15:06:12 +05:00
if (value.deleted) return;
2020-02-03 12:03:07 +05:00
items[items.length] = value;
2020-03-01 11:37:59 +05:00
});
2020-03-01 11:42:30 +05:00
return sort(items).desc(sortFn);
2020-02-02 20:07:11 +05:00
}
}