All files / modules/10-common/hooks useEventSourceListener.tsx

89.71% Statements 61/68
54.29% Branches 19/35
78.57% Functions 11/14
89.55% Lines 60/67

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 148 149 150 151 152 153 154              1x 1x 1x 1x 1x 1x 1x 1x   1x             1x 1x 1x 1x                                     1x             8x 8x 8x 8x 8x 8x 8x   8x 2x   2x       2x     8x 2x     8x                     8x       8x       8x 3x 1x         2x       8x 2x   2x 2x 2x   2x     8x 4x         4x 4x     8x 5x 1x     5x 4x 1x 1x         8x 1x 1x 1x       8x 1x 1x 1x       8x    
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import qs, { IStringifyOptions } from 'qs'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { useHistory, useParams } from 'react-router-dom'
import SessionToken from 'framework/utils/SessionToken'
import { returnUrlParams } from '@common/utils/routeUtils'
import { getLoginPageURL } from 'framework/utils/SessionUtils'
import routes from '@common/RouteDefinitions'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useDeepCompareEffect } from './useDeepCompareEffect'
 
interface EventSourceListenerReturn {
  startListening: () => void
  stopListening: () => void
}
 
enum EventType {
  MESSAGE = 'message',
  OPEN = 'open',
  ERROR = 'error'
}
 
export type EventSourceEvent<T> = {
  onOpen?: () => void
  onError?: (event?: Event) => void
  onParseError?: (error?: Error) => void
  onMessage: (event: { data: T; event: Event }) => void
  options?: boolean | AddEventListenerOptions | EventListenerOptions
}
 
interface EventSourceListenerProps<T> {
  url: string
  event: EventSourceEvent<T>
  queryParams?: Record<string, unknown>
  queryParamStringifyOptions?: IStringifyOptions
  lazy?: boolean
}
 
export const useEventSourceListener = <T extends unknown>({
  url,
  event,
  lazy = false,
  queryParams,
  queryParamStringifyOptions
}: EventSourceListenerProps<T>): EventSourceListenerReturn => {
  const [init, setInit] = useState<boolean>(false)
  const { accountId } = useParams<AccountPathProps>()
  const history = useHistory()
  const [forceStop, setForceStop] = React.useState(false)
  const [source, setSource] = useState<EventSource>()
  const { onMessage, onError, onOpen, onParseError, options } = event
  const token = SessionToken.getToken()
 
  const getRequestOptions = React.useCallback((): Partial<RequestInit> => {
    const headers: HeadersInit = {}
 
    Iif (token && token.length > 0) {
      headers.Authorization = `Bearer ${token}`
    }
 
    return { headers }
  }, [token])
 
  const getQueryParams = (params?: Record<string, unknown>): string => {
    return `?${qs.stringify({ ...params, routingId: accountId }, queryParamStringifyOptions)}`
  }
 
  const onMessageEventListener = (_event: Event & { data: string }): void => {
    let parsedData
 
    try {
      parsedData = JSON.parse(_event.data)
      onMessage({ data: parsedData, event: _event })
    } catch (e) {
      onParseError?.(e as Error)
    }
  }
 
  const onOpenEventListener = (): void => {
    onOpen?.()
  }
 
  const onErrorEventListener = (_event: Event): void => {
    onError?.(_event)
  }
 
  useDeepCompareEffect(() => {
    if (!token) {
      history.push({
        pathname: routes.toRedirect(),
        search: returnUrlParams(getLoginPageURL({ returnUrl: window.location.href }))
      })
    } else {
      setSource(new EventSourcePolyfill(`${url}${getQueryParams(queryParams)}`, getRequestOptions()))
    }
  }, [url, token, queryParams, accountId])
 
  const createListener = (_source: EventSource): void => {
    removeListener(_source)
 
    _source.addEventListener(EventType.MESSAGE, onMessageEventListener as EventListenerOrEventListenerObject, options)
    _source.addEventListener(EventType.OPEN, onOpenEventListener as EventListenerOrEventListenerObject, options)
    _source.addEventListener(EventType.ERROR, onErrorEventListener as EventListenerOrEventListenerObject, options)
 
    !init && setInit(false)
  }
 
  const removeListener = (_source: EventSource): void => {
    _source.removeEventListener(
      EventType.MESSAGE,
      onMessageEventListener as EventListenerOrEventListenerObject,
      options
    )
    _source.removeEventListener(EventType.OPEN, onOpenEventListener as EventListenerOrEventListenerObject, options)
    _source.removeEventListener(EventType.ERROR, onErrorEventListener as EventListenerOrEventListenerObject, options)
  }
 
  useEffect(() => {
    if (source && (init || !lazy) && !forceStop) {
      createListener(source)
    }
 
    return () => {
      if (source) {
        removeListener(source)
        source.close()
      }
    }
  }, [source])
 
  const startListening = React.useCallback(() => {
    Eif (source) {
      createListener(source)
      setForceStop(false)
    }
  }, [source])
 
  const stopListening = React.useCallback(() => {
    Eif (source) {
      removeListener(source)
      setForceStop(true)
    }
  }, [source])
 
  return { startListening, stopListening }
}