Files
patch-db/client/lib/source/ws-source.ts
Alex Inkin 6f6c26acd4 feat(client): remove data mutation (#32)
* feat(client): remove data mutation

* chore: address comments and fix some other issues

* chore: send the most recent cache upon subscription
2022-05-26 16:23:56 -06:00

57 lines
1.2 KiB
TypeScript

import { Observable } from 'rxjs'
import { webSocket, WebSocketSubject, WebSocketSubjectConfig } from 'rxjs/webSocket'
import { Update } from '../types'
import { Source } from './source'
export class WebsocketSource<T> implements Source<T> {
private websocket$: WebSocketSubject<RPCResponse<Update<T>>> | undefined
constructor (
private readonly url: string,
) { }
watch$ (): Observable<RPCResponse<Update<T>>> {
const fullConfig: WebSocketSubjectConfig<RPCResponse<Update<T>>> = {
url: this.url,
openObserver: {
next: () => {
this.websocket$!.next(document.cookie as any)
},
},
}
this.websocket$ = webSocket(fullConfig)
return this.websocket$
}
}
interface RPCBase {
jsonrpc: '2.0'
}
export interface RPCSuccess<T> extends RPCBase {
result: T
}
export interface RPCError extends RPCBase {
error: {
code: number // 34 means unauthenticated
message: string
data: {
details: string
}
}
}
export type RPCResponse<T> = RPCSuccess<T> | RPCError
class RpcError {
code: number
message: string
details: string
constructor (e: RPCError['error']) {
this.code = e.code
this.message = e.message
this.details = e.data.details
}
}