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(delegate): clean up generated zod schemas for delegate auxiliary fields #2003

Merged
merged 2 commits into from
Feb 23, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Feb 23, 2025

fixes #1993

Copy link
Contributor

coderabbitai bot commented Feb 23, 2025

📝 Walkthrough

Walkthrough

This pull request refines the schema generation process by enhancing the filtering logic for delegate auxiliary models. In the Zod schema generator, filtering now excludes any types or fields that include the DELEGATE_AUX_RELATION_PREFIX string. Additionally, the enum schema generator was modified to filter out enum values using the same prefix, and a new method for mapping delegate input types was introduced. A regression test for a schema featuring user delegation has also been added.

Changes

File(s) Change Summary
packages/schema/src/plugins/zod/generator.ts
packages/schema/src/plugins/zod/transformer.ts
Enhanced filtering logic to exclude types, fields, and enum values containing DELEGATE_AUX_RELATION_PREFIX. Replaced startsWith with a some check, added descriptive comments, and introduced a new private method mapDelegateInputType for transforming input types.
tests/regression/tests/issue-1993.test.ts Added a regression test to validate schema generation with a schema involving user delegation and relation mappings.
packages/sdk/src/model-meta-generator.ts
packages/sdk/src/utils.ts
Removed getBackLink and getRelationName functions, replaced with a single getRelationBackLink function. Added new functions getRelationBackLink and getRelationName to enhance relation field handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Schema Generation Process
    participant Generator as ZodSchemaGenerator
    participant Transformer as Transformer

    Client->>Generator: Call generate()
    Generator->>Generator: Filter out types with DELEGATE_AUX_RELATION_PREFIX
    Generator->>Generator: Process object schemas and filter delegate auxiliary fields
    Generator->>Transformer: Invoke generateEnumSchemas()
    Transformer->>Transformer: Filter enum values with DELEGATE_AUX_RELATION_PREFIX
    Transformer->>Transformer: Call mapDelegateInputType() if input type requires transformation
    Transformer-->>Generator: Return transformed enum schema
    Generator-->>Client: Return complete schema
Loading

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

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

🧹 Nitpick comments (2)
tests/regression/tests/issue-1993.test.ts (1)

1-46: Regression test addition.
This new test suite neatly verifies schema handling for delegate auxiliary fields. Consider including an explicit assertion that generated code excludes delegate-prefixed types, ensuring thorough coverage.

packages/schema/src/plugins/zod/generator.ts (1)

246-247: Field-level exclusion with startsWith().
Filtering fields by startsWith(DELEGATE_AUX_RELATION_PREFIX) complements the .includes() checks above. Although slightly different from the earlier includes(), it suits prefix-based naming conventions for fields.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e379f8 and e23f5c9.

📒 Files selected for processing (3)
  • packages/schema/src/plugins/zod/generator.ts (3 hunks)
  • packages/schema/src/plugins/zod/transformer.ts (4 hunks)
  • tests/regression/tests/issue-1993.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (8)
packages/schema/src/plugins/zod/transformer.ts (5)

2-2: New constant import looks correct.
No issues with importing DELEGATE_AUX_RELATION_PREFIX from '@zenstackhq/runtime'; this aligns well with the later filtering logic.


7-7: Addition of isDelegateModel import.
Good addition that supports delegate-model detection.


72-76: Enum value filtering with delegate prefix.
Excluding enum values starting with DELEGATE_AUX_RELATION_PREFIX avoids polluting user-facing schemas with internal fields. Implementation is direct and maintains clarity.


252-262: Reduced input types for delegate references.
Filtering and remapping delegate-specific input types is appropriate. Ensures only relevant names are imported and avoids generating extraneous schemas.


302-327: New mapDelegateInputType method.
Regex approach and the conditional remapping logic are clear and well-handled. Gracefully returns early if patterns are not matched. This is a solid addition for delegate input type transformation.

packages/schema/src/plugins/zod/generator.ts (3)

1-1: New constant import.
Pulling in DELEGATE_AUX_RELATION_PREFIX is consistent with the intended filtering logic.


92-98: Exclusion of delegate aux input object types.
Excluding input object types that match the prefix prevents generating unwanted auxiliary schemas. The .includes() usage is appropriate for internal partial matches.


100-104: Exclusion of delegate aux output object types.
Mirrors the input object logic to prevent extraneous output object generation. This symmetry is well implemented.

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

🧹 Nitpick comments (1)
packages/schema/src/plugins/zod/transformer.ts (1)

306-344: Add error handling and documentation to the delegate input type mapping.

While the implementation is logically sound, consider these improvements:

  1. Add JSDoc documentation to explain:

    • The purpose of the method
    • The format of input type names it expects to handle
    • The transformation logic
    • Return value description
  2. Add error handling for edge cases:

    • When regex match fails
    • When oppositeRelationField is not found

Here's a suggested improvement:

+/**
+ * Maps delegate model input types to their base types.
+ * E.g.: "UserCreateNestedOneWithoutDelegate_aux_PostInput" => "UserCreateWithoutAssetInput"
+ *
+ * @param inputType - The input type reference to transform
+ * @param contextDataModel - The data model providing context
+ * @param contextFieldName - The field name in the context model
+ * @returns The transformed input type reference or the original if no transformation needed
+ */
 private mapDelegateInputType(
     inputType: PrismaDMMF.InputTypeRef,
     contextDataModel: DataModel,
     contextFieldName: string
 ) {
     const contextField = contextDataModel.fields.find((f) => f.name === contextFieldName);
     if (!contextField || !isDataModel(contextField.type.reference?.ref)) {
         return inputType;
     }

     if (!contextField.$inheritedFrom || !isDelegateModel(contextField.$inheritedFrom)) {
         return inputType;
     }

     let processedInputType = inputType;

     const match = inputType.type.match(/^(\S+?)((NestedOne)?WithoutDelegate_aux\S+?)((Nested)?Input)$/);
     if (match) {
         let mappedInputTypeName = match[1];

         if (contextDataModel) {
             const oppositeRelationField = getRelationBackLink(contextField);
+            // Return early if we can't find the opposite relation
+            if (!oppositeRelationField) {
+                return inputType;
+            }
             mappedInputTypeName += `Without${upperCaseFirst(oppositeRelationField.name)}`;
         }

         mappedInputTypeName += match[4];

         processedInputType = { ...inputType, type: mappedInputTypeName };
     }
     return processedInputType;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e23f5c9 and ff5d94f.

📒 Files selected for processing (4)
  • packages/schema/src/plugins/zod/transformer.ts (4 hunks)
  • packages/sdk/src/model-meta-generator.ts (2 hunks)
  • packages/sdk/src/utils.ts (1 hunks)
  • tests/regression/tests/issue-1993.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/regression/tests/issue-1993.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (6)
packages/sdk/src/model-meta-generator.ts (2)

32-32: LGTM!

The import of getRelationBackLink is correctly added to replace the removed getBackLink function.


291-291: LGTM!

The usage of getRelationBackLink is correctly implemented to replace the removed getBackLink function.

packages/sdk/src/utils.ts (2)

636-674: LGTM! The getRelationBackLink function is well-implemented.

The function correctly handles:

  1. Type reference validation
  2. Source model determination based on inheritance
  3. Relation name matching for backlinks
  4. Edge cases like self-references

676-685: LGTM! The getRelationName function is concise and focused.

The function efficiently extracts the relation name from the @relation attribute.

packages/schema/src/plugins/zod/transformer.ts (2)

2-2: LGTM! Required imports added for delegate auxiliary field handling.

The new imports are correctly added and necessary for the enhanced delegate model handling functionality.

Also applies to: 5-5, 8-8


73-77: LGTM! Proper filtering of delegate auxiliary fields from enum schemas.

The implementation correctly filters out enum values that start with DELEGATE_AUX_RELATION_PREFIX before generating the schema, which aligns with the PR's objective of cleaning up generated Zod schemas for delegate auxiliary fields.

@ymc9 ymc9 merged commit d42dc32 into dev Feb 23, 2025
11 checks passed
@ymc9 ymc9 deleted the fix/issue-1993 branch February 23, 2025 05:50
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