All files / src/hooks useWsTicker.ts

76.25% Statements 61/80
65.62% Branches 21/32
72.72% Functions 8/11
79.22% Lines 61/77

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147  1x 1x 1x 1x 1x 1x 1x                             6x 6x 6x 6x   6x 6x 6x   6x 4x 4x         4x   4x 4x               6x 3x 3x       1x       2x 2x 2x   2x 2x 2x   2x 2x       4x     2x 2x       2x               2x         2x 4x 4x 4x 4x     2x 2x 2x 2x   2x 2x 2x 1x 1x         1x 1x 1x                 6x 3x 3x 1x 1x                         6x     1x  
import {ITicker, ImarketCodes, TKOptionsInterface} from '../interfaces';
import {useRef, useState, useEffect} from 'react';
import getLastBuffers from '../functions/getLastBuffers';
import sortBuffers from '../functions/sortBuffers';
import {throttle} from 'lodash';
import socketDataEncoder from '../functions/socketDataEncoder';
import updateSocketData from '../functions/updateSocketData';
import isArrayOfImarketCodes from '../functions/isArrayOfImarketCodes';
 
/**
 * useWsTicker is a custom hook that connects to a WebSocket API
 * and retrieves real-time ticker data for a given market code.
 * @param targetMarketCodes - Array of market codes to retrieve ticker data for.
 * @param options - `throttle_time` the data update frequency(ms).
 * @throws targetMarketCodes should be React State Value, if not, unexpected errors can occur.
 * @returns Object with the WebSocket object, connection status, and real-time ticker data.
 */
function useWsTicker(
  targetMarketCodes: ImarketCodes[],
  onError?: (error: Error) => void,
  options: TKOptionsInterface = {},
) {
  const {throttle_time = 400, debug = false} = options;
  const SOCKET_URL = 'wss://api.upbit.com/websocket/v1';
  const socket = useRef<WebSocket | null>(null);
  const buffer = useRef<ITicker[]>([]);
 
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const [loadingBuffer, setLoadingBuffer] = useState<ITicker[]>([]);
  const [socketData, setSocketData] = useState<ITicker[] | null>(null);
 
  const throttled = throttle(() => {
    try {
      const lastBuffers = getLastBuffers(
        buffer.current,
        targetMarketCodes.length,
      );
 
      const sortedBuffers = sortBuffers(lastBuffers, targetMarketCodes);
 
      sortedBuffers && setLoadingBuffer(sortedBuffers);
      buffer.current = [];
    } catch (error) {
      console.error(error);
      return;
    }
  }, throttle_time);
 
  // socket 세팅
  useEffect(() => {
    try {
      if (
        targetMarketCodes.length > 0 &&
        !isArrayOfImarketCodes(targetMarketCodes)
      ) {
        throw new Error(
          'targetMarketCodes does not have the correct interface',
        );
      }
      if (targetMarketCodes.length > 0 && !socket.current) {
        socket.current = new WebSocket(SOCKET_URL);
        socket.current.binaryType = 'arraybuffer';
 
        const socketOpenHandler = () => {
          setIsConnected(true);
          Iif (debug)
            console.log('[completed connect] | socket Open Type: ', 'ticker');
          if (socket.current?.readyState == 1) {
            const sendContent = [
              {ticket: 'test'},
              {
                type: 'ticker',
                codes: targetMarketCodes.map(code => code.market),
              },
            ];
            socket.current.send(JSON.stringify(sendContent));
            Iif (debug) console.log('message sending done');
          }
        };
 
        const socketCloseHandler = () => {
          setIsConnected(false);
          setLoadingBuffer([]);
          setSocketData(null);
          buffer.current = [];
          Iif (debug) console.log('connection closed');
        };
 
        const socketErrorHandler = (event: Event) => {
          const error = (event as ErrorEvent).error as Error;
          console.error('[Error]', error);
        };
 
        const socketMessageHandler = (evt: MessageEvent<ArrayBuffer>) => {
          const data = socketDataEncoder<ITicker>(evt.data);
          Iif (debug) console.log('data:', data);
          data && buffer.current.push(data);
          throttled();
        };
 
        socket.current.onopen = socketOpenHandler;
        socket.current.onclose = socketCloseHandler;
        socket.current.onerror = socketErrorHandler;
        socket.current.onmessage = socketMessageHandler;
      }
      return () => {
        if (socket.current) {
          if (socket.current.readyState != 0) {
            socket.current.close();
            socket.current = null;
          }
        }
      };
    } catch (error) {
      if (error instanceof Error) {
        if (onError) {
          onError(error);
        } else E{
          console.error(error);
          throw error;
        }
      }
    }
  }, [targetMarketCodes]);
 
  useEffect(() => {
    try {
      if (loadingBuffer.length > 0) {
        if (!socketData) {
          setSocketData(loadingBuffer);
        } else E{
          setSocketData(prev => {
            return prev && updateSocketData(prev, loadingBuffer);
          });
          setLoadingBuffer([]);
        }
      }
    } catch (error) {
      console.error(error);
    }
  }, [loadingBuffer]);
 
  return {socket: socket.current, isConnected, socketData};
}
 
export default useWsTicker;