github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/graphql/formation_template_validation.go (about)

     1  package graphql
     2  
     3  import (
     4  	"fmt"
     5  
     6  	validation "github.com/go-ozzo/ozzo-validation/v4"
     7  	"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
     8  	"github.com/kyma-incubator/compass/components/director/pkg/inputvalidation"
     9  )
    10  
    11  // Validate missing godoc
    12  func (i FormationTemplateInput) Validate() error {
    13  	fieldRules := []*validation.FieldRules{
    14  		validation.Field(&i.Name, validation.Required, validation.RuneLength(0, longStringLengthLimit)),
    15  		validation.Field(&i.ApplicationTypes, validation.Required, inputvalidation.Each(validation.Required, validation.RuneLength(0, longStringLengthLimit))),
    16  		validation.Field(&i.RuntimeTypes, inputvalidation.Each(validation.Required, validation.RuneLength(0, longStringLengthLimit))),
    17  		validation.Field(&i.Webhooks, validation.By(webhooksRuleFunc)),
    18  	}
    19  
    20  	if i.RuntimeTypeDisplayName != nil && (len(*i.RuntimeTypeDisplayName) == 0 || len(*i.RuntimeTypeDisplayName) > longLongStringLengthLimit) {
    21  		return apperrors.NewInvalidDataError(fmt.Sprintf("Invalid %q: length should be between %q and %q", "RuntimeTypeDisplayName", 0, longLongStringLengthLimit))
    22  	}
    23  
    24  	if !validateRuntimeArtifactKind(i) {
    25  		return apperrors.NewInvalidDataError(fmt.Sprintf("Invalid %q: should be one of %s", "RuntimeArtifactKind", AllArtifactType))
    26  	}
    27  
    28  	if !allRuntimeFieldsArePresent(i) && !allRuntimeFieldsAreMissing(i) {
    29  		return apperrors.NewInvalidDataError("Either all RuntimeTypes, RuntimeArtifactKind and RuntimeArtifactKind fields should be present or all of them should be missing")
    30  	}
    31  
    32  	return validation.ValidateStruct(&i, fieldRules...)
    33  }
    34  
    35  func validateRuntimeArtifactKind(i FormationTemplateInput) bool {
    36  	if i.RuntimeArtifactKind != nil {
    37  		isArtifactTypeValid := false
    38  		for _, artifactType := range AllArtifactType {
    39  			if *i.RuntimeArtifactKind == artifactType {
    40  				isArtifactTypeValid = true
    41  				break
    42  			}
    43  		}
    44  		return isArtifactTypeValid
    45  	}
    46  
    47  	return true
    48  }
    49  
    50  func allRuntimeFieldsAreMissing(i FormationTemplateInput) bool {
    51  	return i.RuntimeArtifactKind == nil && i.RuntimeTypeDisplayName == nil && len(i.RuntimeTypes) == 0
    52  }
    53  
    54  func allRuntimeFieldsArePresent(i FormationTemplateInput) bool {
    55  	return i.RuntimeArtifactKind != nil && i.RuntimeTypeDisplayName != nil && len(i.RuntimeTypes) > 0
    56  }