2020-11-06 22:44:16 +05:00
|
|
|
import Storage from "./storage";
|
|
|
|
|
import HyperSearch from "hypersearch";
|
|
|
|
|
import { getSchema } from "./schemas";
|
|
|
|
|
import PersistentCachedMap from "./persistentcachedmap";
|
2020-03-01 11:37:59 +05:00
|
|
|
import sort from "fast-sort";
|
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-02-03 12:03:07 +05:00
|
|
|
async init() {
|
2020-11-16 12:57:39 +05:00
|
|
|
const store = new PersistentCachedMap(this.storeKey, this.storage);
|
2020-11-06 22:44:16 +05:00
|
|
|
await store.init();
|
|
|
|
|
this.search = new HyperSearch({
|
|
|
|
|
schema: getSchema(this.type),
|
|
|
|
|
tokenizer: "forward",
|
|
|
|
|
store,
|
2020-11-16 12:57:39 +05:00
|
|
|
onIndexUpdated: async () => {
|
|
|
|
|
await this.storage.write(this.indexKey, this.search.indexer.export());
|
|
|
|
|
},
|
2020-11-06 22:44:16 +05:00
|
|
|
});
|
2020-11-16 12:57:39 +05:00
|
|
|
const index = await this.storage.read(this.indexKey);
|
|
|
|
|
this.search.indexer.import(index);
|
2020-02-02 20:07:11 +05:00
|
|
|
}
|
|
|
|
|
|
2020-02-06 16:46:23 +05:00
|
|
|
exists(id) {
|
2020-11-06 22:44:16 +05:00
|
|
|
const item = this.getItem(id);
|
|
|
|
|
return item && !item.deleted;
|
2020-02-02 20:07:11 +05:00
|
|
|
}
|
|
|
|
|
|
2020-03-23 15:06:12 +05:00
|
|
|
getRaw() {
|
2020-11-06 22:44:16 +05:00
|
|
|
return Array.from(this.search.getAllDocs());
|
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-06 22:44:16 +05:00
|
|
|
this.search.options.store.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
|
|
|
}
|
|
|
|
|
}
|