-
Notifications
You must be signed in to change notification settings - Fork 55
/
PouchDbKeyValueStore.ts
66 lines (62 loc) · 2.07 KB
/
PouchDbKeyValueStore.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable promise/always-return */
import { EMPTY, Observable, from } from 'rxjs';
import { KeyValueCollection, KeyValueStore } from '../types';
import { Logger } from 'ts-log';
import { OpaqueString } from '@cardano-sdk/util';
import { PouchDbStore } from './PouchDbStore';
import { sanitizePouchDbDoc } from './util';
/** PouchDB database that implements KeyValueStore by using keys as document _id */
export class PouchDbKeyValueStore<K extends string | OpaqueString<any>, V extends {}>
extends PouchDbStore<V>
implements KeyValueStore<K, V>
{
/**
* @param dbName collection name
* @param logger will silently swallow the errors if not set
*/
constructor(dbName: string, logger: Logger) {
// Using a db per collection
super(dbName, logger);
}
setAll(docs: KeyValueCollection<K, V>[]): Observable<void> {
if (this.destroyed) return EMPTY;
return from(
(this.idle = this.idle.then(async (): Promise<void> => {
try {
await this.clearDB();
await this.db.bulkDocs(
docs.map(({ key, value }) => ({
...this.toPouchDbDoc(value),
_id: key
}))
);
} catch (error) {
this.logger.error(`PouchDbDocumentStore(${this.dbName}): failed to setAll`, docs, error);
}
}))
);
}
getValues(keys: K[]): Observable<V[]> {
if (this.destroyed) return EMPTY;
return new Observable((observer) => {
this.db
.bulkGet({ docs: keys.map((key) => ({ id: key })) })
.then(({ results }) => {
const values: V[] = [];
for (const { docs } of results) {
if (docs.length !== 1 || 'error' in docs[0]) {
return observer.complete();
}
values.push(sanitizePouchDbDoc(docs[0].ok));
}
observer.next(values);
observer.complete();
})
.catch(observer.complete.bind(observer));
});
}
setValue(key: K, value: V): Observable<void> {
return this.forcePut(key, value);
}
}