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

85 lines
2.0 KiB
JavaScript
Raw Normal View History

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-03-30 15:52:48 +05:00
constructor(context, type, eventManager) {
super(context, type, eventManager);
this.type = type;
this.map = new Map();
this.items = undefined;
2022-03-30 15:52:48 +05:00
// this.eventManager = eventManager;
// 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
2022-03-28 10:22:26 +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;
// }
// }
2022-02-08 13:16:41 +05:00
this.map = new MapStub.Map(data, this.type);
}
async clear() {
await super.clear();
this.map.clear();
this.invalidateCache();
}
async updateItem(item) {
await super.updateItem(item);
this.map.set(item.id, item);
this.invalidateCache();
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);
this.invalidateCache();
2021-01-13 13:02:35 +05:00
}
2020-03-23 15:06:12 +05:00
getRaw() {
return Array.from(this.map.values());
2020-03-23 15:06:12 +05:00
}
getItems(map = undefined) {
if (this.items) return this.items;
this.items = [];
this.map.forEach((value) => {
if (!value || value.deleted || !value.id) return;
value = map ? map(value) : value;
this.items.push(value);
2020-03-01 11:37:59 +05:00
});
this.items.sort((a, b) => b.dateCreated - a.dateCreated);
return this.items;
}
invalidateCache() {
this.items = undefined;
2020-02-02 20:07:11 +05:00
}
}