Refactor sources (#40)

* major refactor to exclude multiple sources

Co-authored-by: Matt Hill <matthewonthemoon@gmail.com>
This commit is contained in:
Alex Inkin
2022-08-21 23:36:07 +03:00
committed by GitHub
parent 2fef1e572c
commit f4732b18a2
9 changed files with 37 additions and 213 deletions

View File

@@ -1,44 +1,18 @@
import { EMPTY, merge, Observable, ReplaySubject, Subject } from 'rxjs'
import { catchError, switchMap } from 'rxjs/operators'
import { map, Observable, shareReplay } from 'rxjs'
import { tap } from 'rxjs/operators'
import { Store } from './store'
import { DBCache, Http } from './types'
import { RPCError } from './source/ws-source'
import { Source } from './source/source'
import { DBCache, Update } from './types'
export class PatchDB<T> {
public store: Store<T> = new Store(this.http, this.initialCache)
public connectionError$ = new Subject<Error>()
public rpcError$ = new Subject<RPCError>()
public cache$ = new ReplaySubject<DBCache<T>>(1)
private sub = this.sources$
.pipe(
switchMap(sources =>
merge(...sources.map(s => s.watch$(this.store))).pipe(
catchError(e => {
this.connectionError$.next(e)
return EMPTY
}),
),
),
)
.subscribe(res => {
if ('result' in res) {
this.store.update(res.result)
this.cache$.next(this.store.cache)
} else {
this.rpcError$.next(res)
}
})
public store: Store<T> = new Store(this.initialCache)
public cache$ = this.source$.pipe(
tap(res => this.store.update(res)),
map(_ => this.store.cache),
shareReplay(1),
)
constructor(
private readonly sources$: Observable<Source<T>[]>,
private readonly http: Http<T>,
private readonly source$: Observable<Update<T>>,
private readonly initialCache: DBCache<T>,
) {}
clean() {
this.sub.unsubscribe()
}
}