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(json): support recursive definitions #1865

Merged
merged 1 commit into from
Nov 16, 2024
Merged

fix(json): support recursive definitions #1865

merged 1 commit into from
Nov 16, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 16, 2024

fixes #1858

Copy link
Contributor

coderabbitai bot commented Nov 16, 2024

📝 Walkthrough

Walkthrough

The pull request introduces modifications to TypeScript compiler options and enhances the testing suite for JSON field handling. Specifically, it sets the noImplicitAny option to false in the createProject function, allowing implicit any types. Additionally, new tests are added to validate recursive types in JSON fields, particularly for a Post model with nested Content types, and updates are made to the Profile type in the User model to support optional and array fields.

Changes

File Path Change Summary
packages/sdk/src/code-gen.ts Modified createProject function to set noImplicitAny to false in compilerOptions.
tests/integration/tests/enhancements/json/crud.test.ts Added a new test case works with recursive types for validating nested Content in Post model.
tests/integration/tests/enhancements/json/typing.test.ts Added multiple test cases for JSON field typing, including optional fields, array fields, enums, and recursive definitions in Profile and Content types.

Assessment against linked issues

Objective Addressed Explanation
Support Recursive JSON Type (#1858)

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

🧹 Outside diff range and nitpick comments (5)
packages/sdk/src/code-gen.ts (1)

18-18: Consider alternative approaches for recursive type support

Instead of disabling type checking, consider these type-safe alternatives:

  1. Use TypeScript's built-in recursive type syntax:
type JSONContent = {
    type: string;
    children?: JSONContent[];
    text?: string;
};
  1. Use interface declarations which naturally support recursion:
interface JSONContent {
    type: string;
    children?: JSONContent[];
    text?: string;
}
  1. Use type assertions or type parameters where needed:
type JSONContent<T = any> = {
    type: string;
    children?: Array<JSONContent<T>>;
    text?: string;
};

Would you like help implementing any of these alternative approaches?

tests/integration/tests/enhancements/json/typing.test.ts (2)

363-380: Consider expanding test coverage

The current test effectively validates the basic recursive structure. Consider adding test cases for:

  1. Edge cases with empty arrays and null fields
  2. Maximum nesting depth validation
  3. Complete field verification after retrieval

Example additional test case:

// Test edge cases
const edgeCaseContent: Content = {
    type: 'text',
    content: [],  // Empty array
    text: null    // Null optional field
};

// Test deep nesting
const deepContent: Content = {
    type: 'root',
    content: Array(10).fill(null).map((_, i) => ({
        type: `level-${i}`,
        text: i === 9 ? 'deepest' : undefined,
        content: []
    }))
};

// Verify all fields after retrieval
const post = await db.post.create({ data: { content: edgeCaseContent } });
expect(post.content).toEqual(edgeCaseContent);

Line range hint 1-334: Consider reorganizing tests for better maintainability

The test suite is comprehensive but could benefit from better organization:

  1. Group related test cases using describe blocks (e.g., "Basic Types", "Complex Types", "Recursive Types")
  2. Extract common schema definitions into shared fixtures
  3. Consider using parameterized tests for type coverage scenarios

Example restructuring:

describe('JSON field typing', () => {
    describe('Basic Types', () => {
        it('works with simple field', ...);
        it('works with optional field', ...);
        it('works with array field', ...);
    });
    
    describe('Complex Types', () => {
        it('works with type nesting', ...);
        it('works with enums', ...);
    });
    
    describe('Recursive Types', () => {
        it('supports recursive definition', ...);
        it('handles edge cases', ...);
    });
});
tests/integration/tests/enhancements/json/crud.test.ts (2)

348-391: Implementation successfully demonstrates recursive JSON type support.

The test case effectively validates the core functionality of recursive JSON types, matching the requirements from issue #1858. The schema definition and nested data structure provide a good foundation.

Consider expanding test coverage to include:

  • Invalid type structure validation
  • Update operations on nested content
  • Array manipulation (push/pop operations)
  • Error cases (malformed data)

Example test cases:

// Invalid structure
await expect(
  db.post.create({
    data: {
      content: {
        type: 'text',
        content: [{ invalidField: true }]
      }
    }
  })
).toBeRejectedByPolicy();

// Update nested content
const updated = await db.post.update({
  where: { id: post.id },
  data: {
    content: {
      ...post.content,
      content: [...post.content.content, { type: 'text', text: 'new' }]
    }
  }
});

390-390: Enhance assertion coverage for nested structures.

The current assertion only checks a single nested property. Consider using a more comprehensive assertion that validates the entire structure.

// Replace the single property check with a full structure validation
await expect(post).toMatchObject({
  content: {
    type: 'text',
    content: [{
      type: 'text',
      content: [{
        type: 'text',
        text: 'hello'
      }]
    }]
  }
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 68a0eb3 and 26292dc.

📒 Files selected for processing (3)
  • packages/sdk/src/code-gen.ts (1 hunks)
  • tests/integration/tests/enhancements/json/crud.test.ts (1 hunks)
  • tests/integration/tests/enhancements/json/typing.test.ts (1 hunks)
🔇 Additional comments (1)
tests/integration/tests/enhancements/json/typing.test.ts (1)

339-343: LGTM: Recursive type definition matches requirements

The Content type definition correctly implements the recursive structure requested in issue #1858, allowing for nested content through the optional array field while maintaining type safety.

@@ -15,6 +15,7 @@ export function createProject(options?: CompilerOptions) {
strict: true,
skipLibCheck: true,
noEmitOnError: true,
noImplicitAny: false,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Reconsider disabling noImplicitAny as it reduces type safety

Setting noImplicitAny: false is a significant change that weakens TypeScript's type checking. While this may fix the recursive JSON type issue, it could:

  1. Allow untyped code to pass compilation
  2. Hide potential type errors
  3. Reduce code maintainability and type safety across the codebase

Consider keeping noImplicitAny: true and instead handle recursive types explicitly:

-            noImplicitAny: false,

Committable suggestion skipped: line range outside the PR's diff.

@ymc9 ymc9 merged commit c7f333d into dev Nov 16, 2024
13 checks passed
@ymc9 ymc9 deleted the fix/issue-1858 branch November 16, 2024 20:04
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