All files / modules/75-cd/components/PipelineSteps/HttpStep HttpStep.tsx

98.61% Statements 71/72
75.7% Branches 162/214
93.33% Functions 14/15
98.61% Lines 71/72

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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259              97x 97x 97x 97x 97x 97x 97x   97x 97x     97x 97x   97x 97x 97x 97x     97x   100x 100x 100x                             9x   9x 3x                         6x 2x     4x     1x 15x                     100x 100x 100x 100x 100x               3x 3x   3x         1x       3x         1x       3x         1x       3x 2x                           2x 2x     1x 1x   1x           3x 3x 3x 3x   3x       3x 3x     1x 1x   1x           3x 2x     3x     100x                     100x     7x               7x           3x                       3x                       1x                   1x 1x             1x 1x            
/*
 * 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 from 'react'
import { getMultiTypeFromValue, IconName, MultiTypeInputType, SelectOption } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import * as Yup from 'yup'
import { FormikErrors, yupToFormErrors } from 'formik'
import { v4 as uuid } from 'uuid'
import { isArray, isEmpty, set } from 'lodash-es'
 
import { StepProps, StepViewType, ValidateInputSetProps } from '@pipeline/components/AbstractSteps/Step'
import { getDurationValidationSchema } from '@common/components/MultiTypeDuration/MultiTypeDuration'
import type { HttpHeaderConfig, StringNGVariable } from 'services/cd-ng'
 
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { PipelineStep } from '@pipeline/components/PipelineSteps/PipelineStep'
import type { StringsMap } from 'stringTypes'
import { httpStepType } from './HttpStepBase'
import HttpInputSetStep from './HttpInputSetStep'
import { HttpStepWidgetWithRef } from './HttpStepWidget'
import { HttpStepVariablesView, HttpStepVariablesViewProps } from './HttpStepVariablesView'
import type { HttpStepData, HttpStepFormData, HttpStepHeaderConfig, HttpStepOutputVariable } from './types'
 
export class HttpStep extends PipelineStep<HttpStepData> {
  constructor() {
    super()
    this._hasDelegateSelectionVisible = true
    this._hasStepVariables = true
  }
 
  renderStep(this: HttpStep, props: StepProps<HttpStepData>): JSX.Element {
    const {
      initialValues,
      onUpdate,
      onChange,
      stepViewType,
      inputSetData,
      formikRef,
      customStepProps,
      isNewStep,
      readonly,
      allowableTypes
    } = props
 
    if (stepViewType === StepViewType.InputSet || stepViewType === StepViewType.DeploymentForm) {
      return (
        <HttpInputSetStep
          initialValues={this.processInitialValues(initialValues, true)}
          onUpdate={data => onUpdate?.(this.processFormData(data))}
          stepViewType={stepViewType}
          readonly={!!inputSetData?.readonly}
          template={inputSetData?.template}
          path={inputSetData?.path || ''}
          allowableTypes={allowableTypes}
        />
      )
    }
 
    if (stepViewType === StepViewType.InputVariable) {
      return <HttpStepVariablesView {...(customStepProps as HttpStepVariablesViewProps)} originalData={initialValues} />
    }
 
    return (
      <HttpStepWidgetWithRef
        initialValues={this.processInitialValues(initialValues)}
        onUpdate={data => onUpdate?.(this.processFormData(data))}
        onChange={data => onChange?.(this.processFormData(data))}
        stepViewType={stepViewType}
        isNewStep={isNewStep}
        readonly={!!inputSetData?.readonly}
        allowableTypes={allowableTypes}
        isDisabled={readonly}
        ref={formikRef}
      />
    )
  }
 
  protected type = StepType.HTTP
  protected stepName = 'HTTP Step'
  protected stepIcon: IconName = 'http-step'
  protected stepIconColor = Color.GREY_700
  protected stepDescription: keyof StringsMap = 'pipeline.stepDescription.HTTP'
 
  validateInputSet({
    data,
    template,
    getString,
    viewType
  }: ValidateInputSetProps<HttpStepData>): FormikErrors<HttpStepData> {
    const errors: FormikErrors<HttpStepData> = { spec: {} }
    const isRequired = viewType === StepViewType.DeploymentForm || viewType === StepViewType.TriggerForm
    /* istanbul ignore else */
    if (
      getMultiTypeFromValue(template?.spec?.url) === MultiTypeInputType.RUNTIME &&
      isRequired &&
      isEmpty(data?.spec?.url)
    ) {
      set(errors, 'spec.url', getString?.('fieldRequired', { field: 'URL' }))
    }
 
    /* istanbul ignore else */
    if (
      getMultiTypeFromValue(template?.spec?.method) === MultiTypeInputType.RUNTIME &&
      isRequired &&
      isEmpty(data?.spec?.method)
    ) {
      set(errors, 'spec.method', getString?.('fieldRequired', { field: 'Method' }))
    }
 
    /* istanbul ignore else */
    if (
      getMultiTypeFromValue(template?.spec?.requestBody) === MultiTypeInputType.RUNTIME &&
      isRequired &&
      isEmpty(data?.spec?.requestBody)
    ) {
      set(errors, 'spec.requestBody', getString?.('fieldRequired', { field: 'Request Body' }))
    }
 
    /* istanbul ignore else */
    if ((isArray(template?.spec?.headers) || isArray(template?.spec?.outputVariables)) && getString) {
      const schema = Yup.object().shape({
        spec: Yup.object().shape({
          headers: Yup.array().of(
            Yup.object().shape({
              value: Yup.string().required(getString('common.validation.valueIsRequired'))
            })
          ),
          outputVariables: Yup.array().of(
            Yup.object().shape({
              value: Yup.string().required(getString('common.validation.valueIsRequired'))
            })
          )
        })
      })
      try {
        schema.validateSync(data)
      } catch (e) {
        /* istanbul ignore else */
        if (e instanceof Yup.ValidationError) {
          const err = yupToFormErrors(e)
 
          Object.assign(errors, err)
        }
      }
    }
 
    /* istanbul ignore else */
    if (getMultiTypeFromValue(template?.timeout) === MultiTypeInputType.RUNTIME) {
      let timeoutSchema = getDurationValidationSchema({ minimum: '10s' })
      Eif (isRequired) {
        timeoutSchema = timeoutSchema.required(getString?.('validation.timeout10SecMinimum'))
      }
      const timeout = Yup.object().shape({
        timeout: timeoutSchema
      })
 
      try {
        timeout.validateSync(data)
      } catch (e) {
        /* istanbul ignore else */
        if (e instanceof Yup.ValidationError) {
          const err = yupToFormErrors(e)
 
          Object.assign(errors, err)
        }
      }
    }
 
    /* istanbul ignore else */
    if (isEmpty(errors.spec)) {
      delete errors.spec
    }
 
    return errors
  }
 
  protected defaultValues: HttpStepData = {
    identifier: '',
    name: '',
    type: StepType.HTTP,
    timeout: '10s',
    spec: {
      url: '',
      method: httpStepType[0].value as string
    }
  }
 
  protected isHarnessSpecific = true
 
  private processInitialValues(initialValues: HttpStepData, forInpuSet?: boolean): HttpStepFormData {
    return {
      ...initialValues,
      spec: {
        ...(initialValues.spec as HttpStepFormData),
        method:
          getMultiTypeFromValue(initialValues.spec?.method as string) === MultiTypeInputType.RUNTIME
            ? (initialValues.spec?.method as string)
            : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
              httpStepType.find(step => step.value === (initialValues.spec?.method || 'GET'))!,
        headers:
          getMultiTypeFromValue(initialValues.spec?.headers as string) === MultiTypeInputType.RUNTIME
            ? (initialValues.spec?.headers as string)
            : Array.isArray(initialValues.spec?.headers)
            ? initialValues.spec.headers.map(
                (header: HttpHeaderConfig): HttpStepHeaderConfig => ({
                  ...header,
                  id: uuid()
                })
              )
            : forInpuSet
            ? undefined
            : [],
        outputVariables:
          getMultiTypeFromValue(initialValues.spec?.outputVariables as string) === MultiTypeInputType.RUNTIME
            ? (initialValues.spec?.outputVariables as string)
            : Array.isArray(initialValues.spec?.outputVariables)
            ? initialValues.spec.outputVariables.map((variable: StringNGVariable) => ({
                ...variable,
                id: uuid()
              }))
            : forInpuSet
            ? undefined
            : []
      }
    }
  }
 
  processFormData(data: HttpStepFormData): HttpStepData {
    return {
      ...data,
      spec: {
        ...data.spec,
        method: ((data.spec.method as SelectOption)?.value as string) || data.spec.method?.toString(),
        headers:
          getMultiTypeFromValue(data.spec.headers as string) === MultiTypeInputType.RUNTIME
            ? (data.spec.headers as string)
            : Array.isArray(data.spec.headers)
            ? data.spec.headers
                .filter((variable: HttpStepHeaderConfig) => variable.value)
                .map(({ id, ...header }: HttpStepHeaderConfig) => header)
            : undefined,
        outputVariables:
          getMultiTypeFromValue(data.spec.outputVariables as string) === MultiTypeInputType.RUNTIME
            ? (data.spec.outputVariables as string)
            : Array.isArray(data.spec.outputVariables)
            ? data.spec.outputVariables
                .filter((variable: HttpStepOutputVariable) => variable.value)
                .map(({ id, ...variable }: HttpStepOutputVariable) => variable)
            : undefined
      }
    }
  }
}