github.com/kaptinlin/jsonschema@v0.4.6/required.go (about)

     1  package jsonschema
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // EvaluateRequired checks if all the required properties specified in the schema are present in the data object.
     9  // According to the JSON Schema Draft 2020-12:
    10  //   - The value of the "required" keyword must be an array of strings, where each string is a unique property name.
    11  //   - An object instance is valid against this keyword if every item in the array is the name of a property in the instance.
    12  //   - Omitting this keyword has the same behavior as an empty array, meaning no properties are required.
    13  //
    14  // This method ensures that all properties listed as required are present in the data instance.
    15  // If a required property is missing, it returns a EvaluationError detailing the missing properties.
    16  //
    17  // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-required
    18  func evaluateRequired(schema *Schema, object map[string]interface{}) *EvaluationError {
    19  	if schema.Required == nil {
    20  		// No required properties defined, nothing to do.
    21  		return nil
    22  	}
    23  
    24  	// Proceed with checking for required properties only if it is indeed an object.
    25  	var missingProps []string
    26  	for _, propName := range schema.Required {
    27  		if _, exists := object[propName]; !exists {
    28  			missingProps = append(missingProps, propName)
    29  		}
    30  	}
    31  
    32  	if len(missingProps) > 0 {
    33  		if len(missingProps) == 1 {
    34  			return NewEvaluationError("required", "missing_required_property", "Required property {property} is missing", map[string]interface{}{
    35  				"property": fmt.Sprintf("'%s'", missingProps[0]),
    36  			})
    37  		} else {
    38  			quotedProperties := make([]string, len(missingProps))
    39  			for i, prop := range missingProps {
    40  				quotedProperties[i] = fmt.Sprintf("'%s'", prop)
    41  			}
    42  			return NewEvaluationError("required", "missing_required_properties", "Required properties {properties} are missing", map[string]interface{}{
    43  				"properties": strings.Join(quotedProperties, ", "),
    44  			})
    45  		}
    46  	}
    47  
    48  	return nil
    49  }