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

50 lines
1.0 KiB
JavaScript
Raw Normal View History

import Indexer from "./indexer";
2020-03-01 11:37:59 +05:00
import sort from "fast-sort";
import { EV } from "../common";
import IndexedCollection from "./indexed-collection";
2020-02-02 20:07:11 +05:00
export default class CachedCollection extends IndexedCollection {
constructor(context, type) {
super(context, type);
2020-11-24 01:39:32 +05:00
this.map = new Map();
}
2020-02-03 12:03:07 +05:00
async init() {
await super.init();
const data = await this.indexer.readMulti(this.indexer.indices);
this.map = new Map(data);
}
async clear() {
await super.clear();
this.map.clear();
}
async updateItem(item) {
await super.updateItem(item);
this.map.set(item.id, item);
EV.publish("db:write", 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;
}
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());
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) => {
2020-04-21 12:23:51 +05:00
if (!value || 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
}
}