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

77.27% Statements 34/44
70% Branches 28/40
80% Functions 8/10
78.05% Lines 32/41

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 155 156 157 158 159 160 161 162 163                  1075x     1075x   1075x 1075x   1075x 182x                                                                                                 94x 94x       58x 57x 57x 55x     38x 38x 38x     38x       1075x                       996x 996x 996x 996x     996x                       996x   996x 221x 136x 136x                           221x 181x         996x               4x 4x                      
/*
 * 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.
 */
 
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { UseMutateProps, UseMutateReturn, MutateMethod, GetDataError } from 'restful-react'
import { useState, useCallback, useEffect, Dispatch, SetStateAction } from 'react'
// eslint-disable-next-line no-restricted-imports
import type { Cancelable, DebounceSettings } from 'lodash' // only type imports
import { debounce, identity } from 'lodash-es'
 
import { shouldShowError } from '@harness/uicore'
import { useDeepCompareEffect } from './useDeepCompareEffect'
 
const isCancellable = <T extends (...args: any[]) => any>(func: T): func is T & Cancelable => {
  return typeof (func as any).cancel === 'function' && typeof (func as any).flush === 'function'
}
 
export type WrappedUseMutateProps<TData, TError, TQueryParams, TRequestBody, TPathParams> = Omit<
  UseMutateProps<TData, TError, TQueryParams, TRequestBody, TPathParams>,
  'path' | 'verb'
> & {
  lazy?: boolean
  body: TRequestBody
  mock?: TData | TError
  debounce?:
    | {
        wait?: number
        options: DebounceSettings
      }
    | boolean
    | number
} & any // TODO: Add correct types here
 
type UseMutateWrapper<TData, TError, TQueryParams, TRequestBody, TPathParams> = (
  props: WrappedUseMutateProps<TData, TError, TQueryParams, TRequestBody, TPathParams>
) => UseMutateReturn<TData, TError, TRequestBody, TQueryParams, TPathParams>
 
export interface UseMutateAsGetReturn<
  TData = any,
  TError = any,
  TQueryParams = {
    [key: string]: any
  },
  TRequestBody = any,
  TPathParams = unknown
> {
  data: TData | null
  initLoading: boolean
  loading: boolean
  error: GetDataError<TError> | null
  cancel(): void
  refetch(
    props?: WrappedUseMutateProps<TData, TError, TRequestBody, TQueryParams, TPathParams>
  ): Promise<void> | undefined
}
 
async function _fetchData<TData, TError, TQueryParams, TRequestBody, TPathParams>(
  mutate: MutateMethod<TData, TQueryParams, TRequestBody, TPathParams>,
  props: WrappedUseMutateProps<TData, TError, TRequestBody, TQueryParams, TPathParams>,
  setInitLoading: Dispatch<SetStateAction<boolean>>,
  setData: Dispatch<SetStateAction<TData | null>>,
  setError: Dispatch<SetStateAction<TError | null>>
): Promise<void> {
  try {
    const data = await mutate(props.body, {
      queryParams: props.queryParams,
      pathParams: props.pathParams
    })
    if (data) {
      setInitLoading(false)
      setData(data)
      setError(null)
    }
  } catch (e) {
    Eif (shouldShowError(e)) {
      setData(null)
      setError(e)
    }
 
    setInitLoading(false)
  }
}
 
export function useMutateAsGet<
  TData = any,
  TError = any,
  TQueryParams = {
    [key: string]: any
  },
  TRequestBody = any,
  TPathParams = unknown
>(
  useMutateWrapper: UseMutateWrapper<TData, TError, TRequestBody, TQueryParams, TPathParams>,
  props: WrappedUseMutateProps<TData, TError, TRequestBody, TQueryParams, TPathParams>
): UseMutateAsGetReturn<TData, TError, TQueryParams, TRequestBody, TPathParams> {
  const [data, setData] = useState<TData | null>(null)
  const [initLoading, setInitLoading] = useState(!props.lazy)
  const [error, setError] = useState<GetDataError<TError> | null>(null)
  const { mutate, loading, cancel } = useMutateWrapper(props)
 
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const fetchData = useCallback(
    typeof props.debounce === 'object'
      ? debounce(_fetchData, props.debounce.wait, props.debounce.options)
      : typeof props.debounce === 'number'
      ? debounce(_fetchData, props.debounce)
      : props.debounce
      ? debounce(_fetchData)
      : _fetchData,
    [props.debounce]
  )
 
  // Cancel fetchData on unmount (if debounce)
  useEffect(() => (isCancellable(fetchData) ? () => fetchData.cancel() : undefined), [fetchData])
 
  useDeepCompareEffect(() => {
    if (!props.lazy && !props.mock) {
      try {
        fetchData(mutate, props, setInitLoading, setData, setError)?.then(identity, e => {
          if (shouldShowError(e)) {
            setError(e)
          }
          setInitLoading(false)
        })
      } catch (e) {
        if (shouldShowError(e)) {
          setError(e)
        }
        setInitLoading(false)
      }
    }
 
    return () => {
      cancel?.()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.lazy, props.body, props.queryParams, props.pathParams, props.base, props.mock])
 
  return {
    data,
    ...props.mock,
    initLoading,
    loading,
    error,
    cancel,
    refetch: newProps => {
      try {
        return fetchData(mutate, newProps || props, setInitLoading, setData, setError)?.then(identity, e => {
          if (shouldShowError(e)) setError(e)
        })
      } catch (e) {
        if (shouldShowError(e)) {
          setError(e)
        }
      }
    }
  }
}