2020-11-16 15:00:52 +05:00
|
|
|
import Indexer from "./indexer";
|
2020-03-01 11:37:59 +05:00
|
|
|
import sort from "fast-sort";
|
2020-11-16 15:00:52 +05:00
|
|
|
import { EV } from "../common";
|
2020-11-04 10:42:19 +05:00
|
|
|
import IndexedCollection from "./indexed-collection";
|
2020-02-02 20:07:11 +05:00
|
|
|
|
2020-11-04 10:42:19 +05:00
|
|
|
export default class CachedCollection extends IndexedCollection {
|
2020-11-16 15:00:52 +05:00
|
|
|
constructor(context, type) {
|
|
|
|
|
super(context, type);
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-03 12:03:07 +05:00
|
|
|
async init() {
|
2020-11-16 15:00:52 +05:00
|
|
|
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, index = true) {
|
|
|
|
|
await super.updateItem(item, index);
|
|
|
|
|
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) {
|
2020-11-16 15:00:52 +05:00
|
|
|
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() {
|
2020-11-16 15:00:52 +05:00
|
|
|
return Array.from(this.map.values());
|
2020-03-23 15:06:12 +05:00
|
|
|
}
|
|
|
|
|
|
2020-11-04 10:42:19 +05:00
|
|
|
getItems(sortFn = (u) => u.dateCreated) {
|
2020-02-02 20:07:11 +05:00
|
|
|
let items = [];
|
2020-11-16 15:00:52 +05:00
|
|
|
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
|
|
|
}
|
|
|
|
|
}
|