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

fix: make nullable arrays configurable #612

Merged
merged 2 commits into from
Oct 17, 2024
Merged

Conversation

danielgtaylor
Copy link
Owner

@danielgtaylor danielgtaylor commented Oct 16, 2024

This is an alternative approach to #594. @lsdch would love to know what you think.

  1. There is precedent in Huma to use global variables to control behavior. This adds another such value to set the default array nullability called huma.DefaultArrayNullable.
  2. The default stays true, as this is more correct based on how Go marshals JSON. A nil slice will encode as null so we ask the user to opt-in to alternative behavior.
  3. Updates docs to reflect this and adds a note about nil slices encoding as null.
  4. Adds a few tests.

IMO this prevents another break, moving back to less correct/accurate behavior, and makes everything explicit. I'm not the biggest fan of global variables but it seems reasonable here instead of trying to plumb everything through the various types and interfaces. Thoughts?

Summary by CodeRabbit

  • Documentation

    • Updated request validation documentation to clarify nullable fields and rules for optional and required fields.
    • Enhanced examples for making fields nullable in Go structs.
  • New Features

    • Introduced a global variable to control the default nullability of arrays, simplifying configuration.
  • Tests

    • Added new test cases for nullable and non-nullable arrays, improving schema validation coverage.

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request introduces updates to the documentation and codebase regarding request validation and nullability in Go structs. It clarifies the handling of nullable fields, particularly for arrays, by introducing a new global variable DefaultArrayNullable in schema.go. This variable centralizes the configuration of array nullability. Additionally, new test cases are added to schema_test.go to ensure robust validation of the schema generation logic, particularly concerning nullable and non-nullable arrays.

Changes

File Change Summary
docs/docs/features/request-validation.md Updated documentation to clarify handling of nullable fields and rules for optional/required fields. Enhanced examples for making fields nullable.
schema.go Introduced a new global variable DefaultArrayNullable to control array nullability; modified schemaFromType to utilize this variable.
schema_test.go Added new test cases for nullable and non-nullable arrays; enhanced existing tests for various data structures and scenarios.

Possibly related PRs

🐰 In the meadow where fields grow,
A rabbit hops to and fro.
With nullable arrays, oh what a treat,
New tests and docs make it all neat!
Hooray for changes, clear and bright,
In the code, everything feels just right! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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

codecov bot commented Oct 16, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.83%. Comparing base (0f7ad56) to head (7adb2c5).
Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #612   +/-   ##
=======================================
  Coverage   92.83%   92.83%           
=======================================
  Files          22       22           
  Lines        3923     3923           
=======================================
  Hits         3642     3642           
  Misses        236      236           
  Partials       45       45           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Outside diff range and nitpick comments (4)
docs/docs/features/request-validation.md (3)

60-63: LGTM! Consider adding a brief explanation of huma.DefaultArrayNullable.

The changes clearly explain the new logic for determining nullable fields, particularly for arrays. This aligns well with the PR objectives of making nullable arrays configurable.

To enhance clarity, consider adding a brief explanation of huma.DefaultArrayNullable and how users can configure it. This could be added as a note or included in the existing explanation.


66-67: LGTM! Consider adding an explanation for the object nullability limitation.

The changes clearly state the limitations of object nullability and introduce a panic for unsupported cases. This aligns with the PR objectives of preventing potential issues.

To provide more context, consider adding a brief explanation of why object nullability is not currently supported (e.g., complexity and poor tool support for anyOf/oneOf). This could help users understand the reasoning behind this limitation.


90-93: LGTM! Valuable explanation of default slice nullability.

The added note provides excellent context for why slices are nullable by default in Go, referencing the official Go JSON package documentation. This aligns well with the PR objectives of clarifying nullability behavior.

To make the information even more accessible, consider adding a brief code example demonstrating the behavior of nil slices when marshaled to JSON. This could help reinforce the concept for readers.

🧰 Tools
🪛 Markdownlint

92-92: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

schema.go (1)

25-29: Consider the implications of introducing a global variable.

The introduction of DefaultArrayNullable as a global variable allows for configurable default nullability of arrays. While this provides flexibility, it's important to consider the potential drawbacks of using global state:

  1. It may lead to unexpected behavior if modified during runtime.
  2. It could make the code harder to reason about, as the behavior now depends on a global state.
  3. It might complicate testing, as tests may need to reset this global state.

Consider alternatives such as:

  1. Making this a configuration option passed to relevant functions.
  2. Using a context-based approach for configuration.

If you decide to keep it as a global variable, ensure it's well-documented and its usage is consistent throughout the codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0f7ad56 and 7adb2c5.

📒 Files selected for processing (3)
  • docs/docs/features/request-validation.md (3 hunks)
  • schema.go (2 hunks)
  • schema_test.go (2 hunks)
🧰 Additional context used
🪛 Markdownlint
docs/docs/features/request-validation.md

92-92: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

🔇 Additional comments (4)
docs/docs/features/request-validation.md (1)

81-81: LGTM! Clear documentation update.

The minor update to the comment for struct examples improves clarity without changing the functionality.

schema.go (1)

Line range hint 1-894: Overall assessment: Approved with suggestions for improvement

The changes introduced in this PR provide a flexible way to configure the default nullability of arrays in the schema generation process. This is a valuable feature that can enhance the usability of the library. However, there are a few points to consider for improving the implementation and ensuring its robustness:

  1. The use of a global variable (DefaultArrayNullable) introduces potential risks and complexities. Consider alternative approaches such as configuration options or context-based configuration.
  2. Ensure comprehensive test coverage for the new array nullability behavior, including scenarios with DefaultArrayNullable set to both true and false.
  3. Update any relevant documentation to reflect this change in behavior.
  4. Verify that this change doesn't introduce inconsistencies in schema generation or break any existing assumptions in the codebase or dependent projects.

These suggestions aim to maintain the flexibility introduced by this change while mitigating potential risks and ensuring the continued reliability of the schema generation process.

schema_test.go (2)

725-743: Good addition of test case for nullable array

The test case "field-nullable-array" correctly verifies that an array field with nullable:"true" generates the expected schema where the type includes "null".


745-763: Good addition of test case for non-nullable array

The test case "field-non-nullable-array" appropriately tests that an array field with nullable:"false" generates a schema without the "null" type, ensuring non-nullability.

docs/docs/features/request-validation.md Show resolved Hide resolved
schema.go Show resolved Hide resolved
schema_test.go Show resolved Hide resolved
schema_test.go Show resolved Hide resolved
@lsdch
Copy link
Contributor

lsdch commented Oct 17, 2024

Looks good to me ! I like the idea of keeping things simple by using a global variable in this case 👍

@danielgtaylor danielgtaylor merged commit 1d5dce7 into main Oct 17, 2024
7 checks passed
@danielgtaylor danielgtaylor deleted the nullable-array-option branch October 17, 2024 16:34
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.

2 participants