All files / json-crdt-repo/src/__tests__/e2e clients.ts

29.03% Statements 9/31
0% Branches 0/6
0% Functions 0/9
26.92% Lines 7/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 511x 1x 1x 1x           1x             1x                                     1x                              
import WebSocket from 'ws';
import {WebSocketChannel} from '@jsonjoy.com/channel/lib/WebSocketChannel';
import {RxPersistentCaller} from '@jsonjoy.com/rpc-calls/lib/caller/RxPersistentCaller';
import {FetchCaller} from '@jsonjoy.com/rpc-calls/lib/caller/FetchCaller';
import {RpcMessageFormat} from '@jsonjoy.com/rpc-codec-base/lib/constants';
import type {RpcCodec} from '@jsonjoy.com/rpc-codec/lib/RpcCodec';
import type {BinBatchCodec} from '@jsonjoy.com/rpc-codec-base';
 
/** Adapts an {@link RpcCodec} to the {@link BinBatchCodec} interface for use with {@link FetchCaller}. */
const rpcCodecToBinBatchCodec = (rpcCodec: RpcCodec<any>): BinBatchCodec<any> => ({
  id: rpcCodec.specifier(),
  format: rpcCodec.msg.format ?? RpcMessageFormat.Compact,
  toChunk: (messages: any[]) => rpcCodec.encode(messages, rpcCodec.req),
  fromChunk: (chunk: Uint8Array) => rpcCodec.decode(chunk, rpcCodec.res),
});
 
export const setupRpcPersistentClient = (codec: RpcCodec<any>) => {
  const port = +(process.env.PORT || 9999);
  const url = `ws://localhost:${port}/rx`;
  const caller = new RxPersistentCaller({
    codec,
    physical: {
      newChannel: () =>
        new WebSocketChannel({
          newSocket: () => new WebSocket(url, [codec.specifier()]) as any,
        }),
    },
  });
  caller.start();
  const call = caller.call.bind(caller);
  const call$ = caller.call$.bind(caller);
  const stop = async () => void caller.stop();
  return {caller: caller as any, call, call$, stop};
};
 
export const setupFetchRpcClient = (codec: RpcCodec<any>) => {
  const port = +(process.env.PORT || 9999);
  const url = `http://localhost:${port}/rx`;
  const caller = new FetchCaller({
    url,
    codec: rpcCodecToBinBatchCodec(codec),
    headers: {
      'Content-Type': `application/x.${codec.specifier()}`,
    },
  });
  const call = caller.call.bind(caller);
  const call$ = caller.call$.bind(caller);
  const stop = async () => void caller.stop();
  return {caller: caller as any, call, call$, stop};
};