Files
start-os/frontend/projects/ui/src/app/services/patch-db/patch-db.service.ts
Matt Hill 3ddeb5fa94 [Fix] websocket connecting and patchDB connection monitoring (#1738)
* refactor how we handle rpc responses and patchdb connection monitoring

* websockets only

* remove unused global error handlers

* chore: clear storage inside auth service

* feat: convert all global toasts to declarative approach (#1754)

* no more reference to serverID

Co-authored-by: Aiden McClelland <me@drbonez.dev>
Co-authored-by: waterplea <alexander@inkin.ru>
2022-08-22 10:53:52 -06:00

65 lines
1.6 KiB
TypeScript

import { Inject, Injectable } from '@angular/core'
import { Bootstrapper, PatchDB, Store } from 'patch-db-client'
import { Observable, of, Subscription } from 'rxjs'
import { catchError, debounceTime, finalize, tap } from 'rxjs/operators'
import { DataModel } from './data-model'
import { BOOTSTRAPPER } from './patch-db.factory'
@Injectable({
providedIn: 'root',
})
export class PatchDbService {
private sub?: Subscription
constructor(
@Inject(BOOTSTRAPPER)
private readonly bootstrapper: Bootstrapper<DataModel>,
private readonly patchDb: PatchDB<DataModel>,
) {}
start(): void {
// Early return if already started
if (this.sub) {
return
}
console.log('patchDB: STARTING')
this.sub = this.patchDb.cache$
.pipe(
debounceTime(420),
tap(cache => {
this.bootstrapper.update(cache)
}),
)
.subscribe()
}
stop(): void {
// Early return if already stopped
if (!this.sub) {
return
}
console.log('patchDB: STOPPING')
this.patchDb.store.reset()
this.sub.unsubscribe()
this.sub = undefined
}
// prettier-ignore
watch$: Store<DataModel>['watch$'] = (...args: (string | number)[]): Observable<DataModel> => {
const argsString = '/' + args.join('/')
console.log('patchDB: WATCHING ', argsString)
return this.patchDb.store.watch$(...(args as [])).pipe(
tap(data => console.log('patchDB: NEW VALUE', argsString, data)),
catchError(e => {
console.error('patchDB: WATCH ERROR', e)
return of(e.message)
}),
finalize(() => console.log('patchDB: UNSUBSCRIBING', argsString)),
)
}
}