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: Refactor Update Metadata #2681

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

komyg
Copy link

@komyg komyg commented Sep 4, 2024

Describe your changes

Refactor the PatchMetadata file to:

  • Remove a database call inside a for loop.
  • Improve its clarity and maintainability.

Issue ticket number and link

Checklist before requesting a review (skip if just adding/editing APIs & templates)

  • I added tests, otherwise the reason is:
  • I added observability, otherwise the reason is:
  • I added analytics, otherwise the reason is:

Summary by CodeRabbit

  • New Features

    • Introduced a new method to retrieve multiple connections by their IDs, improving data handling efficiency.
    • Enhanced the updateMetadata function to better manage connection IDs and error responses.
  • Bug Fixes

    • Improved error handling to provide clearer feedback by listing all unknown connection IDs in a single response.
  • Refactor

    • Streamlined the logic in the updateMetadata function for better clarity and maintainability.
    • Simplified test assertions for error responses, focusing on error codes.

Copy link

coderabbitai bot commented Sep 4, 2024

Walkthrough

The changes involve significant modifications to the updateMetadata function and related tests in the server's connection handling. Key updates include the introduction of new helper functions for parsing request bodies and handling connection IDs, as well as improved error handling that consolidates responses for unknown connection IDs. Additionally, a new method in the ConnectionService class allows for retrieving multiple connections by their IDs, enhancing flexibility in managing connection data.

Changes

Files Change Summary
packages/server/lib/controllers/connection/updateMetadata.integration.test.ts Test assertions simplified to focus on error codes, while maintaining status code checks.
packages/server/lib/controllers/connection/updateMetadata.ts Refactored updateMetadata function with new parseBody and bodyParamToArray functions. Improved error handling by retrieving connections in bulk and returning comprehensive error messages.
packages/shared/lib/services/connection.service.ts Introduced getConnectionsByConnectionIds method for bulk retrieval of connections. Updated updateMetadata method to accept both Connection[] and StoredConnection[].

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Database

    Client->>Server: Send updateMetadata request
    Server->>Server: Parse request body
    Server->>Database: Get connections by IDs
    Database-->>Server: Return connections
    alt Unknown connections
        Server->>Server: Construct error message
    end
    Server-->>Client: Return response (success/error)
Loading

🐰 In the meadow, changes bloom,
New helpers dance, dispelling gloom.
Connections gathered, swift and bright,
Errors clear, a joyful sight!
Hops of code, a happy tune,
Celebrate under the bright, full moon! 🌙


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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

@komyg komyg force-pushed the fix/refactor-update-metadata branch from 37453e9 to ad36f8c Compare September 4, 2024 20:08
Copy link

@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, codebase verification and nitpick comments (1)
packages/server/lib/controllers/connection/updateMetadata.ts (1)

56-70: LGTM with a minor suggestion!

The updateByConnectionId function looks good. It improves the user experience by providing clearer feedback for unknown connection IDs.

Consider extracting the error response for unknown connection IDs into a separate function to further improve code clarity and reusability. For example:

function sendUnknownConnectionError(res: Response, unknownIds: string[], providerConfigKey: string) {
    res.status(404).send({
        error: {
            code: 'unknown_connection',
            message: `Connection with connection ids: ${unknownIds.join(', ')} and provider config key ${providerConfigKey} not found. Please make sure the connection exists in the Nango dashboard. No actions were taken on any of the connections as a result of this failure.`
        }
    });
}

Then, you can use it in updateByConnectionId like this:

if (storedConnections.length !== connectionIds.length) {
    const unknownIds = connectionIds.filter((connectionId) => !storedConnections.find((conn) => conn.connection_id === connectionId));
    sendUnknownConnectionError(res, unknownIds, providerConfigKey);
    return;
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f202839 and 37453e9.

Files selected for processing (3)
  • packages/server/lib/controllers/connection/updateMetadata.integration.test.ts (2 hunks)
  • packages/server/lib/controllers/connection/updateMetadata.ts (2 hunks)
  • packages/shared/lib/services/connection.service.ts (2 hunks)
Files skipped from review due to trivial changes (1)
  • packages/server/lib/controllers/connection/updateMetadata.integration.test.ts
Additional comments not posted (5)
packages/server/lib/controllers/connection/updateMetadata.ts (3)

Line range hint 16-36: LGTM!

The refactoring of updateMetadata looks good. Breaking down the function into smaller, reusable parts improves code clarity and maintainability. The error handling has also been improved to consolidate responses for unknown connection IDs.


38-46: LGTM!

The parseBody function looks good. It improves code clarity by centralizing the extraction of parameters from the request body.


48-54: LGTM!

The bodyParamToArray function looks good. It ensures consistent handling of both single and multiple connection IDs.

packages/shared/lib/services/connection.service.ts (2)

488-500: LGTM!

The new getConnectionsByConnectionIds method looks good:

  • It correctly queries the _nango_connections table based on the provided parameters.
  • It handles the case when no results are found by returning an empty array.
  • It follows best practices and has clear naming.

The code changes are approved.


Line range hint 709-715: LGTM!

The changes to the updateMetadata method look good:

  • The updated method signature enhances flexibility by accepting both Connection[] and StoredConnection[].
  • The method implementation remains correct and maintains its original functionality.
  • It follows best practices by using a database transaction and merging metadata correctly.

The code changes are approved.

Copy link

@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, codebase verification and nitpick comments (1)
packages/server/lib/controllers/connection/connectionId/metadata/patchMetadata.ts (1)

57-71: LGTM with a minor suggestion!

The code changes are approved. The function is well-structured and handles the case when any of the connection IDs are not found.

Consider extracting the error response logic into a separate function to improve code readability and reusability. For example:

function sendUnknownConnectionError(res: Response, unknownIds: string[], providerConfigKey: string) {
    res.status(404).send({
        error: {
            code: 'unknown_connection',
            message: `Connection with connection ids: ${unknownIds.join(', ')} and provider config key ${providerConfigKey} not found. Please make sure the connection exists in the Nango dashboard. No actions were taken on any of the connections as a result of this failure.`
        }
    });
}

Then, update the updateByConnectionId function to use the new function:

async function updateByConnectionId(res: Response, connectionIds: string[], providerConfigKey: string, environmentId: number, metadata: Metadata) {
    const storedConnections = await connectionService.getConnectionsByConnectionIds(connectionIds, providerConfigKey, environmentId);
    if (storedConnections.length !== connectionIds.length) {
        const unknownIds = connectionIds.filter((connectionId) => !storedConnections.find((conn) => conn.connection_id === connectionId));
-       res.status(404).send({
-           error: {
-               code: 'unknown_connection',
-               message: `Connection with connection ids: ${unknownIds.join(', ')} and provider config key ${providerConfigKey} not found. Please make sure the connection exists in the Nango dashboard. No actions were taken on any of the connections as a result of this failure.`
-           }
-       });
+       sendUnknownConnectionError(res, unknownIds, providerConfigKey);
        return;
    }

    await connectionService.updateMetadata(storedConnections, metadata);
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 37453e9 and ad36f8c.

Files selected for processing (3)
  • packages/server/lib/controllers/connection/connectionId/metadata/patchMetadata.integration.test.ts (2 hunks)
  • packages/server/lib/controllers/connection/connectionId/metadata/patchMetadata.ts (2 hunks)
  • packages/shared/lib/services/connection.service.ts (2 hunks)
Files skipped from review due to trivial changes (1)
  • packages/server/lib/controllers/connection/connectionId/metadata/patchMetadata.integration.test.ts
Files skipped from review as they are similar to previous changes (1)
  • packages/shared/lib/services/connection.service.ts
Additional comments not posted (3)
packages/server/lib/controllers/connection/connectionId/metadata/patchMetadata.ts (3)

Line range hint 17-37: LGTM!

The code changes are approved. The refactoring enhances code clarity and modularity by using helper functions for parsing the request body and updating metadata.


39-47: LGTM!

The code changes are approved. The function improves code clarity by structuring the request body and ensures that connectionIds is always an array using the bodyParamToArray helper function.


49-55: LGTM!

The code changes are approved. The function correctly converts a string or an array of strings to an array of strings and handles the case when the input is undefined.

@komyg komyg changed the title Refactor Update Metadata fix: Refactor Update Metadata Sep 5, 2024
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