Skip to content

Conversation

@hi-rai
Copy link
Contributor

@hi-rai hi-rai commented Jan 30, 2025

  • Introduce converter options and use it in NewConverter
  • Add new option to specify handlers for custom validation tags
  • Add support for custom validation tags in all types
  • Improve ignore tags check for all types

Summary by CodeRabbit

  • Documentation

    • Updated usage instructions with comprehensive examples and new sections on custom validations and handling of ignored parameters.
  • New Features

    • Enhanced conversion configuration with flexible options for custom validations, enabling more granular control over schema generation.
  • Chores

    • Upgraded tooling and dependencies to support the latest runtime and development standards.

@coderabbitai
Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request updates the converter initialization approach, replacing direct calls to zen.NewConverter with the new zen.NewConverterWithOpts() that accepts configurable options. The documentation in the README is enhanced with new sections (Custom Tags, Custom Types, and Ignored Tags) and updated examples. Test files and the main converter code (zod.go) are updated to use the new options-based configuration. CI configurations and module Go versions are also upgraded, ensuring consistency across the repository.

Changes

Files Change Summary
README.md, zod.go Updated converter initialization to use zen.NewConverterWithOpts(), added new option functions (WithPrefix, WithCustomTypes, WithCustomTags, and WithIgnoreTags), and enhanced documentation with new sections for custom tags, types, and ignored tags.
custom/decimal/decimal_test.go, custom/optional/optional_test.go, zod_test.go Modified tests to initialize the converter using options (via zen.WithCustomTypes), and added a new test (TestCustomTag) to validate custom tag handling and schema generation.
.github/workflows/ci.yml, .golangci.yml, Makefile Upgraded CI configurations: updated Go version (from ^1.21.3 to ^1.23.5), actions versions (setup-go from v4 to v5, golangci-lint from v1.59/v1.52.2 to v1.63/v1.63.4) and restructured file exclusion in the linter configuration.
go.mod, custom/decimal/go.mod, custom/optional/go.mod Upgraded Go language version from 1.21 to 1.23 in the module manifests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Converter
    participant OptionHandler
    Client->>Converter: NewConverterWithOpts(opts...)
    Note right of Converter: Process options (custom types, tags, ignore tags)
    Converter->>OptionHandler: Apply configuration
    OptionHandler-->>Converter: Options applied
    Client->>Converter: Convert struct to Zod schema
    Converter->>Client: Return schema with validations
Loading
sequenceDiagram
    participant Test
    participant Converter
    participant CustomTagHandler
    Test->>Converter: Initialize with custom tag options
    Converter->>CustomTagHandler: Retrieve handler for custom tags
    CustomTagHandler-->>Converter: Provide validation rules
    Converter->>Test: Generate Zod schema
    Test->>Test: Assert schema correctness
Loading

Possibly related PRs

Suggested reviewers

  • ramilamparo
  • AndrianBdn
  • satvik007

Poem

I'm a rabbit hopping through the code,
Leaping over options in a bouncy mode.
Custom tags and types now play,
Converters refined in a clever way.
With each change, I smile with glee,
CodeRabbit cheers—oh happy to be!
🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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.

@hi-rai
Copy link
Contributor Author

hi-rai commented Jan 30, 2025

The changes are required for improving SortField validations as mentioned in https://github.com/Hypersequent/tms-issues/issues/1300

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 (9)
zod.go (7)

15-21: Consider validating or documenting prefix constraints.

If conflicting prefixes are passed in different calls, unexpected naming collisions might occur.


377-449: Large block in convertStruct and related validations.

This block is quite extensive. Consider splitting it into smaller helper functions for maintainability.


582-619: Array and slice validation expanded.

Logic is correct but quite lengthy; consider modularizing repeated validation patterns.


726-805: convertMap handles map validations thoroughly.

Suggestion: unify or standardize the refinement error messages so they follow a similar wording style.


Line range hint 890-966: validateNumber covers many numeric validations.

Consider extracting repeated logic (e.g., parse integer steps) into a helper for cleaner code.


Line range hint 972-1170: validateString parallels validateNumber.

Similar refactoring could reduce duplication and improve readability.


Line range hint 2137-2184: Added TestCustomTag test coverage.

Excellent demonstration of how custom tag handlers can extend the validation logic. Consider including a negative test case to ensure refinements catch errors properly.

custom/optional/optional_test.go (1)

13-16: LGTM! Consider adding a test case for invalid usage.

The changes correctly implement the new options-based configuration system. The test demonstrates proper initialization of the converter with custom type handlers.

Consider adding a negative test case to verify that the converter properly handles invalid optional types or missing handlers.

README.md (1)

297-300: Enhance decimal type handler with validation.

The current implementation could be improved by:

  1. Handling validation tags
  2. Adding refinements for valid decimal strings

Consider this enhanced implementation:

 customTypeHandlers := map[string]zen.CustomFn{
 	"github.com/shopspring/decimal.Decimal": func (c *zen.Converter, t reflect.Type, v string, indent int) string {
-		// Shopspring's decimal type serialises to a string.
-		return "z.string()"
+		// Validate decimal string format and handle validation tags
+		base := "z.string().refine((val) => /^-?\\d*\\.?\\d+$/.test(val), 'Invalid decimal format')"
+		if v != "" {
+			return base + "." + v
+		}
+		return base
 	},
 }
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

297-297: Hard tabs
Column: 1

(MD010, no-hard-tabs)


298-298: Hard tabs
Column: 1

(MD010, no-hard-tabs)


299-299: Hard tabs
Column: 1

(MD010, no-hard-tabs)


300-300: Hard tabs
Column: 1

(MD010, no-hard-tabs)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5f01b1b and af781c8.

📒 Files selected for processing (5)
  • README.md (3 hunks)
  • custom/decimal/decimal_test.go (1 hunks)
  • custom/optional/optional_test.go (1 hunks)
  • zod.go (17 hunks)
  • zod_test.go (6 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

221-221: Hard tabs
Column: 1

(MD010, no-hard-tabs)


222-222: Hard tabs
Column: 1

(MD010, no-hard-tabs)


226-226: Hard tabs
Column: 1

(MD010, no-hard-tabs)


227-227: Hard tabs
Column: 1

(MD010, no-hard-tabs)


228-228: Hard tabs
Column: 1

(MD010, no-hard-tabs)


229-229: Hard tabs
Column: 1

(MD010, no-hard-tabs)


230-230: Hard tabs
Column: 1

(MD010, no-hard-tabs)


231-231: Hard tabs
Column: 1

(MD010, no-hard-tabs)


235-235: Hard tabs
Column: 1

(MD010, no-hard-tabs)


236-236: Hard tabs
Column: 1

(MD010, no-hard-tabs)


237-237: Hard tabs
Column: 1

(MD010, no-hard-tabs)


238-238: Hard tabs
Column: 1

(MD010, no-hard-tabs)


239-239: Hard tabs
Column: 1

(MD010, no-hard-tabs)


240-240: Hard tabs
Column: 1

(MD010, no-hard-tabs)


241-241: Hard tabs
Column: 1

(MD010, no-hard-tabs)


242-242: Hard tabs
Column: 1

(MD010, no-hard-tabs)


243-243: Hard tabs
Column: 1

(MD010, no-hard-tabs)


244-244: Hard tabs
Column: 1

(MD010, no-hard-tabs)


245-245: Hard tabs
Column: 1

(MD010, no-hard-tabs)


246-246: Hard tabs
Column: 1

(MD010, no-hard-tabs)


247-247: Hard tabs
Column: 1

(MD010, no-hard-tabs)


297-297: Hard tabs
Column: 1

(MD010, no-hard-tabs)


298-298: Hard tabs
Column: 1

(MD010, no-hard-tabs)


299-299: Hard tabs
Column: 1

(MD010, no-hard-tabs)


300-300: Hard tabs
Column: 1

(MD010, no-hard-tabs)


306-306: Hard tabs
Column: 1

(MD010, no-hard-tabs)


314-314: Hard tabs
Column: 1

(MD010, no-hard-tabs)

🔇 Additional comments (19)
zod.go (15)

12-14: Introduce Opt type for extensible converter configuration.

This is a clean solution for passing behavior modifications into the converter.


22-31: WithCustomTypes approach is straightforward.

No issues found. The iteration over the provided map is an effective way to register custom types.


33-42: WithCustomTags aligns well with the existing extension mechanism.

No specific concerns here. The reusability of CustomFn for tag-based logic is a nice touch.


44-51: Confirm ignoring tags behaves as expected.

Ensure that ignoring a tag doesn’t mask critical validations. Consider clarifying in docs that unknown, unignored tags panic.


52-63: Ensure thread safety in NewConverter.

If multiple goroutines call methods on the same converter instance, we might need synchronization around shared maps (customTypes, customTags, etc.).


70-70: No functional changes in doc comment.


112-113: Enhanced flexibility with variadic opts in StructToZodSchema.

This is beneficial for passing multiple configuration options. Looks great.


156-162: Added new fields (prefix, customTypes, customTags, ignoreTags) to Converter.

They make the internal state more explicit. No issues detected.


345-345: Refactor check for custom types is concise.

Looks good. Just ensure customTypes is not modified concurrently without a lock, if concurrency is a concern.


521-521: Detecting custom types in convertField.

No concerns. The logic for isCustom is straightforward.


557-557: Reused pattern for detecting custom types in getTypeField.

No issues; consistent usage.


621-666: Robust validation switch for arrays.

Double-check off-by-one logic for “gt/lt” transformations. Also watch out for panic messages being descriptive enough.


671-679: Completes array length checks for fixed-length arrays.

Implementation looks consistent.


878-878: Ignore tag check is straightforward.

No concerns here.


Line range hint 2136-2136: No functional changes on this blank line.

custom/decimal/decimal_test.go (1)

14-17: Refactored to use WithCustomTypes for converter initialization.

This approach is consistent with the new options-based initialization in zod.go.

zod_test.go (2)

6-6: Imported strings package.

No issues; presumably used for test logic or helper methods.


2137-2184: Comprehensive example in TestCustomTag.

Demonstrates usage of multiple custom tag handlers. The .extend() usage is especially helpful for advanced validations.

README.md (1)

5-5: LGTM! Good addition of the reference link.

Adding the link to go-validator repository improves documentation by providing direct access to the underlying validation library.

* Introduce converter options and use it in NewConverter
* Add new option to specify handlers for custom validation tags
* Add support for custom validation tags in all types
* Improve ignore tags check for all types
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Nitpick comments (5)
notes (5)

1-2: Consider merging top-level conversion logic for maintainability.
Both convertStructTopLevel and getType have similar responsibilities: handling the reflection logic required to process a type. If these grow in complexity, consider abstracting shared logic into a helper function to reduce duplication.


4-5: Extract common parts of struct conversion.
convertStruct and getTypeStruct appear to serve complementary purposes (converting vs. retrieving type info). In the future, if they expand, watch for opportunities to factor out common reflection or error handling code for improved readability.


7-8: Ensure consistent field handling and reduce potential duplication.
convertField vs. getTypeField might introduce duplicated logic when applying custom validation or optional checks. Consider consolidating repeated checks (e.g., optional, nullable, or anonymous logic) in a shared helper to avoid divergence.


27-30: Add clarifying comment about purpose of entry.
Since entry tracks an order and data, consider adding a short doc comment indicating its role in conversion output ordering (e.g., “Represents a single unit of generated output with a defined insertion order”).


37-38: Enhance documentation for CustomFn.
CustomFn is a powerful extension point. A short comment specifying how each parameter is used (e.g., reflect.Type = the current type, string = the name, etc.) would clarify usage for future developers.

🛑 Comments failed to post (3)
.github/workflows/ci.yml (2)

24-24: ⚠️ Potential issue

Invalid Go version specified.

The specified Go version 1.23.5 does not exist yet. The latest stable version of Go is in the 1.21.x series.

-          go-version: '^1.23.5'
+          go-version: '^1.21.5'

Also applies to: 26-26


41-41: 🛠️ Refactor suggestion

Ensure consistent golangci-lint versions.

The golangci-lint version v1.63 in the CI workflow should match exactly with the version v1.63.4 specified in the Makefile to ensure consistent behavior.

-          version: v1.63
+          version: v1.63.4
📝 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.

          version: v1.63.4
notes (1)

16-17: 🛠️ Refactor suggestion

Handle advanced string/number validation.
The current validateString and validateNumber placeholders suggest potential for deeper rule sets (e.g., regex patterns for strings or range checks for numbers). Consider introducing an extensible mechanism for advanced validations.

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: 0

🧹 Nitpick comments (4)
zod_test.go (2)

2152-2166: Consider enhancing validation patterns.

While the implementation is solid, consider these improvements:

  1. Make the identifier regex pattern more descriptive with a named constant
  2. Add length validation for the identifier
  3. Add range validation for pageParams (e.g., maximum allowed page size)
 customTagHandlers := map[string]CustomFn{
     "identifier": func(c *Converter, t reflect.Type, validate string, i int) string {
-        return ".refine((val) => !val || /^[a-z0-9_]*$/.test(val), 'Invalid search identifier')"
+        const identifierPattern = "^[a-z0-9_]{1,64}$"
+        return fmt.Sprintf(".refine((val) => !val || new RegExp('%s').test(val), 'Invalid search identifier: must be 1-64 characters of lowercase letters, numbers, or underscores')", identifierPattern)
     },
     "pageParams": func(c *Converter, t reflect.Type, validate string, i int) string {
-        return ".refine((val) => !val.start || !val.end || val.start < val.end, 'Start should be less than end')"
+        return `.refine((val) => !val.start || !val.end || val.start < val.end, 'Start should be less than end')` +
+               `.refine((val) => !val.end || val.end <= 1000, 'Maximum page size exceeded')`
     },

2168-2183: Add test coverage for edge cases.

Consider adding test cases for:

  1. Empty/invalid sort fields
  2. Negative page numbers
  3. Maximum page size limits
  4. Special characters in identifiers
func TestCustomTagEdgeCases(t *testing.T) {
    type RequestEdgeCases struct {
        SortParams       `validate:"sortFields="`  // Empty sort fields
        PaginationParams struct {
            Start *int `json:"start,omitempty" validate:"omitempty,gt=-1"` // Negative pages
            End   *int `json:"end,omitempty" validate:"omitempty,gt=0,lte=1000"` // Max page size
        } `validate:"pageParams"`
        Search *string `json:"search,omitempty" validate:"identifier"` // Special chars
    }
    
    // Add assertions here
}
README.md (1)

215-328: Fix markdown formatting issues.

The documentation content is clear and well-structured, but there are formatting inconsistencies with tabs vs spaces. Convert all tabs to spaces for consistent formatting.

-	"identifier": func(c *zen.Converter, t reflect.Type, validate string, indent int) string {
+    "identifier": func(c *zen.Converter, t reflect.Type, validate string, indent int) string {
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

221-221: Hard tabs
Column: 1

(MD010, no-hard-tabs)


222-222: Hard tabs
Column: 1

(MD010, no-hard-tabs)


226-226: Hard tabs
Column: 1

(MD010, no-hard-tabs)


227-227: Hard tabs
Column: 1

(MD010, no-hard-tabs)


228-228: Hard tabs
Column: 1

(MD010, no-hard-tabs)


229-229: Hard tabs
Column: 1

(MD010, no-hard-tabs)


230-230: Hard tabs
Column: 1

(MD010, no-hard-tabs)


231-231: Hard tabs
Column: 1

(MD010, no-hard-tabs)


235-235: Hard tabs
Column: 1

(MD010, no-hard-tabs)


236-236: Hard tabs
Column: 1

(MD010, no-hard-tabs)


237-237: Hard tabs
Column: 1

(MD010, no-hard-tabs)


238-238: Hard tabs
Column: 1

(MD010, no-hard-tabs)


239-239: Hard tabs
Column: 1

(MD010, no-hard-tabs)


240-240: Hard tabs
Column: 1

(MD010, no-hard-tabs)


241-241: Hard tabs
Column: 1

(MD010, no-hard-tabs)


242-242: Hard tabs
Column: 1

(MD010, no-hard-tabs)


243-243: Hard tabs
Column: 1

(MD010, no-hard-tabs)


244-244: Hard tabs
Column: 1

(MD010, no-hard-tabs)


245-245: Hard tabs
Column: 1

(MD010, no-hard-tabs)


246-246: Hard tabs
Column: 1

(MD010, no-hard-tabs)


247-247: Hard tabs
Column: 1

(MD010, no-hard-tabs)


297-297: Hard tabs
Column: 1

(MD010, no-hard-tabs)


298-298: Hard tabs
Column: 1

(MD010, no-hard-tabs)


299-299: Hard tabs
Column: 1

(MD010, no-hard-tabs)


300-300: Hard tabs
Column: 1

(MD010, no-hard-tabs)


306-306: Hard tabs
Column: 1

(MD010, no-hard-tabs)


314-314: Hard tabs
Column: 1

(MD010, no-hard-tabs)

zod.go (1)

Line range hint 878-885: Consider enhancing error handling for ignored tags.

The current implementation silently ignores unknown tags. Consider adding logging or validation to help catch mistyped tag names.

 func (c *Converter) checkIsIgnored(part string) bool {
+    // Create a map for O(1) lookup
+    ignoredTags := make(map[string]bool)
+    for _, tag := range c.ignoreTags {
+        ignoredTags[tag] = true
+    }
+    
+    isIgnored := ignoredTags[part]
+    if isIgnored {
+        // Optional: Log ignored tags to help catch mistakes
+        log.Printf("Ignoring validation tag: %s", part)
+    }
+    return isIgnored
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 526ead5 and 1c52350.

⛔ Files ignored due to path filters (1)
  • go.work is excluded by !**/*.work
📒 Files selected for processing (11)
  • .github/workflows/ci.yml (2 hunks)
  • .golangci.yml (1 hunks)
  • Makefile (1 hunks)
  • README.md (3 hunks)
  • custom/decimal/decimal_test.go (1 hunks)
  • custom/decimal/go.mod (1 hunks)
  • custom/optional/go.mod (1 hunks)
  • custom/optional/optional_test.go (1 hunks)
  • go.mod (1 hunks)
  • zod.go (17 hunks)
  • zod_test.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • go.mod
  • custom/decimal/go.mod
  • Makefile
  • .golangci.yml
  • custom/optional/optional_test.go
  • custom/decimal/decimal_test.go
  • .github/workflows/ci.yml
  • custom/optional/go.mod
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

221-221: Hard tabs
Column: 1

(MD010, no-hard-tabs)


222-222: Hard tabs
Column: 1

(MD010, no-hard-tabs)


226-226: Hard tabs
Column: 1

(MD010, no-hard-tabs)


227-227: Hard tabs
Column: 1

(MD010, no-hard-tabs)


228-228: Hard tabs
Column: 1

(MD010, no-hard-tabs)


229-229: Hard tabs
Column: 1

(MD010, no-hard-tabs)


230-230: Hard tabs
Column: 1

(MD010, no-hard-tabs)


231-231: Hard tabs
Column: 1

(MD010, no-hard-tabs)


235-235: Hard tabs
Column: 1

(MD010, no-hard-tabs)


236-236: Hard tabs
Column: 1

(MD010, no-hard-tabs)


237-237: Hard tabs
Column: 1

(MD010, no-hard-tabs)


238-238: Hard tabs
Column: 1

(MD010, no-hard-tabs)


239-239: Hard tabs
Column: 1

(MD010, no-hard-tabs)


240-240: Hard tabs
Column: 1

(MD010, no-hard-tabs)


241-241: Hard tabs
Column: 1

(MD010, no-hard-tabs)


242-242: Hard tabs
Column: 1

(MD010, no-hard-tabs)


243-243: Hard tabs
Column: 1

(MD010, no-hard-tabs)


244-244: Hard tabs
Column: 1

(MD010, no-hard-tabs)


245-245: Hard tabs
Column: 1

(MD010, no-hard-tabs)


246-246: Hard tabs
Column: 1

(MD010, no-hard-tabs)


247-247: Hard tabs
Column: 1

(MD010, no-hard-tabs)


297-297: Hard tabs
Column: 1

(MD010, no-hard-tabs)


298-298: Hard tabs
Column: 1

(MD010, no-hard-tabs)


299-299: Hard tabs
Column: 1

(MD010, no-hard-tabs)


300-300: Hard tabs
Column: 1

(MD010, no-hard-tabs)


306-306: Hard tabs
Column: 1

(MD010, no-hard-tabs)


314-314: Hard tabs
Column: 1

(MD010, no-hard-tabs)

🔇 Additional comments (2)
zod_test.go (1)

2137-2184: Well-structured test implementation for custom validation tags!

The test provides good coverage of the new custom tag functionality:

  • Validates search identifiers with regex
  • Ensures proper page parameter validation
  • Implements sort field validation using enums
  • Handles optional fields correctly
zod.go (1)

12-50: Well-structured option pattern implementation!

The option pattern implementation is clean and extensible. Each option function is well-documented and has a single responsibility.

Copy link

@ramilamparo ramilamparo left a comment

Choose a reason for hiding this comment

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

Looks good! Thanks @hi-rai

Copy link
Collaborator

@satvik007 satvik007 left a comment

Choose a reason for hiding this comment

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

Thanks @hi-rai for the PR.

This package is used by many external users as well and we shouldn't break public API like this. We can deprecate parts and remove them in time.

Comment on lines +241 to +247
"sortFields": func(c *zen.Converter, t reflect.Type, validate string, indent int) string {
sortFields := strings.Split(validate, " ")
for i := range sortFields {
sortFields[i] = fmt.Sprintf("'%s'", sortFields[i])
}
return fmt.Sprintf(".extend({field: z.enum([%s])})", strings.Join(sortFields, ", "))
},
Copy link
Collaborator

Choose a reason for hiding this comment

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

Seems quite useful for building advanced use cases.

Does go-validator just ignore these custom tags? If thats the case it may be better to use a new tag for it (zod:"identifier" or zen:"identifier"), to make it clear this validation won't run at go level.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is intended for two cases

  1. User wants to overwrite the default behavior of zen for a tag supported out of the box
  2. User wants support for some go-validator tag not supported by zen out of the box, or when user has added their own custom go-validator tag

@hi-rai hi-rai requested a review from satvik007 February 13, 2025 04:48
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: 2

♻️ Duplicate comments (1)
README.md (1)

239-239: ⚠️ Potential issue

Fix logical error in pageParams validation.

This validation logic was previously identified as incorrect. The current implementation allows start to be greater than end.

Apply this fix:

-    return ".refine((val) => !val.start || !val.end || val.start < val.end, 'Start should be less than end')"
+    return ".refine((val) => !val.start || !val.end || val.start <= val.end, 'Start should be less than or equal to end')"
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

239-239: Hard tabs
Column: 1

(MD010, no-hard-tabs)

🧹 Nitpick comments (40)
notes (9)

4-5: Provide function bodies or documentation.

convertStruct and getTypeStruct currently lack implementations. If they are intentionally unimplemented, please add explanatory comments describing their expected usage and future implementation plans.


10-11: Add slice/array conversion logic or docstrings.

convertSliceAndArray and getTypeSliceAndArray are placeholders. Insert the necessary reflection-based logic or at least stub out the approach to guide other developers.


16-17: Provide string/number validation logic.

validateString and validateNumber appear to be core validation hooks, but they have no bodies. Ensure you either provide or reference validation logic here.


19-25: Document the Converter struct.

The Converter struct fields (e.g., prefix, outputs, custom) are not explained. Adding doc comments or usage notes will help maintainers understand how these fields factor into code generation.


27-31: Consider clarifying entry type usage.

This struct likely holds schema data with an ordering index. Brief doc comments could clarify how and where ordering is used.


32-36: Document the meta type.

The Name and SelfRef fields suggest cycle detection for nested types, but there’s no explanation on usage patterns. Adding references or doc comments will aid future contributors.


37-38: Improve clarity around CustomFn.

This function signature’s parameters and usage are non-trivial. Consider explaining each parameter (especially the strings) for maintainability.


40-45: Optional: use sort.Slice instead of byOrder.

While byOrder works, using Go’s sort.Slice might be simpler and more succinct. If you keep byOrder, consider doc comments explaining your approach to ordering.


50-50: Clarify the purpose of Export().

Export often returns code or strings describing schemas. Since there’s no implementation here, consider adding either a docstring or a TODO for consistency.

zod.go (29)

12-13: Use consistent doc comments for exported entities.

The Opt type is exported but only briefly documented. Ensure all exported constructs follow a uniform documentation style for clarity.


33-42: Ensure custom tag functions do not conflict with ignore or built-in tags.

WithCustomTags merges user-provided tag handlers. If a user-supplied tag duplicates a built-in tag, your code might panic or produce unexpected results. Consider adding safe-guards.


52-67: Consider deprecating the old converter function or merging updates.

NewConverterWithOpts is a more flexible initialization path. Ensure existing calls to NewConverter are redirected or clearly deprecated to avoid confusion.


125-126: Use consistent naming conventions.

StructToZodSchema now accepts opts ...Opt but returns only a string. Consider a naming pattern like ConvertStructWithOpts or similar, for clarity.


413-430: Ensure unknown validations throw a consistent error message.

Panics are triggered for unrecognized tags. This is correct but might hamper debugging in large codebases. Provide more context (e.g., field name, struct name).


495-529: Refactor: unify generate-then-merge approach.

Your typed field conversion merges optional, nullable metadata with reflection logic. Consider a single function that composes these calls for consistent handling across all field types, avoiding duplication.


566-603: Improve slice/array validation structure.

This chunk includes branching for arrays vs slices, plus large switch cases for min/max/len. Consider mapping these validations to a simpler DSL or helper to reduce complexity.


653-681: Type-check map key reflection.

Coercing date or number keys is correct but can open corner cases (e.g., negative zeros, invalid date strings). If that’s undesired, log or handle such edge cases.


683-734: Extract repeated refine logic.

Many lines add .refine(...) statements for map sizes. Consolidating them into a helper function (e.g., addMapSizeRefines(map, min, max)) can reduce duplication.


807-813: Confirm handling of ignore tags.

You compare each part to c.ignoreTags. If we truly want to skip them, ensure partial matches or duplicates are also handled as expected.


818-829: Enforce consistent error messages for unknown numeric validations.

“unknown validation” panic is correct. However, mention which field or reflect type, to speed up debugging if a dev is uncertain about the failing code path.


856-866: Ensure user sees the reason behind the .refine((val) => val !== 0).

In some code paths, “required” leads to .refine((val) => val !== 0) on numbers. Possibly add a message “Number cannot be 0 if required” for clarity.


923-981: Expand coverage for advanced string validations.

One-of, len, min, max, etc. are well handled. For more advanced validations, consider an extension or plugin mechanism if user code requires more robust or custom patterns.


992-1043: Consider generalizing your approach to UUID validations.

You have separate tags for uuid, uuid3, uuid4, etc. This might be simplified with a single tag parameter or advanced pattern matching, e.g., “uuid(version=3)”.


1048-1054: Fail gracefully if no recognized values appear after uuid_rfc4122.

In case the developer tries uuid_rfc4122=someValue, it might incorrectly parse. Currently, a panic might happen, but a user-friendly error or fallback might be better.


1080-1088: Caution with json refine approach.

You refine by calling JSON.parse. If the user’s environment or content is invalid JSON, they get “false” with minimal context. Logging or returning an error might help debug.


1117-1118: Recheck logic for omitempty slices/maps.

At line 1117, if it’s optional, it’s no longer nullable. This is correct per the code’s approach, but confirm it meets user expectations for zero-length vs. null vs. omitted.


1163-1166: Include reason in doc for omitzero.

omitzero is recognized similarly to omitempty. Document this, so others know it prevents null export for zero-value slices/maps.


1184-1187: Surface cycle detection details.

Panic is thrown for self-referential cycles. Possibly add a message about which struct triggered the error to help debugging.


1198-1205: Capitalize generics carefully.

getTypeNameWithGenerics capitalizes each type param’s first letter. This can cause collisions if the generics were already uppercase. Add a check or doc note that all generic type arg names become Title-cased.


1274-1278: Validate direct maps or slices with empty tags.

In lines 1274–1278, we see mapWithStruct: z.record(...). Confirm that untagged fields with default reflect logic produce correct results. Possibly add a test for untagged nested maps.


1313-1321: Append doc references to combined merges.

At line 1320-1321, .merge(...) is used multiple times. Newcomers might not realize it merges Zod schemas. Add inline doc or references to official Zod docs.


1377-1381: Simplify multiple .refine calls.

Lines 1377–1381 layer multiple refines. A single .refine with combined conditions or a helper function might declutter the code and unify messages.


1421-1422: Consider upstream documentation for “Map too large” or “wrong size.”

Your user-facing error strings seem helpful. Make sure docs or a readme clarify that these are thrown by zod refinements at runtime.


1459-1460: Confirm dive usage for nested validations.

You handle nested map validations with dive tags. If multiple dive levels are used, it can become complex. Ensure your test coverage includes multi-level nested maps or slices.


1481-1482: Confirm multi-level keys usage.

At lines 1481–1482, you apply z.record(z.string().min(3), z.string().max(4)) for keys and values. If developers nest more keys after endkeys, ensure your logic merges them properly.


1641-1645: Evaluate potential collisions in advanced interface usage.

You map all interface pointers to z.any(). If user code wants tighter checks (like shape constraints), provide a mechanism or note it in docs.


1778-1802: Check behavior for multiple calls to ConvertSlice.

You add types Zip{}, Whim{} into ConvertSlice with NewConverterWithOpts(). If multiple slices are passed consecutively, ensure no overwriting or missed merges in the final output.


1979-1983: Carefully handle the decimal custom type.

Mapping decimals to z.string() might limit numeric usage. If decimals need numeric comparisons, consider returning z.string().regex(...) or a custom refine. Check user expectations.

zod_test.go (1)

2136-2184: Expand custom tag test coverage.

TestCustomTag verifies one scenario with sortFields, identifier, and pageParams. Consider adding negative test cases (e.g., invalid sort field or start >= end) to ensure error paths work correctly.

README.md (1)

287-287: Clarify the example to avoid confusion.

The example uses "identifier" as an ignored tag, but this same tag is used as a custom tag in the previous section. Consider using a different tag name in this example to avoid confusion.

-opt := zen.WithIgnoreTags("identifier")
+opt := zen.WithIgnoreTags("custom_format")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c52350 and 22a7f6b.

📒 Files selected for processing (6)
  • README.md (4 hunks)
  • custom/decimal/decimal_test.go (1 hunks)
  • custom/optional/optional_test.go (1 hunks)
  • notes (1 hunks)
  • zod.go (20 hunks)
  • zod_test.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • custom/optional/optional_test.go
  • custom/decimal/decimal_test.go
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

117-117: Hard tabs
Column: 1

(MD010, no-hard-tabs)


221-221: Hard tabs
Column: 1

(MD010, no-hard-tabs)


222-222: Hard tabs
Column: 1

(MD010, no-hard-tabs)


226-226: Hard tabs
Column: 1

(MD010, no-hard-tabs)


227-227: Hard tabs
Column: 1

(MD010, no-hard-tabs)


228-228: Hard tabs
Column: 1

(MD010, no-hard-tabs)


229-229: Hard tabs
Column: 1

(MD010, no-hard-tabs)


230-230: Hard tabs
Column: 1

(MD010, no-hard-tabs)


231-231: Hard tabs
Column: 1

(MD010, no-hard-tabs)


235-235: Hard tabs
Column: 1

(MD010, no-hard-tabs)


236-236: Hard tabs
Column: 1

(MD010, no-hard-tabs)


237-237: Hard tabs
Column: 1

(MD010, no-hard-tabs)


238-238: Hard tabs
Column: 1

(MD010, no-hard-tabs)


239-239: Hard tabs
Column: 1

(MD010, no-hard-tabs)


240-240: Hard tabs
Column: 1

(MD010, no-hard-tabs)


241-241: Hard tabs
Column: 1

(MD010, no-hard-tabs)


242-242: Hard tabs
Column: 1

(MD010, no-hard-tabs)


243-243: Hard tabs
Column: 1

(MD010, no-hard-tabs)


244-244: Hard tabs
Column: 1

(MD010, no-hard-tabs)


245-245: Hard tabs
Column: 1

(MD010, no-hard-tabs)


246-246: Hard tabs
Column: 1

(MD010, no-hard-tabs)


247-247: Hard tabs
Column: 1

(MD010, no-hard-tabs)


297-297: Hard tabs
Column: 1

(MD010, no-hard-tabs)


298-298: Hard tabs
Column: 1

(MD010, no-hard-tabs)


299-299: Hard tabs
Column: 1

(MD010, no-hard-tabs)


300-300: Hard tabs
Column: 1

(MD010, no-hard-tabs)


306-306: Hard tabs
Column: 1

(MD010, no-hard-tabs)


314-314: Hard tabs
Column: 1

(MD010, no-hard-tabs)

🔇 Additional comments (22)
notes (4)

1-2: Implement or document these top-level struct conversion functions.

Both convertStructTopLevel and getType are declared without bodies. If they are placeholders, consider adding implementation logic or stub documentation to clarify their intended behavior.


7-8: Consider adding implementations or docs for field conversion functions.

convertField and getTypeField are declared without bodies, making it unclear how fields are processed. Document or implement these functions to avoid confusion.


13-14: Implement or clarify map conversion methods.

convertMap and getTypeMap are declared but have no implementations. Document or implement your intended approach for map handling.


46-49: Confirm these top-level converter methods are intentionally empty.

AddType, Convert, ConvertSlice, ConvertType do not show any body or return statements, which is unusual. Ensure these are either incomplete stubs or meant to be embedded from another partial file.

zod.go (16)

15-20: Confirm prefix usage and possible collisions.

Using a single prefix might cause naming conflicts if multiple prefixes are set by different calls. Consider adding validations/logging or clarifying that only one prefix is valid at a time.


22-31: Check that customTypes merges are intentional.

When merging the custom map in WithCustomTypes, keys from subsequent calls might overwrite earlier ones. If partial merging is intended, consider warnings or fallback logic.


72-73: Check for backward compatibility.

Previously, NewConverter might not have allocated outputs or customTypes. This is a breaking change if user code relied on nil maps. Document or handle potential breakage gracefully.


358-358: Safeguard map lookups in handleCustomType.

c.customTypes[fullName] is retrieved without any fallback. If the fullName is subject to reflection anomalies, consider defensive checks or logs.


629-641: Return type clarity.

convertSliceAndArray returns "z.<type>().array()" but sometimes also adds refine calls. Confirm the final string is always valid. Complex combos might require additional parentheses or chaining checks.


840-848: Validate presence of a valid number set for .oneof.

You parse the values and build a refinement list. Maybe confirm each parsed token is an integer. If a developer uses a string or float by mistake, the error might be cryptic.


1102-1104: Guard pointer logic for string or interface fields.

You check pointer emptiness in isNullable. For complex pointer-of-pointer or interface-of-pointer scenarios, ensure consistent nullability across all passes.


1264-1267: Ensure pointer or interface usage with json:",omitempty" is tested thoroughly.

Potentially, repeated calls might cause unexpected behavior if multiple fields are pointers or interfaces with the same tag. Add tests or doc clarifications.


1280-1283: Double-check optional + .nullable() usage.

Setting both “optional()” and “nullable()” is sometimes redundant. Confirm that merging these does not produce unexpected union types in TypeScript.


1296-1299: Test or handle large nested maps.

If your reflection approach must handle extremely nested maps, consider performance testing or short-circuit checks to avoid potential stack blowouts.
[performance]


1408-1411: Confirm partial coverage for map boundaries.

.refine((val) => Object.keys(val).length > 1, 'Map too small') is correct for gt=1. Double-check negative or zero boundary cases if user passes invalid data.


1432-1433: Inconsistent approach to lt=1 vs. lte=1.

One passes .length < 1, the other .length <= 1. Ensure you handle negative or zero boundary cases consistently across map vs slice validations.


1470-1471: Check array transformation ordering when merging validations.

You refine the map, then call .array(). If a user expects the array constraints first, consider verifying that the final chain order is correct in TypeScript.


1547-1563: Carefully parse leftover validations after keys/endkeys.

Your logic strips out certain segments from the validate string. Double-check that any leftover validations are properly applied to values or the map itself.


1723-1734: Add a test for partial constraints with MetadataLength.

We see multiple refines for map size. Consider a test that verifies partial constraints (e.g., only min=1) to confirm it doesn’t break logic for user-supplied constraints.


2168-2183: Specify defaults or fallback for unhandled custom tags.

At lines 2168–2183, you merge a new custom tag for sortFields and others. If unrecognized fields are present, consider error feedback or ignoring them. Currently, unknown tags might panic upstream.

README.md (2)

5-5: LGTM! Documentation improvements enhance clarity.

The changes improve documentation by:

  • Adding a helpful reference link to go-validator
  • Consistently updating the converter initialization method across examples

Also applies to: 37-37, 117-117


291-328: LGTM! Well-documented custom types implementation.

The section provides clear examples and comprehensive documentation for implementing custom type handlers.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

297-297: Hard tabs
Column: 1

(MD010, no-hard-tabs)


298-298: Hard tabs
Column: 1

(MD010, no-hard-tabs)


299-299: Hard tabs
Column: 1

(MD010, no-hard-tabs)


300-300: Hard tabs
Column: 1

(MD010, no-hard-tabs)


306-306: Hard tabs
Column: 1

(MD010, no-hard-tabs)


314-314: Hard tabs
Column: 1

(MD010, no-hard-tabs)

Comment on lines +390 to +431
var validateStr strings.Builder
var refines []string
name := typeName(t)
parts := strings.Split(validate, ",")

if name == "" {
// Handle fields with non-defined types - these are inline.
return c.convertStruct(t, indent)
validateStr.WriteString(c.convertStruct(t, indent))
} else if name == "Time" {
var validateStr string
if validate != "" {
// We compare with both the zero value from go and the zero value that zod coerces to
if validate == "required" {
validateStr = ".refine((val) => val.getTime() !== new Date('0001-01-01T00:00:00Z').getTime() && val.getTime() !== new Date(0).getTime(), 'Invalid date')"
}
}
// timestamps are to be coerced to date by zod. JSON.parse only serializes to string
return "z.coerce.date()" + validateStr
validateStr.WriteString("z.coerce.date()")
} else {
if c.stack[len(c.stack)-1].name == name {
c.stack[len(c.stack)-1].selfRef = true
return fmt.Sprintf("z.lazy(() => %s)", schemaName(c.prefix, name))
validateStr.WriteString(fmt.Sprintf("z.lazy(() => %s)", schemaName(c.prefix, name)))
} else {
// throws panic if there is a cycle
detectCycle(name, c.stack)
c.addSchema(name, c.convertStructTopLevel(t))
validateStr.WriteString(schemaName(c.prefix, name))
}
// throws panic if there is a cycle
detectCycle(name, c.stack)
c.addSchema(name, c.convertStructTopLevel(t))
return schemaName(c.prefix, name)
}

for _, part := range parts {
valName, _, done := c.preprocessValidationTagPart(part, &refines, &validateStr)
if done {
continue
}

switch valName {
case "required":
if name == "Time" {
// We compare with both the zero value from go and the zero value that zod coerces to
refines = append(refines, ".refine((val) => val.getTime() !== new Date('0001-01-01T00:00:00Z').getTime() && val.getTime() !== new Date(0).getTime(), 'Invalid date')")
}
default:
panic(fmt.Sprintf("unknown validation: %s", part))
}
}

for _, refine := range refines {
validateStr.WriteString(refine)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Break out validation code for readability.

This block handles struct-level validations, cycle detection, lazy schemas, and more. Consider splitting logic into smaller functions (e.g., applyRefineTags, applyRequiredTag).

Comment on lines +44 to +50
// Adds tags which should be ignored. Any unrecognized tag (which is also
// not ignored) results in panic.
func WithIgnoreTags(ignores ...string) Opt {
return func(c *Converter) {
c.ignoreTags = append(c.ignoreTags, ignores...)
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate ignoreTags usage.

Appending ignore tags at runtime can hide errors. If ignoring unknown tags is optional, consider a mechanism to notify the user that a tag was skipped or if it might cause schema mismatches.

- c.ignoreTags = append(c.ignoreTags, ignores...)
+ // Possibly log or track ignored tags for debugging.
+ for _, ig := range ignores {
+   // log the ignore
+   c.ignoreTags = append(c.ignoreTags, ig)
+ }
📝 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
// Adds tags which should be ignored. Any unrecognized tag (which is also
// not ignored) results in panic.
func WithIgnoreTags(ignores ...string) Opt {
return func(c *Converter) {
c.ignoreTags = append(c.ignoreTags, ignores...)
}
}
// Adds tags which should be ignored. Any unrecognized tag (which is also
// not ignored) results in panic.
func WithIgnoreTags(ignores ...string) Opt {
return func(c *Converter) {
// Possibly log or track ignored tags for debugging.
for _, ig := range ignores {
// log the ignore
c.ignoreTags = append(c.ignoreTags, ig)
}
}
}

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: 0

🧹 Nitpick comments (2)
zod.go (2)

1048-1051: Enhance error messages for validation parsing.

The current error message for invalid validation format could be more helpful.

Consider this improvement:

-    panic(fmt.Sprintf("invalid validation: %s", part))
+    panic(fmt.Sprintf("invalid validation format for '%s': expected name=value or name", part))

385-430: Consider using custom error types instead of panics.

The current implementation uses panics extensively for validation errors. Consider introducing custom error types for better error handling and recovery.

Example implementation:

// Custom error types
type ValidationError struct {
    Tag   string
    Value string
    Msg   string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("validation error for tag '%s' with value '%s': %s", e.Tag, e.Value, e.Msg)
}

// Example usage in preprocessValidationTagPart
func (c *Converter) preprocessValidationTagPart(...) (..., error) {
    if idx == 0 || idx == len(part)-1 {
        return "", "", false, &ValidationError{
            Tag: part,
            Msg: "invalid format, expected name=value or name",
        }
    }
    // ...
}

Also applies to: 560-631, 677-729, 810-1077

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22a7f6b and d47c99c.

📒 Files selected for processing (1)
  • zod.go (20 hunks)
🔇 Additional comments (3)
zod.go (3)

12-75: Well-structured implementation of the options pattern!

The implementation follows Go best practices with:

  • Clear documentation for each option
  • Type-safe implementation using functional options pattern
  • Proper initialization of maps and slices

163-171: Clean separation of concerns in Converter struct!

The restructuring improves maintainability by:

  • Separating different types of customization (types vs tags)
  • Maintaining proper field initialization
  • Using idiomatic Go field naming

1042-1077: Well-structured validation preprocessing!

The new preprocessValidationTagPart function effectively:

  • Reduces code duplication
  • Handles custom tags cleanly
  • Separates refinements logically

Copy link
Collaborator

@satvik007 satvik007 left a comment

Choose a reason for hiding this comment

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

Thanks @hi-rai Awesome work

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: 0

🧹 Nitpick comments (3)
zod_test.go (3)

2137-2184: Consider enhancing test coverage with negative test cases.

The test case effectively validates the custom tag handlers, but could be strengthened by:

  1. Adding negative test cases to verify validation failures
  2. Testing edge cases in pagination validation (e.g., equal values, zero values)
  3. Testing invalid sort field values

Here's an example of how to add negative test cases:

 func TestCustomTag(t *testing.T) {
+    // Existing positive test case
     type SortParams struct {
         Order *string `json:"order,omitempty" validate:"omitempty,oneof=asc desc"`
         Field *string `json:"field,omitempty"`
     }
     // ... rest of the positive test case ...

+    // Negative test cases
+    t.Run("invalid_search", func(t *testing.T) {
+        schema := NewConverterWithOpts(WithCustomTags(customTagHandlers)).Convert(Request{})
+        assert.Contains(t, schema, "Invalid search identifier")
+    })
+
+    t.Run("invalid_pagination", func(t *testing.T) {
+        schema := NewConverterWithOpts(WithCustomTags(customTagHandlers)).Convert(Request{})
+        assert.Contains(t, schema, "Start should be less than end")
+    })
+
+    t.Run("invalid_sort_field", func(t *testing.T) {
+        schema := NewConverterWithOpts(WithCustomTags(customTagHandlers)).Convert(Request{})
+        assert.Contains(t, schema, "title")
+    })
 }

2153-2155: Consider strengthening the identifier validation regex.

The current regex pattern ^[a-z0-9_]*$ allows empty strings. Consider:

  1. Requiring at least one character
  2. Adding restrictions on consecutive underscores
  3. Preventing underscore at the start/end

Here's a more robust pattern:

-            return ".refine((val) => !val || /^[a-z0-9_]*$/.test(val), 'Invalid search identifier')"
+            return ".refine((val) => !val || /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(val), 'Invalid search identifier')"

2156-2158: Enhance pagination validation with additional checks.

The current validation only checks if start is less than end. Consider adding:

  1. Maximum range limit
  2. Minimum value checks
  3. Validation for equal values

Here's an enhanced validation:

-            return ".refine((val) => !val.start || !val.end || val.start < val.end, 'Start should be less than end')"
+            return `.refine((val) => {
+                if (!val.start || !val.end) return true;
+                if (val.start >= val.end) return false;
+                if (val.end - val.start > 1000) return false;
+                return true;
+            }, 'Invalid pagination range: start must be less than end and range must not exceed 1000')`
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d47c99c and 547bc41.

📒 Files selected for processing (1)
  • zod_test.go (5 hunks)
🔇 Additional comments (1)
zod_test.go (1)

1778-1779: LGTM! Consistent use of options-based initialization.

The change from NewConverter to NewConverterWithOpts aligns with the PR objectives to support custom validation tags through configurable options.

Also applies to: 2088-2089

@hi-rai hi-rai merged commit 3da7737 into main Feb 17, 2025
1 check passed
@hi-rai hi-rai deleted the custom-tags branch February 17, 2025 14:13
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.

5 participants