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

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-03-01 11:37:59 +05:00
import sort from "fast-sort";
import IndexedCollection from "./indexed-collection";
import MapStub from "../utils/map";
2020-02-02 20:07:11 +05:00
export default class CachedCollection extends IndexedCollection {
2022-02-08 13:16:41 +05:00
constructor(context, type, encryptionKeyFactory) {
super(context, type, encryptionKeyFactory);
this.type = type;
this.map = new Map();
2022-02-08 13:16:41 +05:00
this.encryptionKeyFactory = encryptionKeyFactory;
}
2020-02-03 12:03:07 +05:00
async init() {
await super.init();
2022-02-08 13:16:41 +05:00
let data = await this.indexer.readMulti(this.indexer.indices);
if (this.map && this.map.dispose) this.map.dispose();
2022-02-08 13:16:41 +05:00
const encryptionKey =
this.encryptionKeyFactory && (await this.encryptionKeyFactory());
if (encryptionKey) {
for (let item of data) {
const [_key, value] = item;
const decryptedValue = JSON.parse(
await this.indexer.decrypt(encryptionKey, value)
);
item[1] = decryptedValue;
}
}
this.map = new MapStub.Map(data, this.type);
}
async clear() {
await super.clear();
this.map.clear();
}
async updateItem(item) {
await super.updateItem(item);
this.map.set(item.id, item);
2020-02-02 20:07:11 +05:00
}
2020-02-06 16:46:23 +05:00
exists(id) {
return this.map.has(id) && !this.map.get(id).deleted;
}
2021-02-16 16:56:06 +05:00
has(id) {
return this.map.has(id);
}
getItem(id) {
return this.map.get(id);
2020-02-02 20:07:11 +05:00
}
2021-01-13 13:02:35 +05:00
async deleteItem(id) {
this.map.delete(id);
await super.deleteItem(id);
}
2020-03-23 15:06:12 +05:00
getRaw() {
return Array.from(this.map.values());
2020-03-23 15:06:12 +05:00
}
getItems(sortFn = (u) => u.dateCreated, manipulate = (item) => item) {
2020-02-02 20:07:11 +05:00
let items = [];
this.map.forEach((value) => {
if (!value || value.deleted || !value.id) return;
value = manipulate ? manipulate(value) : value;
items.push(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
}
}