All files / modules/85-cv/hooks/useLogContentHook useLogContentHook.utils.ts

96.3% Statements 52/54
86% Branches 43/50
100% Functions 13/13
95.35% Lines 41/43

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              19x       19x 19x   19x 4x     19x       49x     60x         49x     26x                                     52x   19x 26x   18x   4x         2x         2x                 69x   19x 15x   15x 15x   15x     19x 13x   13x 1x     12x     19x 6x 6x   6x 6x 6x     19x 3x     6x     3x 3x         3x   3x        
/*
 * 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 moment from 'moment'
import type { SelectOption } from '@harness/uicore'
import type { ApiCallLogDTO, HealthSourceDTO } from 'services/cv'
import type { UseStringsReturn } from 'framework/strings'
import { TimeRangeTypes } from './useLogContentHook.types'
import { RESPONSE_BODY } from './useLogContentHook.constants'
 
export function isPositiveNumber(index: unknown): index is number {
  return typeof index === 'number' && index >= 0
}
 
export function getHealthSourceOptions(
  getString: UseStringsReturn['getString'],
  healthSources?: HealthSourceDTO[]
): SelectOption[] {
  const optionAll: SelectOption = { label: getString('all'), value: '' }
 
  const healthSourcesOptions =
    healthSources?.map(healthSource => ({
      label: healthSource.name ?? '',
      value: healthSource.identifier ?? ''
    })) ?? []
 
  return [optionAll, ...healthSourcesOptions]
}
 
export const getTimeRangeOptions = (getString: UseStringsReturn['getString']): SelectOption[] => [
  {
    label: getString('cv.lastOneHour'),
    value: TimeRangeTypes.LAST_1_HOUR
  },
  {
    label: getString('cv.monitoredServices.serviceHealth.last4Hrs'),
    value: TimeRangeTypes.LAST_4_HOURS
  },
  {
    label: getString('cv.last12Hours'),
    value: TimeRangeTypes.LAST_12_HOUR
  },
  {
    label: getString('cv.monitoredServices.serviceHealth.last24Hrs'),
    value: TimeRangeTypes.LAST_24_HOUR
  }
]
 
export const startOfSecond = (time: moment.Moment): Date => time.utc().startOf('minute').toDate()
 
export const getTimeRangeInMilliseconds = (timeRange: TimeRangeTypes): [number, number] => {
  switch (timeRange) {
    case TimeRangeTypes.LAST_1_HOUR:
      return [startOfSecond(moment().subtract(1, 'hour').add(1, 'second')).getTime(), startOfSecond(moment()).getTime()]
    case TimeRangeTypes.LAST_4_HOURS:
      return [
        startOfSecond(moment().subtract(4, 'hours').add(1, 'second')).getTime(),
        startOfSecond(moment()).getTime()
      ]
    case TimeRangeTypes.LAST_12_HOUR:
      return [
        startOfSecond(moment().subtract(12, 'hours').add(1, 'second')).getTime(),
        startOfSecond(moment()).getTime()
      ]
    case TimeRangeTypes.LAST_24_HOUR:
      return [
        startOfSecond(moment().subtract(24, 'hours').add(1, 'second')).getTime(),
        startOfSecond(moment()).getTime()
      ]
    default:
      return [0, 0]
  }
}
 
export const formatDate = (date?: number): string => (date ? moment(new Date(date)).format('L, LT') : '')
 
export const getInfoText = (getString: UseStringsReturn['getString'], timeRange?: SelectOption): string => {
  const [_startTime, _endTime] = getTimeRangeInMilliseconds(timeRange?.value as TimeRangeTypes)
 
  const startTime = formatDate(_startTime)
  const endTime = formatDate(_endTime)
 
  return `${getString('cv.showingLogsFor')} ${timeRange?.label?.toLowerCase()} from ${startTime} to ${endTime}.`
}
 
export const getStatusColor = (statusCode = '500'): 'success' | 'error' => {
  const _code = Number(statusCode)
 
  if (_code >= 200 && _code < 300) {
    return 'success'
  }
 
  return 'error'
}
 
export function downloadJson(data: string, fileName: string): void {
  const jsonString = `data:text/json;chatset=utf-8,${encodeURIComponent(data)}`
  const link = document.createElement('a')
 
  link.href = jsonString
  link.download = `${fileName}-${moment().format('L-LT')}.json`
  link.click()
}
 
export function parseResponseBody(data: ApiCallLogDTO[]): ApiCallLogDTO[] {
  return data.map(log => ({
    ...log,
    responses: log.responses?.map(response => {
      if (response.name === RESPONSE_BODY) {
        let value
 
        try {
          value = response.value && JSON.parse(response.value)
        } catch (e) {
          value = response.value
        }
 
        return { ...response, value }
      }
      return response
    })
  }))
}