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

     1  package graphql
     2  
     3  import (
     4  	validation "github.com/go-ozzo/ozzo-validation/v4"
     5  	"github.com/kyma-incubator/compass/components/director/internal/model"
     6  	"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
     7  	"github.com/kyma-incubator/compass/components/director/pkg/jsonschema"
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // Validate missing godoc
    12  func (i LabelDefinitionInput) Validate() error {
    13  	return validation.Errors{
    14  		"rule.validSchema": i.validateSchema(),
    15  		"key":              validation.Validate(i.Key, validation.Required, validation.In(model.ScenariosKey)),
    16  		"schema":           validation.Validate(i.Schema),
    17  	}.Filter()
    18  }
    19  
    20  func (i LabelDefinitionInput) validateSchema() error {
    21  	if i.Schema != nil {
    22  		if _, err := jsonschema.NewValidatorFromStringSchema(string(*i.Schema)); err != nil {
    23  			return errors.Wrapf(err, "while validating schema: [%+v]", *i.Schema)
    24  		}
    25  	}
    26  	if i.Key == model.ScenariosKey {
    27  		if err := i.validateScenariosSchema(); err != nil {
    28  			return errors.Wrapf(err, "while validating schema for key %s", model.ScenariosKey)
    29  		}
    30  	}
    31  	return nil
    32  }
    33  
    34  func (i LabelDefinitionInput) validateScenariosSchema() error {
    35  	if i.Schema == nil {
    36  		return apperrors.NewInternalError("schema can not be nil")
    37  	}
    38  
    39  	validator, err := jsonschema.NewValidatorFromRawSchema(model.SchemaForScenariosSchema)
    40  	if err != nil {
    41  		return errors.Wrap(err, "while compiling validator schema")
    42  	}
    43  
    44  	result, err := validator.ValidateString(string(*i.Schema))
    45  	if err != nil {
    46  		return errors.Wrap(err, "while validating new schema")
    47  	}
    48  	if !result.Valid {
    49  		return result.Error
    50  	}
    51  
    52  	return nil
    53  }