import { createJSONRPCRequest, JSONRPCErrorException, JSONRPCID, JSONRPCParams, JSONRPCRequest, JSONRPCResponse, } from 'json-rpc-2.0'; import { nanoid } from 'nanoid'; import request from 'sync-request'; import { ErrorInfo } from 'ably'; export class BlockingClient { request(method: string, params: JSONRPCParams): any { return this.requestWithID(method, params, nanoid()); } private requestWithID(method: string, params: JSONRPCParams | undefined, id: JSONRPCID): any { const requestData: JSONRPCRequest = createJSONRPCRequest(id, method, params); const rawResponse = request('POST', 'http://localhost:3000/json-rpc', { json: requestData, }) .getBody() .toString(); const response: JSONRPCResponse = JSON.parse(rawResponse); if (response.result !== undefined && !response.error) { return response.result; } else if (response.result === undefined && response.error && response.error.data?.ablyError) { const { code, message, statusCode } = response.error.data.errorInfo; throw new ErrorInfo(message, code, statusCode); } else if (response.result === undefined && response.error) { throw new JSONRPCErrorException(response.error.message, response.error.code, response.error.data); } else { throw new Error('An unexpected error occurred'); } } }