Skip to content

Add EachWithOptions for Validating Arrays of Objects#12

Merged
kthehatter merged 2 commits intomainfrom
development/eachwithoptions
Mar 17, 2025
Merged

Add EachWithOptions for Validating Arrays of Objects#12
kthehatter merged 2 commits intomainfrom
development/eachwithoptions

Conversation

@kthehatter
Copy link
Owner

@kthehatter kthehatter commented Mar 16, 2025

Changes:

  1. Added EachWithOptions Function:
    • Validates each element in a slice or array against a set of ValidationOption rules.
    • Supports both map[string]interface{} and structs, converting structs to maps using StructToMap.
    • Returns the first validation error encountered, prefixed with the element’s index (e.g., "element at index 0: 'name' is required").
    • Includes nil and type checks to ensure robust input handling.
  2. Updated StructToMap Function:
    • Converts structs to map[string]interface{} using field names or json tags (e.g., Name with json:"name" maps to "name").
    • Processes only exported fields to avoid reflection panics on unexported fields.
    • Preserves case sensitivity, ensuring keys like "name" and "Name" remain distinct, aligning with JSON’s case-sensitive nature.
  3. Comprehensive Test Suite:
    • Added TestEachWithOptions with cases covering:
      • Valid and invalid arrays of maps and structs.
      • Nil, empty, and non-array inputs.
      • Mixed-case JSON keys (e.g., {"name": "ahmed", "Name": 123}) to verify case sensitivity.
      • Structs with json tags to ensure correct mapping (e.g., Name string json:"name"``).
    • Uses testify/require for assertions, ensuring all edge cases are tested.

Motivation:

  • Enables validation of nested JSON arrays (e.g., {"options": [{"name": "color", "value": "red"}]}).
  • Supports structs unmarshaled from JSON with case-sensitive key matching.
  • Fixes previous issues with unexported fields and incorrect key mapping.

Summary by CodeRabbit

  • New Features

    • Enhanced data validation to apply flexible rules on list inputs, providing detailed error messaging for issues such as missing required values or unexpected data types.
    • Introduced a utility function to convert structs to maps, improving data handling during validation.
  • Tests

    • Expanded test coverage to ensure reliable validation across various input scenarios and edge cases, including handling of required fields and type correctness.

@coderabbitai
Copy link

coderabbitai bot commented Mar 16, 2025

Walkthrough

The changes enhance the validator package by adding a new function EachWithOptions that applies specified validation options to every element of a slice or array. This function checks if the input is nil or not a slice/array, converts structs to maps when needed, and provides detailed error messages for failures. A corresponding test function, TestEachWithOptions, covers various input scenarios. Additionally, the validation logic now checks for missing required fields early, and a utility function StructToMap has been introduced to convert structs to maps via reflection.

Changes

File(s) Change Summary
validator/range.go
validator/range_test.go
Added new function EachWithOptions for per-element validation in slices/arrays, including struct-to-map conversion and comprehensive tests via TestEachWithOptions.
validator/validator.go Introduced a check in Validate to return an error for missing required fields; added the utility function StructToMap to convert structs to maps based on JSON tags, with new imports for reflect and strings.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant EachWithOptions
  participant ElementValidator
  participant StructConverter
  
  Caller->>EachWithOptions: Invoke validator(slice/array)
  EachWithOptions->>EachWithOptions: Check for nil, type, and empty slice/array
  alt Element is present
      EachWithOptions->>ElementValidator: Process element at index i
      alt Element is a struct
          ElementValidator->>StructConverter: Convert struct to map
          StructConverter-->>ElementValidator: Return converted map
      else Element is map
          ElementValidator-->>EachWithOptions: Use element as is
      end
      ElementValidator->>EachWithOptions: Validate with provided options
  else Invalid input
      EachWithOptions-->>Caller: Return error immediately
  end
  EachWithOptions-->>Caller: Return final validation result
Loading

Poem

I hop through lines of code with glee,
Each function blooms like a field to see.
With EachWithOptions, each element's in play,
Structs turn to maps in a magical way.
Tests and checks guard every byte,
A coder rabbit sings through the night!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

level=warning msg="[runner] Can't run linter goanalysis_metalinter: buildir: failed to load package : could not load export data: no export data for "github.com/gin-gonic/gin""
level=error msg="Running error: can't run linter goanalysis_metalinter\nbuildir: failed to load package : could not load export data: no export data for "github.com/gin-gonic/gin""

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72d57e7 and 62551a2.

📒 Files selected for processing (1)
  • validator/validator_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • validator/validator_test.go

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
validator/validator.go (1)

88-111: StructToMap implementation looks good but could handle edge cases better.

The function correctly converts structs to maps using reflection and respects JSON tags. It also properly checks for exported fields. However, it doesn't handle nil or non-struct inputs.

Consider improving robustness with these modifications:

 // StructToMap converts a struct to a map[string]interface{} for validation
 func StructToMap(obj interface{}) map[string]interface{} {
+	if obj == nil {
+		return make(map[string]interface{})
+	}
+
 	result := make(map[string]interface{})
 	v := reflect.ValueOf(obj)
+	
+	// Handle non-struct types
+	if v.Kind() != reflect.Struct {
+		return result
+	}
+	
 	t := reflect.TypeOf(obj)

 	for i := range v.NumField() {
 		field := t.Field(i)
 		// Use the json tag if present, otherwise fall back to field name
 		jsonTag := field.Tag.Get("json")
 		key := field.Name
 		if jsonTag != "" {
 			// Split on "," to handle options like "omitempty"
 			if parts := strings.Split(jsonTag, ","); len(parts) > 0 {
 				key = parts[0]
 			}
 		}
 		// Only process exported fields
 		if field.PkgPath == "" { // PkgPath is empty for exported fields
 			result[key] = v.Field(i).Interface()
 		}
 	}
 	return result
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 48ca92d and 72d57e7.

📒 Files selected for processing (3)
  • validator/range.go (1 hunks)
  • validator/range_test.go (1 hunks)
  • validator/validator.go (3 hunks)
🔇 Additional comments (2)
validator/range.go (1)

113-142: Well-implemented function with thorough error handling.

The new EachWithOptions function provides robust validation for array elements with comprehensive error handling. It handles nil values, type checking, and provides clear error messages with element indices.

One minor suggestion to improve performance:

 // EachWithOptions applies a set of validation options to each element in a slice or array, returning the first error
 func EachWithOptions(options []ValidationOption) ValidatorFunc {
 	return func(value interface{}) error {
 		if value == nil {
 			return fmt.Errorf("value must be a non-nil slice or array")
 		}
 		v := reflect.ValueOf(value)
 		if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
 			return fmt.Errorf("value must be a slice or array, got %T", value)
 		}
 		if v.Len() == 0 {
 			return nil
 		}
+		// Pre-allocate capacity for nestedBody to avoid multiple reallocations
+		nestedBodies := make([]map[string]interface{}, 0, v.Len())
+
 		for i := 0; i < v.Len(); i++ {
 			elem := v.Index(i).Interface()
 			nestedBody, ok := elem.(map[string]interface{})
 			if !ok {
 				if reflect.TypeOf(elem).Kind() == reflect.Struct {
 					nestedBody = StructToMap(elem)
 				} else {
 					return fmt.Errorf("element at index %d must be an object, got %T", i, elem)
 				}
 			}
 			if err := Validate(nestedBody, options); err != nil {
 				return fmt.Errorf("element at index %d: %v", i, err)
 			}
+			nestedBodies = append(nestedBodies, nestedBody)
 		}
 		return nil
 	}
 }

This is an optional optimization that could be useful if you're handling large arrays.

validator/range_test.go (1)

148-257: Comprehensive test coverage with good edge cases.

The test function thoroughly covers various scenarios including happy paths, error cases, and edge conditions. The test cases for mixed-case JSON keys, empty arrays, and struct handling are particularly valuable.

Consider adding one additional test case to verify handling of deeply nested structures:

 		{
 			name: "json with mixed case keys",
 			input: []interface{}{
 				map[string]interface{}{
 					"name":  "ahmed",
 					"Name":  123,
 					"value": "test",
 				},
 			},
 			expected: nil,
 		},
+		{
+			name: "nested structures",
+			input: []interface{}{
+				map[string]interface{}{
+					"name": "parent",
+					"value": map[string]interface{}{
+						"name": "child",
+						"value": "nested",
+					},
+				},
+			},
+			expected: nil,
+		},
 	}

This would help ensure that the validation works correctly with complex nested data structures.

Comment on lines +40 to +43
// Check if the field is required but missing *before* running validators
if !option.IsOptional && !exists {
return fmt.Errorf("%s is required", option.Key)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Code duplication concern.

This new validation check for required fields is duplicated at lines 61-63. Having multiple checks for the same condition can lead to confusion and maintenance issues.

 // Validate checks the request body against the validation options and returns the first error.
 func Validate(body map[string]interface{}, options []ValidationOption) error {
 	for _, option := range options {
 		value, exists := body[option.Key]

 		// Skip validation if the field is optional and not present
 		if option.IsOptional && !exists {
 			continue
 		}

-		// Check if the field is required but missing *before* running validators
-		if !option.IsOptional && !exists {
-			return fmt.Errorf("%s is required", option.Key)
-		}
-
 		// Apply transformations
 		if exists {
 			for _, transformer := range option.Transformers {
 				value = transformer(value)
 			}
 			body[option.Key] = value // Update the body with the transformed value
 		}

 		// Run all validators for the field (if it exists)
 		for _, validator := range option.Validators {
 			if err := validator.Func(value); err != nil {
 				return fmt.Errorf("%s", validator.Message)
 			}
 		}

 		// Check if the field is required but missing
 		if !option.IsOptional && !exists {
 			return fmt.Errorf("'%s' is required", option.Key)
 		}

Either keep only one of the checks or make their purposes clear with improved comments if they serve different purposes.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Check if the field is required but missing *before* running validators
if !option.IsOptional && !exists {
return fmt.Errorf("%s is required", option.Key)
}
// Validate checks the request body against the validation options and returns the first error.
func Validate(body map[string]interface{}, options []ValidationOption) error {
for _, option := range options {
value, exists := body[option.Key]
// Skip validation if the field is optional and not present
if option.IsOptional && !exists {
continue
}
// Apply transformations
if exists {
for _, transformer := range option.Transformers {
value = transformer(value)
}
body[option.Key] = value // Update the body with the transformed value
}
// Run all validators for the field (if it exists)
for _, validator := range option.Validators {
if err := validator.Func(value); err != nil {
return fmt.Errorf("%s", validator.Message)
}
}
// Check if the field is required but missing
if !option.IsOptional && !exists {
return fmt.Errorf("'%s' is required", option.Key)
}
}
return nil
}

@kthehatter kthehatter merged commit 1092010 into main Mar 17, 2025
2 checks passed
@kthehatter kthehatter deleted the development/eachwithoptions branch March 17, 2025 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant