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

60 lines
1.2 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 {
constructor(context, type) {
super(context, type);
this.type = type;
this.map;
}
2020-02-03 12:03:07 +05:00
async init() {
await super.init();
const data = await this.indexer.readMulti(this.indexer.indices);
if (this.map && this.map.dispose) this.map.dispose();
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() {
if (!this.map) return [];
return Array.from(this.map.values());
2020-03-23 15:06:12 +05:00
}
getItems(sortFn = (u) => u.dateCreated) {
2020-02-02 20:07:11 +05:00
let items = [];
this.map.forEach((value) => {
if (!value || value.deleted || !value.id) 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
}
}