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

RESTApiHandler support compound ids (@@id) #1754

Merged
merged 15 commits into from
Oct 7, 2024

Conversation

thomassnielsen
Copy link
Contributor

@thomassnielsen thomassnielsen commented Sep 30, 2024

#1748

Adds support for the Prisma @@id compound ids to the RESTApiHandler.

Discord thread

Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request primarily involve updates to the RequestHandler class in the packages/server/src/api/rest/index.ts file, introducing a new constant idDivider and modifying the structure of ID fields in the RelationshipInfo and ModelInfo types to support arrays of FieldInfo objects. Additionally, several methods have been updated to handle composite IDs, enhancing the request handling capabilities. Correspondingly, the packages/server/tests/api/rest.test.ts file has been updated to include tests for a new PostLike model, ensuring that the API correctly manages likes on posts using compound IDs.

Changes

File Change Summary
packages/server/src/api/rest/index.ts - Added constant idDivider.
- Updated idField to idFields: FieldInfo[] in RelationshipInfo and ModelInfo.
- Updated method signatures for makeIdFilter, makeIdSelect, makeIdKey, and makeCompoundId to accommodate FieldInfo[].
packages/server/tests/api/rest.test.ts - Introduced PostLike model with relationships to User and Post.
- Added tests for creating, retrieving, and deleting likes using compound IDs.
- Included tests for existing CRUD operations to ensure no disruption of functionality.
- Imported idDivider for managing compound IDs in tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Database

    Client->>API: Request to create a PostLike
    API->>Database: Validate and process request with makeIdFilter
    Database-->>API: Confirmation of PostLike creation
    API-->>Client: Response with created PostLike

    Client->>API: Request to fetch PostLikes
    API->>Database: Query PostLikes with makeIdSelect
    Database-->>API: Return PostLikes data
    API-->>Client: Response with PostLikes data
Loading
sequenceDiagram
    participant Client
    participant API
    participant Database

    Client->>API: Request to update a PostLike
    API->>Database: Validate and process request with makeCompoundId
    Database-->>API: Confirmation of PostLike update
    API-->>Client: Response with updated PostLike

    Client->>API: Request to delete a PostLike
    API->>Database: Validate and process request with makeIdKey
    Database-->>API: Confirmation of PostLike deletion
    API-->>Client: Response confirming deletion
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7079a9c and dfb97b9.

📒 Files selected for processing (1)
  • packages/server/tests/api/rest.test.ts (11 hunks)
🧰 Additional context used
🔇 Additional comments (7)
packages/server/tests/api/rest.test.ts (7)

306-333: New test case for fetching a related resource with a compound ID looks good.

This test case correctly verifies the functionality of fetching a related resource (likes) for a post, where the likes have a compound ID. The test creates necessary data, makes the API call, and checks the response structure and content.

A few observations:

  1. The test uses the idDivider constant to construct the compound ID, which is a good practice for consistency.
  2. The response structure is correctly verified, including the compound ID in the data array.

1328-1376: New 'compound id' describe block with tests for GET operations looks good.

This block adds two important test cases for compound ID support:

  1. "get all" test: Verifies that the API correctly returns all PostLike entries with compound IDs.
  2. "get single" test: Checks that a single PostLike entry can be retrieved using its compound ID.

Both tests create necessary data, make API calls, and verify the response structure and content. The use of idDivider for constructing compound IDs is consistent.


1641-1683: New test cases for creating relations with compound IDs look good.

These test cases verify the creation of PostLike entries with compound IDs. They cover two scenarios:

  1. Creating a PostLike entry through the main endpoint.
  2. Creating a PostLike entry with a single compound ID.

Both tests properly set up the necessary data (User and Post) before attempting to create the PostLike entry. The compound ID is correctly constructed using the idDivider.


1822-1841: Test case for updating an item with a compound ID is implemented correctly.

This test verifies the update operation for a PostLike entry using its compound ID. It correctly:

  1. Sets up the necessary data (User, Post, and PostLike).
  2. Constructs the compound ID using idDivider.
  3. Sends a PUT request to update the PostLike entry.
  4. Checks for a successful response status.

1926-1942: Test case for updating a collection of relations with compound IDs looks good.

This test case verifies the functionality of updating a collection of relations (likes) for a post, where the likes have compound IDs. It correctly:

  1. Sets up the necessary data (User, Post, and PostLike).
  2. Sends a PATCH request to update the likes relationship.
  3. Uses the correct compound ID format in the request body.
  4. Checks for a successful response status.

2022-2035: Test case for deleting an item with a compound ID is implemented correctly.

This test verifies the delete operation for a PostLike entry using its compound ID. It properly:

  1. Sets up the necessary data (User, Post, and PostLike).
  2. Constructs the compound ID using idDivider.
  3. Sends a DELETE request to remove the PostLike entry.
  4. Checks for the correct response status (204 No Content).
  5. Verifies that the response body is undefined.

Line range hint 1-2492: Overall, the implementation of compound ID support is robust and well-tested.

The new test cases added for compound ID support cover all CRUD operations (Create, Read, Update, Delete) and related data fetching. They consistently use the idDivider constant for ID construction, which promotes maintainability. The tests verify both the response structures and the correct handling of compound IDs in various scenarios.

Some key strengths of the implementation:

  1. Comprehensive coverage of different operations involving compound IDs.
  2. Consistent use of idDivider for ID construction.
  3. Proper setup of test data before each operation.
  4. Verification of response structures and statuses.

No significant issues were found in the implementation of compound ID support. The test suite provides a solid foundation for ensuring the reliability of the API's handling of entities with compound IDs.


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
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 , many thanks for making this PR. It's a great start! I've left some comments there, please help take a look.

I'm not sure how much time you have to continue working on this. Another option is we merge it first, and I can follow up with a separate PR to continue polishing it.

I'd love to include it in the next release!

packages/server/src/api/rest/index.ts Outdated Show resolved Hide resolved
packages/server/src/api/rest/index.ts Outdated Show resolved Hide resolved
packages/server/src/api/rest/index.ts Outdated Show resolved Hide resolved
packages/server/src/api/rest/index.ts Show resolved Hide resolved
packages/server/src/api/rest/index.ts Outdated Show resolved Hide resolved
@thomassnielsen
Copy link
Contributor Author

I'm not sure how much time you have to continue working on this. Another option is we merge it first, and I can follow up with a separate PR to continue polishing it.

I have some time today and tomorrow so I'll try to fix at least what's been discussed in this PR and add some more tests. When's the next release cutoff point?

@ymc9
Copy link
Member

ymc9 commented Oct 1, 2024

I'm not sure how much time you have to continue working on this. Another option is we merge it first, and I can follow up with a separate PR to continue polishing it.

I have some time today and tomorrow so I'll try to fix at least what's been discussed in this PR and add some more tests. When's the next release cutoff point?

Thank you! Current goal of v2.7 is 10/15. Please take your time 😄.

@thomassnielsen thomassnielsen marked this pull request as ready for review October 4, 2024 07:13
@thomassnielsen
Copy link
Contributor Author

Marking this ready for review now and moving on to looking at the openapi plugin.

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

🧹 Outside diff range and nitpick comments (2)
packages/server/src/api/rest/index.ts (1)

1481-1484: Simplify sorting logic for related models with composite IDs

In the buildSort method, the logic for sorting on related models with composite IDs can be simplified by leveraging the makeIdSelect method or by ensuring consistent handling of ID fields.

Consider refactoring the sorting logic to reuse existing methods for selecting ID fields, improving code readability and maintainability.

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

331-331: Use idDivider when specifying compound IDs

In the response assertion, you've hardcoded the compound ID as '1_user1'. For consistency and maintainability, use the idDivider variable when constructing compound IDs.

Apply this diff to fix:

-                            data: [{ type: 'postLike', id: '1_user1' }],
+                            data: [{ type: 'postLike', id: `1${idDivider}user1` }],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between be8c1c4 and 9ceaa78.

📒 Files selected for processing (2)
  • packages/server/src/api/rest/index.ts (39 hunks)
  • packages/server/tests/api/rest.test.ts (11 hunks)
🔇 Additional comments (1)
packages/server/src/api/rest/index.ts (1)

1568-1569: Verify composite ID filters in makeFilterValue

When filtering by composite IDs, ensure that the makeIdFilter function constructs the correct Prisma where clause. Incorrect filtering may lead to unexpected query results.

Run the following script to check how composite ID filters are constructed:

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

35-36: LGTM! Consider adding a comment for clarity.

The addition of the idDivider constant is a good approach for handling compound IDs. It matches Prisma's default and allows for potential future configurability.

Consider adding a brief comment explaining the purpose of this constant, e.g.:

// Separator used for joining multiple ID fields in compound IDs
export const idDivider = '_';

1198-1226: LGTM! Well-implemented utility methods for compound ID handling.

The new methods makeIdFilter, makeIdSelect, makeIdKey, and makeCompoundId are well-implemented and provide essential functionality for consistent handling of compound IDs throughout the class. These methods ensure that Prisma queries are constructed correctly for both single and compound IDs, and that compound IDs are consistently represented and manipulated.

Consider adding JSDoc comments to these methods to improve code documentation. For example:

/**
 * Creates a Prisma filter object for the given ID fields and resource ID.
 * @param idFields - Array of FieldInfo objects representing the ID fields.
 * @param resourceId - The resource ID (compound or single).
 * @returns A Prisma filter object.
 */
private makeIdFilter(idFields: FieldInfo[], resourceId: string) {
    // ... existing implementation ...
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9ceaa78 and ccdb1cc.

📒 Files selected for processing (1)
  • packages/server/src/api/rest/index.ts (30 hunks)
🔇 Additional comments (6)
packages/server/src/api/rest/index.ts (6)

58-58: LGTM! Good update for compound ID support.

The changes to RelationshipInfo and ModelInfo types, replacing idField: string with idFields: FieldInfo[], are well-implemented. This modification allows for multiple ID fields and provides more detailed information about each ID field, which is essential for supporting compound IDs.

Also applies to: 64-64


756-757: LGTM! Proper handling of compound IDs in relationships.

The changes in the processCreate method correctly implement compound ID support for relationship connections. The use of makeIdKey ensures that the proper key is used for both single and compound IDs. This modification maintains consistency and correctness when creating entities with relationships that may have compound IDs.

Also applies to: 764-766, 773-773


810-814: LGTM! Consistent handling of compound IDs in relationship CRUD.

The modifications to the processRelationshipCRUD method properly implement compound ID support for relationship operations. The use of makeIdFilter and makeIdSelect ensures that both single and compound IDs are handled correctly in the where clause and select statement. This change maintains consistency across different types of relationship operations.

Also applies to: 845-845


910-910: LGTM! Proper handling of compound IDs in update operations.

The changes in the processUpdate method correctly implement compound ID support for update operations. The use of makeIdFilter and makeIdKey ensures that both single and compound IDs are handled properly in the where clause and when setting relationships. This modification maintains consistency and correctness when updating entities with potential compound IDs.

Also applies to: 929-929, 937-939, 944-944


963-963: LGTM! Consistent handling of compound IDs in delete operations.

The modification to the processDelete method properly implements compound ID support for delete operations. The use of makeIdFilter ensures that both single and compound IDs are handled correctly in the where clause. This change maintains consistency with other CRUD operations and supports the overall goal of compound ID implementation.


983-983: LGTM! Proper handling of compound IDs in type map construction.

The modifications to the buildTypeMap method correctly implement compound ID support when constructing the type map. By using idFields instead of a single idField, the method now properly handles both single and compound IDs. This change is crucial as it provides the correct type information for other methods that rely on this data, ensuring consistency throughout the API handler.

Also applies to: 1003-1003

@thomassnielsen thomassnielsen marked this pull request as draft October 4, 2024 09:12
@thomassnielsen
Copy link
Contributor Author

Testing with an updated openapi plugin it looks like there's something still missing here, so converting it back to a draft.

@thomassnielsen
Copy link
Contributor Author

Never mind, forgot to build before publishing the latest to verdaccio 🤦

@thomassnielsen thomassnielsen marked this pull request as ready for review October 4, 2024 09:21
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.

Thanks for continuing to work on this @thomassnielsen ! I've left two minor comments and the code overall looks very good to me now.

packages/server/tests/api/test.zmodel Outdated Show resolved Hide resolved
packages/server/tests/api/rest.test.ts Outdated Show resolved Hide resolved
@ymc9 ymc9 changed the base branch from main to dev October 6, 2024 14:35
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.

Looking good now! I'll merge it after CI passes. Thank you!

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