Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom validation tags #14

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Add support for custom validation tags #14

wants to merge 2 commits into from

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

Release Notes

  • Documentation

    • Updated README with new sections on custom tags, ignored tags, and custom types
    • Added detailed examples for custom validation and type handling
  • Improvements

    • Enhanced converter configuration with more flexible initialization options
    • Added support for custom type and tag handling
    • Improved schema generation flexibility
  • Maintenance

    • Upgraded Go version from 1.21 to 1.23
    • Updated CI workflow and linting tools
    • Refined golangci-lint configuration

Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces significant enhancements to the Zen library, focusing on improving configurability and extensibility. The changes span multiple files, with key modifications to the zod.go file that introduce new options for converter initialization, custom type handling, and tag management. The README has been updated to provide comprehensive documentation on custom tags, types, and validation strategies. Additionally, the project's tooling and Go version have been upgraded across various configuration files.

Changes

File Change Summary
README.md Added sections on Custom Tags, Ignored Tags, and expanded Custom Types documentation
zod.go Refactored NewConverter to accept variadic options, added new option functions (WithPrefix, WithCustomTypes, etc.), restructured Converter struct
custom/decimal/decimal_test.go, custom/optional/optional_test.go Updated converter initialization using new options approach
.github/workflows/ci.yml Upgraded Go version to 1.23.5, updated action and tool versions
.golangci.yml Restructured file exclusion configuration
Makefile Updated golangci-lint version to v1.63.4
go.mod and custom module go.mod files Updated Go version from 1.21 to 1.23

Sequence Diagram

sequenceDiagram
    participant User
    participant Converter
    participant CustomTypeHandler
    participant ValidationHandler

    User->>Converter: Initialize with options
    Converter->>CustomTypeHandler: Register custom types
    Converter->>ValidationHandler: Register custom tags
    User->>Converter: Convert struct to Zod schema
    Converter-->>User: Generated Zod schema
Loading

Possibly related PRs

Suggested reviewers

  • ramilamparo
  • AndrianBdn
  • satvik007

Poem

🐰 A Rabbit's Ode to Zen's New Grace 🌟

With options dancing, code takes flight,
Custom types now shine so bright
Validators leap, tags take wing
Zod schemas now can truly sing!
Hop along, dear dev, and see
The magic of flexibility! 🎉

✨ 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.

README.md Outdated Show resolved Hide resolved
* 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.

custom/optional/optional_test.go Show resolved Hide resolved
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.

Comment on lines +12 to +20
// Opt represents a converter option used to modify its behavior.
type Opt func(*Converter)

// Adds prefix to the generated schema and type names.
func WithPrefix(prefix string) Opt {
return func(c *Converter) {
c.prefix = prefix
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

I love this new API but we might be breaking existing code. How about keeping the original API and adding this new code with a different function name?

case "omitempty":
case "required":
case "dive":
goto forEnd
Copy link
Collaborator

Choose a reason for hiding this comment

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

How about breaking loop using go's breaks with label

https://www.ardanlabs.com/blog/2013/11/label-breaks-in-go.html

Comment on lines +735 to +761
idx := strings.Index(part, "=")
if idx == 0 || idx == len(part)-1 {
panic(fmt.Sprintf("invalid validation: %s", part))
}

var valName string
var valValue string
if idx == -1 {
valName = part
} else {
valName = part[:idx]
valValue = part[idx+1:]
}

if c.checkIsIgnored(valName) {
continue
}

if h, ok := c.customTags[valName]; ok {
v := h(c, reflect.TypeOf(0), valValue, 0)
if strings.HasPrefix(v, ".refine") {
refines = append(refines, v)
} else {
validateStr.WriteString(v)
}
continue
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This code seems to be duplicated thrice in this file.

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.

3 participants