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(runtime): intercepts $extends to reproxy its result to make sure enhancements persist #1847

Merged
merged 3 commits into from
Nov 16, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 13, 2024

No description provided.

Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces enhancements to the makeProxy function in the proxy.ts file, specifically for handling the $extends property of the Prisma client. It ensures that when this property is accessed, it checks for function invocation and manages proxy wrapping to avoid duplication. Additionally, the error handling in the createHandlerProxy function is improved for better stack trace reporting. The changes are supported by updated integration tests and a new regression test suite that validate the functionality and behavior of the enhanced Prisma client.

Changes

File Path Change Summary
packages/runtime/src/enhancements/node/proxy.ts - Enhanced makeProxy function to handle $extends property, ensuring proper proxy wrapping.
- Improved error handling in createHandlerProxy for better stack trace management.
tests/integration/tests/enhancements/with-policy/client-extensions.test.ts - Updated assertions in tests to reflect expected results after applying extensions to the Prisma client.
- Removed intermediate variable xprisma for direct assertions.
tests/regression/tests/issue-prisma-extension.test.ts - Introduced a new test suite for validating enhanced Prisma client functionality with two test cases for findMany and findManyListView methods.
tests/regression/tests/issue-1859.test.ts - Introduced a new test suite for issue 1859, validating enhanced client functionality with two test cases for findMany and findManyListView methods.

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

🧹 Outside diff range and nitpick comments (6)
tests/regression/tests/issue-prisma-extension.test.ts (2)

7-15: Consider adding more test cases for edge cases

The schema definition is clear and concise. However, consider adding test cases for:

  • Nested relations (e.g., Post with Comments)
  • Multiple extension layers
  • Error cases when permissions are denied

34-38: Add negative test case for unpublished posts

The test verifies that published posts are accessible but doesn't explicitly verify that unpublished posts are filtered out. Consider adding an assertion to check that the unpublished post (id: 2) is not included in the results.

tests/integration/tests/enhancements/with-policy/client-extensions.test.ts (3)

47-49: LGTM! Comprehensive test coverage for extension and enhancement combinations.

The test cases effectively verify the behavior of $extends with different enhancement combinations. They demonstrate that:

  1. Raw extensions see all records (length 3)
  2. Enhanced extensions filter records correctly (length 2)
  3. The order of applying enhancements and extensions maintains consistent behavior

Consider adding test cases for:

  • Chaining multiple extensions ($extends(ext1).$extends(ext2))
  • Nested extensions (ext1 that calls $extends internally)

Also applies to: 83-85


114-118: LGTM! Clear and isolated test cases for client extensions.

The test effectively verifies that client extensions work correctly with different enhancement orders. The boolean flag reset ensures proper test isolation.

Consider using a jest spy instead of a boolean flag for better test practices:

const logSpy = jest.fn();
// ... in extension
$log: logSpy
// ... in test
expect(logSpy).toHaveBeenCalledWith('abc');

295-297: LGTM! Good coverage of result modifications.

The tests effectively verify that both direct mutations and computed fields persist through enhancement wrapping. The use of expect.objectContaining makes the assertions robust.

Consider adding test cases for:

  • Computed fields that depend on other computed fields
  • Mutations that add/remove fields
  • Error cases (e.g., computing fields with missing dependencies)

Also applies to: 331-333

packages/runtime/src/enhancements/node/proxy.ts (1)

257-274: Consider extracting common logic for property interception

The interception logic for both $transaction and $extends properties shares similarities in how they wrap and proxy new client instances. To enhance maintainability and reduce code duplication, consider refactoring this common functionality into a helper function.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 716091e and e7f6b54.

📒 Files selected for processing (3)
  • packages/runtime/src/enhancements/node/proxy.ts (1 hunks)
  • tests/integration/tests/enhancements/with-policy/client-extensions.test.ts (9 hunks)
  • tests/regression/tests/issue-prisma-extension.test.ts (1 hunks)
🔇 Additional comments (2)
tests/integration/tests/enhancements/with-policy/client-extensions.test.ts (1)

153-154: LGTM! Thorough coverage of query override scopes.

The test suite comprehensively verifies that query overrides work correctly at all scopes (model-specific, all-models, operation-specific, and global) and persist through enhancement wrapping.

Let's verify that all query override scopes are tested:

Also applies to: 189-190, 225-226, 259-260

✅ Verification successful

Verified coverage of all query override scopes.

All query override patterns are present and properly tested across the specified lines.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify coverage of query override scopes
# Look for all query override test patterns in the test file

echo "Checking query override patterns..."
rg -U 'query: \{[^}]+\}' tests/integration/tests/enhancements/with-policy/client-extensions.test.ts

Length of output: 773

packages/runtime/src/enhancements/node/proxy.ts (1)

257-274: Proper handling of $extends to ensure enhancements persist

The added code correctly intercepts the $extends property and re-proxies its result to maintain enhancements. The check to avoid double wrapping using the PRISMA_PROXY_ENHANCER marker is appropriate and ensures that extended Prisma client instances continue to function with the applied proxies.

@ymc9
Copy link
Member Author

ymc9 commented Nov 16, 2024

fixes #1859

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 (2)
tests/regression/tests/issue-1859.test.ts (2)

4-39: Consider strengthening test assertions

While the test effectively validates the core behavior, consider adding these assertions to make it more robust:

  1. Verify the structure of returned posts (not just length)
  2. Test with different args passed to findManyListView
  3. Add negative test cases (e.g., invalid args)
 await expect(db.post.findMany()).resolves.toHaveLength(1);
+await expect(db.post.findMany()).resolves.toMatchObject([
+    { id: 1, title: 'post1', published: true }
+]);

 const extended = db.$extends({
     model: {
         post: {
             findManyListView: async (args: any) => {
                 return { view: true, data: await db.post.findMany(args) };
             },
         },
     },
 });

 await expect(extended.post.findManyListView()).resolves.toMatchObject({
     view: true,
     data: [{ id: 1, title: 'post1', published: true }],
 });
+
+// Test with args
+await expect(extended.post.findManyListView({ 
+    where: { title: 'post1' } 
+})).resolves.toMatchObject({
+    view: true,
+    data: [{ id: 1, title: 'post1', published: true }],
+});
+
+// Negative test
+await expect(extended.post.findManyListView({ 
+    invalid: 'arg' 
+})).rejects.toThrow();

 await expect(extended.post.findMany()).resolves.toHaveLength(1);

27-27: Improve type safety by avoiding any

The args parameter in both findManyListView methods is typed as any. Consider using proper Prisma types for better type safety and IDE support.

-findManyListView: async (args: any) => {
+findManyListView: async (args: Parameters<typeof db.post.findMany>[0]) => {

Also applies to: 62-62

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e7f6b54 and 0ee16cc.

📒 Files selected for processing (1)
  • tests/regression/tests/issue-1859.test.ts (1 hunks)
🔇 Additional comments (1)
tests/regression/tests/issue-1859.test.ts (1)

1-16: LGTM: Well-structured schema with clear access control rules

The schema setup effectively defines the test scenario with appropriate access control rules that will help validate the enhancement behavior.

tests/regression/tests/issue-1859.test.ts Show resolved Hide resolved
@ymc9 ymc9 merged commit 68a0eb3 into dev Nov 16, 2024
13 checks passed
@ymc9 ymc9 deleted the fix/intercept-extends branch November 16, 2024 06:29
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