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

Feature/rest upsert #1863

Open
wants to merge 9 commits into
base: dev
Choose a base branch
from

Conversation

thomassnielsen
Copy link
Contributor

@thomassnielsen thomassnielsen commented Nov 15, 2024

Adds support for upsert operations in the RESTAPIHandler via metadata.

We may also want to add documentation about this to the OpenAPI generator.

Discussion in Discord

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between 6ab1e83 and db755a0.

📒 Files selected for processing (2)
  • packages/server/src/api/rest/index.ts (3 hunks)
  • packages/server/tests/api/rest.test.ts (1 hunks)
 ___________________________________
< Not your grandma's code reviewer. >
 -----------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce a new processUpsert method in the RequestHandler class to manage upsert operations for resources, validating unique constraints and constructing appropriate payloads. The handleRequest method is updated to differentiate between standard creation and upsert operations. Additionally, the REST server tests are enhanced with new test cases for the upsert functionality, including various scenarios for handling match fields and compound IDs. The modifications maintain existing error handling patterns and ensure robust testing for the new features.

Changes

File Path Change Summary
packages/server/src/api/rest/index.ts - Added processUpsert method to handle upsert operations.
- Updated handleRequest to include upsert logic.
packages/server/tests/api/rest.test.ts - Added new tests for upsert functionality, covering various scenarios including unique match fields and compound IDs.
- Enhanced existing CRUD tests with validation for upsert operations.

Possibly related PRs

Suggested reviewers

  • ymc9

Tip

CodeRabbit can generate a title for your PR based on the changes.

Add @coderabbitai placeholder anywhere in the title of your PR and CodeRabbit will replace it with a title based on the changes in the PR. You can change the placeholder by changing the reviews.auto_title_placeholder setting.


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.

@thomassnielsen
Copy link
Contributor Author

I refactored this to treat upserts as peers to creates etc. I'm much happier with this version.

@thomassnielsen thomassnielsen marked this pull request as ready for review November 16, 2024 20:39
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 (1)
packages/server/src/api/rest/index.ts (1)

312-333: Consider typing the request body for better type safety

Currently, the request body is cast to any. Defining a specific type for the request body can enhance type safety and catch potential errors at compile time.

Apply this diff to improve type safety:

- const body = requestBody as any;
+ interface RequestMeta {
+   operation?: string;
+   matchFields?: string[];
+ }
+
+ interface RequestBody {
+   meta?: RequestMeta;
+ }
+
+ const body = requestBody as RequestBody;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ad07053 and 6ab1e83.

📒 Files selected for processing (2)
  • packages/server/src/api/rest/index.ts (3 hunks)
  • packages/server/tests/api/rest.test.ts (2 hunks)
🧰 Additional context used
🪛 eslint
packages/server/tests/api/rest.test.ts

[error] 9-9: 'query' is defined but never used. Allowed unused vars must match /^_/u.

(@typescript-eslint/no-unused-vars)

🔇 Additional comments (6)
packages/server/src/api/rest/index.ts (2)

860-865: Review the exclusion of match fields from the update data

In the upsert operation, match fields are excluded from the update data. There might be cases where match fields need to be updated. Consider allowing match fields to be updated if it aligns with the business logic.


1402-1419: Verify the construction of the 'where' clause for compound IDs

Ensure that the makeUpsertWhere method correctly constructs the where clause for models with compound IDs. Incorrect construction may lead to unexpected behavior during upsert operations.

Run the following script to verify the correctness:

✅ Verification successful

Based on the comprehensive analysis of the codebase, I can now provide a final response:

The compound ID handling in makeUpsertWhere is correctly implemented

The implementation correctly handles both single and compound IDs by:

  1. Creating a base where object from all match fields
  2. For compound IDs (when typeInfo.idFields.length > 1), it properly wraps the fields using Prisma's compound ID format with prismaIdDivider ('_')
  3. The implementation is validated by test cases in packages/server/tests/api/rest.test.ts which include models with compound IDs like PostLike and User

The code is consistent with Prisma's compound ID requirements and is properly tested with various scenarios including:

  • Models with @@id([field1, field2])
  • Proper handling of the prismaIdDivider constant
  • Integration with Prisma's query format
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of 'makePrismaIdKey' and ensure correct 'where' clause construction.

# Search for 'makePrismaIdKey' usages in the codebase
rg 'makePrismaIdKey' -A 5 -B 5

# Search for models with compound IDs
grep -r '@@id' ./prisma/schema.prisma

# Verify upsert operations on models with compound IDs
# (Assuming test cases are available)
cd tests && npm run test-upsert-compound-id

Length of output: 5694


Script:

#!/bin/bash
# Let's analyze the implementation and usage of makeUpsertWhere more thoroughly

# First, let's find the definition of prismaIdDivider constant
rg "prismaIdDivider" -B 2 -A 2

# Find all model definitions to check for compound IDs
fd "schema.prisma" --type f

# Look for test files related to upsert operations
fd "upsert" --type f

# Look for actual usage of makeUpsertWhere
rg "makeUpsertWhere" -B 5 -A 5

# Look for model info type definition
rg "type ModelInfo" -A 10

Length of output: 5704


Script:

#!/bin/bash
# Let's examine the implementation of compound IDs in the test projects' schema files

# Check the schema files for compound ID definitions
cat packages/plugins/trpc/tests/projects/nuxt-trpc-v10/prisma/schema.prisma
cat packages/plugins/trpc/tests/projects/nuxt-trpc-v11/prisma/schema.prisma
cat packages/plugins/trpc/tests/projects/t3-trpc-v10/prisma/schema.prisma
cat packages/plugins/trpc/tests/projects/t3-trpc-v11/prisma/schema.prisma

# Look for test files that might be using compound IDs
rg "@@id" --type ts -B 5 -A 5

# Look for the FieldInfo type definition to understand ID field structure
rg "type FieldInfo" -A 10

Length of output: 63505

packages/server/tests/api/rest.test.ts (4)

1805-1841: Test case for upserting a new entity is correctly implemented

The test case effectively verifies the upsert operation when creating a new entity. It asserts that the entity is created and the response matches the expected structure.


1843-1874: Test case for upserting an existing entity works as expected

This test correctly checks that the upsert operation updates an existing entity when the match field matches, ensuring that the existing entity is updated with new attributes.


1876-1912: Test case accurately captures upsert failure due to non-unique matchFields

The test verifies that an upsert operation fails with a proper error when the specified matchFields are not unique, ensuring the system correctly handles such cases.


1914-1937: Test case confirms upsert operation with compound IDs functions correctly

This test ensures that the upsert operation supports entities with compound IDs using multiple matchFields, confirming that the feature works as intended.

packages/server/src/api/rest/index.ts Outdated Show resolved Hide resolved
Copy link
Member

@ymc9 ymc9 left a comment

Choose a reason for hiding this comment

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

Hi @thomassnielsen , overall it looks very good to me. Please check the few comments I left. Thanks!

),
};
upsertPayload.update[key] = {
connect: enumerate(data.data).map((item: any) =>
Copy link
Member

Choose a reason for hiding this comment

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

I'm wondering if the semantic for the "update" case should use "set" instead of "connect" here - replace the entire connection collection instead of adding new ones?

return error;
}

const matchFields = (requestBody as any).meta.matchFields;
Copy link
Member

Choose a reason for hiding this comment

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

matchFields should always be string[], right? Shall we zod validate it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes an optional array of strings. It makes sense to zod validate it. Where would this be added?

Copy link
Member

Choose a reason for hiding this comment

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

I see you currently have a check body?.meta?.operation === 'upsert'. Maybe we can define a zod schema and replace that check with zod parse?

packages/server/tests/api/rest.test.ts Outdated Show resolved Hide resolved
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