All files / src/persistence/pouchDbStores PouchDbKeyValueStore.ts

96.15% Statements 25/26
100% Branches 5/5
100% Functions 9/9
95.83% Lines 23/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  42x       42x 42x     42x                   7x       2x 1x   1x 1x 1x 2x                         8x 7x 7x 8x   7x 7x 8x 3x   5x   4x 4x             9x      
/* eslint-disable @typescript-eslint/no-explicit-any */
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);
  }
}