-
Notifications
You must be signed in to change notification settings - Fork 324
/
KVIndexStore.ts
49 lines (43 loc) · 1.5 KB
/
KVIndexStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import _ from "lodash";
import { IndexStruct, jsonToIndexStruct } from "../../indices/BaseIndex";
import { DEFAULT_NAMESPACE } from "../constants";
import { BaseKVStore } from "../kvStore/types";
import { BaseIndexStore } from "./types";
export class KVIndexStore extends BaseIndexStore {
private _kvStore: BaseKVStore;
private _collection: string;
constructor(kvStore: BaseKVStore, namespace: string = DEFAULT_NAMESPACE) {
super();
this._kvStore = kvStore;
this._collection = `${namespace}/data`;
}
async addIndexStruct(indexStruct: IndexStruct): Promise<void> {
let key = indexStruct.indexId;
let data = indexStruct.toJson();
await this._kvStore.put(key, data, this._collection);
}
async deleteIndexStruct(key: string): Promise<void> {
await this._kvStore.delete(key, this._collection);
}
async getIndexStruct(structId?: string): Promise<IndexStruct | undefined> {
if (_.isNil(structId)) {
let structs = await this.getIndexStructs();
if (structs.length !== 1) {
throw new Error("More than one index struct found");
}
return structs[0];
} else {
let json = await this._kvStore.get(structId, this._collection);
if (_.isNil(json)) {
return;
}
return jsonToIndexStruct(json);
}
}
async getIndexStructs(): Promise<IndexStruct[]> {
let jsons = (await this._kvStore.getAll(this._collection)) as {
[key: string]: any;
};
return _.values(jsons).map((json) => jsonToIndexStruct(json));
}
}