This commit is contained in:
Matt Hill
2021-07-06 16:56:15 -06:00
committed by Aiden McClelland
parent 43e3c77c14
commit 434c6f7037
4 changed files with 25 additions and 40 deletions

View File

@@ -1,20 +1,17 @@
import { BehaviorSubject, from, Observable } from 'rxjs'
import { observable } from 'mobx'
import { toStream } from 'mobx-utils'
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<T> {
sequence: number
o: { data: T | { } }
cache$: BehaviorSubject<DBCache<T>>
cache: DBCache<T>
sequence$: BehaviorSubject<number>
constructor (
readonly initialCache: DBCache<T>,
) {
this.sequence = initialCache.sequence
this.o = observable({ data: this.initialCache.data })
this.cache$ = new BehaviorSubject(initialCache)
this.cache = initialCache
this.sequence$ = new BehaviorSubject(initialCache.sequence)
}
watch$ (): Observable<T>
@@ -28,33 +25,25 @@ export class Store<T> {
return from(toStream(() => this.peekNode(...args), true))
}
watchCache$ (): Observable<DBCache<T>> {
return this.cache$.asObservable()
}
update (update: Update<T>): void {
if ((update as Revision).patch) {
if (this.sequence + 1 !== update.id) throw new Error(`Outdated sequence: current: ${this.sequence}, new: ${update.id}`)
applyPatch(this.o.data, (update as Revision).patch, true, true)
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.o.data = (update as Dump<T>).value
this.cache.data = (update as Dump<T>).value
}
this.sequence = update.id
this.cache$.next({ sequence: this.sequence, data: this.o.data })
this.cache.sequence = update.id
this.sequence$.next(this.cache.sequence)
}
reset (): void {
this.cache$.next({
sequence: 0,
data: { },
})
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.o.data)
return args.reduce((acc, next) => (acc as any)[`${next}`], this.cache.data)
} catch (e) {
return undefined
}