import { DBCache, Dump, Revision, Update } from './types' import { applyPatch } from 'fast-json-patch' import { BehaviorSubject, from, Observable } from 'rxjs' import { toStream } from 'mobx-utils' export class Store { cache: DBCache sequence$: BehaviorSubject constructor ( readonly initialCache: DBCache, ) { this.cache = initialCache this.sequence$ = new BehaviorSubject(initialCache.sequence) } watch$ (): Observable watch$ (p1: P1): Observable watch$ (p1: P1, p2: P2): Observable watch$ (p1: P1, p2: P2, p3: P3): Observable watch$ (p1: P1, p2: P2, p3: P3, p4: P4): Observable watch$ (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): Observable watch$ (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): Observable watch$ (...args: (string | number)[]): Observable { return from(toStream(() => this.peekNode(...args), true)) } update (update: Update): void { if ((update as Revision).patch) { if (this.cache.sequence + 1 !== update.id) throw new Error(`Outdated sequence: current: ${this.cache.sequence}, new: ${update.id}`) applyPatch(this.cache.data, (update as Revision).patch, true, true) } else { this.cache.data = (update as Dump).value } this.cache.sequence = update.id this.sequence$.next(this.cache.sequence) } reset (): void { this.cache.sequence = 0 this.cache.data = { } as T } private peekNode (...args: (string | number)[]): any { try { return args.reduce((acc, next) => (acc as any)[`${next}`], this.cache.data) } catch (e) { return undefined } } }