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

42 lines
1.2 KiB
JavaScript
Raw Normal View History

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";
import IndexedCollection from "./indexed-collection";
2020-02-02 20:07:11 +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);
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-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) {
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() {
return Array.from(this.search.getAllDocs());
2020-03-23 15:06:12 +05:00
}
getItems(sortFn = (u) => u.dateCreated) {
2020-02-02 20:07:11 +05:00
let items = [];
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
}
}