All files / modules/70-pipeline/components/PipelineStudio/PiplineHooks useValidationErrors.ts

72.73% Statements 16/22
12.5% Branches 1/8
66.67% Functions 2/3
72.73% Lines 16/22

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              101x 101x 101x   101x 101x     101x 101x   101x 103x       103x   103x   103x                           103x 38x     38x         103x    
/*
 * Copyright 2021 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 { useState, useCallback } from 'react'
import { isNil } from 'lodash-es'
import debounce from 'p-debounce'
 
import { validateJSONWithSchema } from '@common/utils/YamlUtils'
import { useDeepCompareEffect } from '@common/hooks'
import type { PipelineInfoConfig, ResponseJsonNode } from 'services/cd-ng'
 
import { usePipelineContext } from '../PipelineContext/PipelineContext'
import { usePipelineSchema } from '../PipelineSchema/PipelineSchemaContext'
 
export function useValidationErrors(): { errorMap: Map<string, string[]> } {
  const { pipelineSchema } = usePipelineSchema()
  const {
    state: { pipeline: originalPipeline, schemaErrors },
    setSchemaErrorView
  } = usePipelineContext()
 
  const [errorMap, setErrorMap] = useState<Map<string, string[]>>(new Map())
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const validateErrors = useCallback(
    debounce(async (_originalPipeline: PipelineInfoConfig, _pipelineSchema: ResponseJsonNode | null): Promise<void> => {
      if (!isNil(_pipelineSchema) && _pipelineSchema.data) {
        const error = await validateJSONWithSchema({ pipeline: _originalPipeline }, _pipelineSchema.data)
        // If you resolved all existing errors then clear the schema error flag
        if (error.size === 0) {
          setSchemaErrorView(false)
        }
        setErrorMap(error)
      }
    }, 300),
    []
  )
 
  useDeepCompareEffect(() => {
    Iif (schemaErrors) {
      validateErrors(originalPipeline, pipelineSchema)
    } else {
      setErrorMap(new Map())
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [originalPipeline, pipelineSchema, schemaErrors])
 
  return { errorMap }
}