All files / src/persistence/inMemoryStores InMemoryCollectionStore.ts

100% Statements 18/18
100% Branches 4/4
100% Functions 5/5
100% Lines 17/17

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  41x 41x 41x   41x 831x 831x       831x 831x       402x 25x       429x 427x 427x         19x     2x       2x 2x      
import { CollectionStore } from '../types';
import { EMPTY, Observable, Subject, delay, of, tap } from 'rxjs';
import { InMemoryStore } from './InMemoryStore';
import { observeAll } from '../util';
 
export class InMemoryCollectionStore<T> extends InMemoryStore implements CollectionStore<T> {
  readonly #updates$ = new Subject<T[]>();
  protected docs: T[] = [];
  observeAll: CollectionStore<T>['observeAll'];
 
  constructor() {
    super();
    this.observeAll = observeAll(this, this.#updates$);
  }
 
  getAll(): Observable<T[]> {
    if (this.docs.length === 0 || this.destroyed) return EMPTY;
    return of(this.docs);
  }
 
  setAll(docs: T[]): Observable<void> {
    if (!this.destroyed) {
      this.docs = docs;
      return of(void 0).pipe(
        // if setAll is called on 1st emission of observeAll,
        // then this has to be asynchronous for observeAll to emit the 2nd item.
        // any delay duration is ok: it's enough that this is called in the next tick
        delay(1),
        tap(() => this.#updates$.next(this.docs))
      );
    }
    return EMPTY;
  }
 
  destroy(): Observable<void> {
    this.#updates$.complete();
    return super.destroy();
  }
}