import { OnRoomStatusChangeResponse, RoomLifecycle, RoomStatus, RoomStatusListener } from '@ably/chat'; import { ErrorInfo } from 'ably'; import { nanoid } from 'nanoid'; import { jsonRpcBlocking, registerCallback } from './jsonrpc'; export class RpcRoomStatus implements RoomStatus { private readonly _instanceId: string; constructor(instanceId: string) { this._instanceId = instanceId; } get current(): RoomLifecycle { const { response } = jsonRpcBlocking.request('RoomStatus#current', { refId: this._instanceId }); return response; } get error(): ErrorInfo | undefined { const { response } = jsonRpcBlocking.request('RoomStatus#error', { refId: this._instanceId }); return response; } onChange(listener: RoomStatusListener): OnRoomStatusChangeResponse { const callbackId = nanoid(); registerCallback(callbackId, listener); const { refId } = jsonRpcBlocking.request('RoomStatus.onChange', { refId: this._instanceId, callbackId, }); return new RpcOnRoomStatusChangeResponse(refId); } offAll(): void { jsonRpcBlocking.request('RoomStatus.offAll', { refId: this._instanceId }); } } export class RpcOnRoomStatusChangeResponse implements OnRoomStatusChangeResponse { private readonly _instanceId: string; constructor(instanceId: string) { this._instanceId = instanceId; // it is common to destructure this object when received from the subscription function, // so we need to bind its functions to preserve reference to this this.off = this.off.bind(this); } off(): void { jsonRpcBlocking.request('OnRoomStatusChangeResponse.off', { refId: this._instanceId }); } }