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: allow 'null' values for optional fields in custom types #1864

Merged
merged 1 commit into from
Nov 16, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 16, 2024

fixes #1857

Copy link
Contributor

coderabbitai bot commented Nov 16, 2024

📝 Walkthrough

Walkthrough

The pull request introduces changes to the generateTypeDefType function in the model-typedef-generator.ts file, specifically altering how optional fields are represented in TypeScript type definitions. Optional fields now also include a null type, ensuring they can be either the specified type or null. Additionally, a new test file, issue-1857.test.ts, has been added to address a regression issue related to optional JSON fields in a GraphQL schema.

Changes

File Path Change Summary
packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts Modified generateTypeDefType to append `
tests/regression/tests/issue-1857.test.ts Introduced a new test for regression issue #1857, validating optional JSON field handling in a GraphQL schema.

Assessment against linked issues

Objective Addressed Explanation
Optional JSON Field Creates An Error Out Of The Box (#1857)

Possibly related PRs


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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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
Contributor

@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

🧹 Outside diff range and nitpick comments (3)
tests/regression/tests/issue-1857.test.ts (3)

7-16: Consider restricting access control in test schema

While the schema correctly tests the optional JSON field issue, the @@allow('all', true) directive is overly permissive for a test case.

Consider limiting the access to only the required operations:

-                @@allow('all', true)
+                @@allow('create', true)

29-36: Enhance the example code with proper cleanup

The example code should include proper resource cleanup and error handling.

Consider updating the example:

 async function main() {
     const prisma = new PrismaClient();
+    try {
         await prisma.post.create({
             data: {
                 content: { type: 'foo', text: null }
             }
         });
+    } finally {
+        await prisma.$disconnect();
+    }
 }

43-43: Add more test cases for comprehensive validation

While the current test case verifies the null value scenario, consider adding more cases to ensure robust validation.

Add test cases for:

// Additional test cases to consider
zodSchemas.models.JSONContentSchema.parse({ type: 'foo', text: 'some text' }); // non-null case
zodSchemas.models.JSONContentSchema.parse({ type: 'foo' }); // undefined case
expect(() => 
  zodSchemas.models.JSONContentSchema.parse({ type: 'foo', text: 123 })
).toThrow(); // invalid type case
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 285b258 and 60d1ec3.

📒 Files selected for processing (2)
  • packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts (1 hunks)
  • tests/regression/tests/issue-1857.test.ts (1 hunks)
🔇 Additional comments (4)
tests/regression/tests/issue-1857.test.ts (2)

1-4: LGTM! Well-structured test setup

The test is properly organized with clear naming that ties it to the issue being fixed.


1-45: Verify test coverage against issue requirements

The test correctly addresses the core issue of allowing null values for optional fields in custom types.

✅ Verification successful

Let me gather more information about the actual issue to ensure the test coverage aligns with the reported problem.


Test coverage correctly addresses the reported issue

The test case perfectly aligns with issue #1857's requirements by:

  • Using the exact same JSONContent type structure with an optional text field
  • Testing the specific scenario where text: null is provided
  • Validating through Zod schema parsing, which would catch any type incompatibility issues
  • Using the same environment setup (PostgreSQL, JSON field)

The test effectively reproduces and verifies the fix for the reported TypeScript error where null was not properly handled for optional JSON fields.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the test matches the issue requirements

# Check if the issue number is referenced in other test files to avoid duplication
rg -l "issue.?1857" --type ts

# Verify the schema structure matches the issue description
rg -A 10 "type JSONContent" --type ts

Length of output: 858


Script:

#!/bin/bash
# Check the issue description and related discussions
gh issue view 1857 || true

# Look for any related changes or discussions in commit messages
git log --grep="1857" --pretty=format:"%h %s" || true

# Search for any other files that might be testing JSON content type
rg "JSONContent.*@json" --type ts

Length of output: 1501

packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts (2)

20-24: LGTM! Clean implementation for nullable optional fields.

The implementation correctly makes optional fields nullable by appending | null to their types, which:

  • Fixes the issue with optional JSON fields
  • Maintains consistency with Prisma's behavior
  • Follows TypeScript best practices for optional fields

20-24: Verify the impact on existing type definitions.

Since this changes how optional fields are typed, let's verify the impact on existing type definitions.

✅ Verification successful

Based on the code inspection, I can now provide a final response regarding the impact of the optional field typing changes.

The change is consistent with Prisma's behavior and doesn't require further verification.

The code change makes TypeDef field types consistent with Prisma's handling of optional fields, where optional fields are both optional (?) and nullable (| null). This is an intentional alignment with Prisma's type system behavior and doesn't introduce any breaking changes, as:

  1. The change is contained within the type definition generator
  2. It matches Prisma's existing behavior for optional fields
  3. The type definitions are generated files, and any regeneration will maintain consistency
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all TypeDef declarations to assess the impact
# Look for type definitions with optional fields to understand the scope of changes

# Search for TypeDef declarations with optional fields
ast-grep --pattern 'type $name {
  $$$
  $field?: $type;
  $$$
}'

# Search for any existing type definitions that might already include '| null'
# to ensure we're not creating duplicates
rg -l '\?: \w+ \| null;'

Length of output: 94


Script:

#!/bin/bash
# Let's try a different approach to find type definitions and their usage

# Find all TypeScript files that might contain type definitions
fd -e ts -x cat {} | grep -B2 -A2 "type.*{" || true

# Look for existing nullable type patterns
rg ":\s*\w+\s*\|\s*null" || true

# Look for optional field patterns
rg ":\s*\w+\?" || true

# Check the specific file for context
cat packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts || true

Length of output: 174476

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant