Skip to content

chore: Refactor display response relationship#3100

Merged
gupta-piyush19 merged 14 commits intomainfrom
refactor-display-response-relationship
Sep 18, 2024
Merged

chore: Refactor display response relationship#3100
gupta-piyush19 merged 14 commits intomainfrom
refactor-display-response-relationship

Conversation

@Dhruwang
Copy link
Member

@Dhruwang Dhruwang commented Sep 5, 2024

What does this PR do?

Fixes https://github.com/formbricks/internal/issues/341

How should this be tested?

Test display and responses relation

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read How we Code at Formbricks
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand bits
  • Ran pnpm build
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues
  • First PR at Formbricks? Please sign the CLA! Without it we wont be able to merge it 🙏

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Formbricks Docs if changes were necessary

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced displayId property in various components to enhance tracking and identification of surveys and responses.
    • Added data migration scripts to improve integrity between displays and responses in the database.
  • Bug Fixes

    • Removed deprecated update functionality from API documentation and codebase, streamlining display management.
  • Refactor

    • Updated response handling to include displayId, improving data association between responses and displays.
    • Simplified display deletion process by removing outdated functions.
  • Documentation

    • Revised documentation to reflect the removal of the update method and associated examples.

@vercel
Copy link

vercel bot commented Sep 5, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
formbricks-cloud ⬜️ Ignored (Inspect) Visit Preview Sep 18, 2024 10:47am
formbricks-docs ⬜️ Ignored (Inspect) Visit Preview Sep 18, 2024 10:47am

@github-actions
Copy link
Contributor

github-actions bot commented Sep 5, 2024

Thank you for following the naming conventions for pull request titles! 🙏

Copy link
Contributor

@gupta-piyush19 gupta-piyush19 left a comment

Choose a reason for hiding this comment

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

Thanks, @Dhruwang for the changes.
I've added a few small questions/change suggestions.
can you please take a look at it?
Thanks 🙌

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 18, 2024

Walkthrough

The changes involve the removal of the "Update Display" functionality from the API, including the deletion of related documentation, service methods, and tests. New properties, such as displayId, have been added to various components and schemas to enhance tracking and management of display-related data. Additionally, a data migration script has been introduced to refactor relationships in the database, ensuring better integrity and association between displays and responses.

Changes

File Path Change Summary
apps/docs/app/developer-docs/api-sdk/page.mdx Removed documentation for the update method on api.client.display.
apps/web/app/api/v1/client/[environmentId]/displays/[displayId]/route.ts Deleted file handling HTTP requests for updating displays, including OPTIONS and PUT methods.
apps/web/app/s/[surveyId]/components/LinkSurvey.tsx Added displayId property to LinkSurvey component.
packages/api/README.md Removed instructions for using api.client.display.update method.
packages/api/src/api/client/display.ts Removed update method from DisplayAPI class.
packages/database/data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts Introduced migration script to refactor display-response relationships.
packages/database/migrations/20240917112456_add_display_id_to_response/migration.sql Added displayId column to Response table with unique and foreign key constraints.
packages/database/package.json Added new migration script for adding display ID to responses.
packages/database/schema.prisma Modified Response and Display models for new relationships and deprecated fields.
packages/js-core/src/app/lib/widget.ts Added displayId parameter to renderWidget function.
packages/js-core/src/website/lib/widget.ts Added displayId parameter to renderWidget function.
packages/lib/display/service.ts Removed updateDisplay and deleteDisplayByResponseId functions; added deleteDisplay function.
packages/lib/display/tests/display.test.ts Replaced tests for updateDisplay with tests for deleteDisplay.
packages/lib/response/service.ts Updated response creation and deletion logic to handle displayId.
packages/lib/responseQueue.ts Removed logic for updating display after response creation; retained displayId.
packages/lib/survey/service.ts Enhanced survey display logic to incorporate response data.
packages/lib/survey/tests/survey.test.ts Added mock data for testing response scenarios.
packages/lib/surveyState.ts Added displayId property in SurveyState class.
packages/react-native/src/survey-web-view.tsx Added displayId to the object in SurveyWebView function.
packages/types/displays.ts Updated validation methods for identifiers and removed ZDisplayUpdateInput schema.
packages/types/responses.ts Added displayId field to response-related schemas.

Suggested labels

bug, 🙋🏻‍♂️help wanted, 🕹️ oss.gg, 🕹️ 50 points, 🕹️ Level 1

Suggested reviewers

  • Dhruwang
  • coderabbitai
  • jonas-hoebenreich

🐰 In the meadow where bunnies play,
A change has come to brighten the day.
With displayId now hopping along,
Our data dances, a joyful song!
No more updates, just a clean slate,
Hooray for the changes, they’re truly great! 🌼


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8b99943 and 564e59f.

Files selected for processing (1)
  • packages/database/data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/database/data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts

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>, please review it.
    -- 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 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: 4

Outside diff range and nitpick comments (1)
packages/lib/display/service.ts (1)

222-246: Approve the addition of the deleteDisplay function.

The new deleteDisplay function looks good and provides a way to delete a display record by its ID. The input validation, cache revalidation, and error handling are all handled appropriately.

Consider adding a check to ensure the display exists before attempting to delete it.

To improve the function's robustness, consider adding a check to ensure the display exists before attempting to delete it. This can help avoid potential errors and provide a more informative error message if the display doesn't exist.

export const deleteDisplay = async (displayId: string): Promise<TDisplay> => {
  validateInputs([displayId, ZId]);
  try {
+   const existingDisplay = await prisma.display.findUnique({
+     where: {
+       id: displayId,
+     },
+   });
+
+   if (!existingDisplay) {
+     throw new ResourceNotFoundError("display", displayId);
+   }
+
    const display = await prisma.display.delete({
      where: {
        id: displayId,
      },
      select: selectDisplay,
    });

    displayCache.revalidate({
      id: display.id,
      personId: display.personId,
      surveyId: display.surveyId,
    });

    return display;
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
};

Consider adding a return type for the error case to improve type safety.

To improve type safety, consider adding a return type for the error case. This can help catch potential type-related issues at compile time.

-export const deleteDisplay = async (displayId: string): Promise<TDisplay> => {
+export const deleteDisplay = async (displayId: string): Promise<TDisplay | never> => {
  validateInputs([displayId, ZId]);
  try {
    const display = await prisma.display.delete({
      where: {
        id: displayId,
      },
      select: selectDisplay,
    });

    displayCache.revalidate({
      id: display.id,
      personId: display.personId,
      surveyId: display.surveyId,
    });

    return display;
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new DatabaseError(error.message);
    }

    throw error;
  }
};
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b1ed61c and 8b99943.

Files selected for processing (21)
  • apps/docs/app/developer-docs/api-sdk/page.mdx (0 hunks)
  • apps/web/app/api/v1/client/[environmentId]/displays/[displayId]/route.ts (0 hunks)
  • apps/web/app/s/[surveyId]/components/LinkSurvey.tsx (1 hunks)
  • packages/api/README.md (0 hunks)
  • packages/api/src/api/client/display.ts (1 hunks)
  • packages/database/data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts (1 hunks)
  • packages/database/migrations/20240917112456_add_display_id_to_response/migration.sql (1 hunks)
  • packages/database/package.json (1 hunks)
  • packages/database/schema.prisma (2 hunks)
  • packages/js-core/src/app/lib/widget.ts (1 hunks)
  • packages/js-core/src/website/lib/widget.ts (1 hunks)
  • packages/lib/display/service.ts (1 hunks)
  • packages/lib/display/tests/display.test.ts (3 hunks)
  • packages/lib/response/service.ts (6 hunks)
  • packages/lib/responseQueue.ts (1 hunks)
  • packages/lib/survey/service.ts (3 hunks)
  • packages/lib/survey/tests/survey.test.ts (2 hunks)
  • packages/lib/surveyState.ts (1 hunks)
  • packages/react-native/src/survey-web-view.tsx (1 hunks)
  • packages/types/displays.ts (1 hunks)
  • packages/types/responses.ts (3 hunks)
Files not reviewed due to no reviewable changes (3)
  • apps/docs/app/developer-docs/api-sdk/page.mdx
  • apps/web/app/api/v1/client/[environmentId]/displays/[displayId]/route.ts
  • packages/api/README.md
Additional comments not posted (35)
packages/database/migrations/20240917112456_add_display_id_to_response/migration.sql (3)

1-6: LGTM!

The warning comment is informative and accurately reflects the changes made in the migration script. It helps the developer understand the potential impact of adding a unique constraint to the displayId column in the Response table.


7-8: LGTM!

The ALTER TABLE statement correctly adds the displayId column to the Response table. The column name and data type are appropriate for establishing a relationship with the Display table.


10-14: LGTM!

The unique index and foreign key constraint are correctly defined on the displayId column in the Response table. These changes enhance the relational structure of the database and ensure data integrity between the Response and Display tables.

The ON DELETE SET NULL and ON UPDATE CASCADE actions are appropriate for handling the deletion and update events, respectively, ensuring that the database remains in a consistent state.

packages/api/src/api/client/display.ts (1)

Line range hint 1-21: Removal of update method and TDisplayUpdateInput import approved.

The removal of the update method and the corresponding import statement for TDisplayUpdateInput has been reviewed and is approved. This change streamlines the DisplayAPI class by eliminating the update capability for display objects.

Please note the following impact and next steps for clients:

  • Clients using this API will no longer be able to update display objects using the update method.
  • If clients were relying on this method, they will need to find alternative ways to update display objects or use a different API.
  • Ensure that the removal of this functionality is communicated to the relevant stakeholders and documented appropriately.
packages/lib/surveyState.ts (1)

79-79: LGTM! The addition of displayId to the accumulated response object aligns with the PR objective.

The change introduces the displayId property to the object being constructed within the accumulateResponse method of the SurveyState class. This modification allows associating the display identifier with the accumulated response data, which could enable better tracking and management of survey responses based on their associated display identifiers.

The change aligns with the PR objective of refactoring the display response relationship.

Please verify that the usage of the accumulated response object in the codebase is updated to handle the new displayId property appropriately. Run the following script to check for any potential issues:

Verification successful

Verification complete: The addition of displayId is consistent and appears safe.

The codebase search confirms that the displayId property is correctly added to the responseAcc object in the accumulateResponse method of the SurveyState class. This change is isolated and doesn't seem to introduce any conflicts or issues in the existing code.

Key observations:

  • The accumulateResponse method in surveyState.ts correctly includes the new displayId property.
  • The responseQueue.ts file calls accumulateResponse but doesn't directly interact with the new property.
  • No other direct usage of the displayId property was found, reducing the risk of unexpected behavior.

While the change appears safe, it's worth noting that the surveyState object is passed to a setSurveyState function in the config, which could potentially expose the new property to other parts of the codebase not visible in this search.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the accumulated response object in the codebase.

# Test: Search for the usage of `responseAcc` and `accumulateResponse`. Expect: No issues with the new `displayId` property.
rg --type typescript -A 5 $'responseAcc|accumulateResponse'

Length of output: 95


Script:

#!/bin/bash
# Description: Verify the usage of the accumulated response object in the codebase using alternative methods.

# Find TypeScript files and search for 'responseAcc' and 'accumulateResponse'
echo "Searching for 'responseAcc':"
find . -name "*.ts" -type f | xargs grep -n "responseAcc" -A 5

echo -e "\nSearching for 'accumulateResponse':"
find . -name "*.ts" -type f | xargs grep -n "accumulateResponse" -A 5

Length of output: 2891

packages/database/data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts (4)

35-65: Return the unfulfilled promises directly to Promise.all.

The past review comment is still valid and applicable here:

please update this code to return the unfullfiled promise(without await) to the promise.all. We can await them together using a single await outside of it.


78-81: LGTM!

The error handling logic is correct, and the implementation looks good.


83-86: LGTM!

The error handling logic for Prisma disconnect is correct, and the implementation looks good.


88-94: LGTM!

The main function correctly orchestrates the migration execution and ensures proper cleanup. The implementation looks good.

packages/lib/responseQueue.ts (1)

90-90: LGTM! The changes align with the PR objectives.

The inclusion of displayId in the response data ensures that this information is available in the response payload, which is a positive change. Additionally, as mentioned in the AI-generated summary, the removal of the display update logic using displayId after response creation simplifies the response handling process by eliminating the need for a conditional update and any associated error handling.

These changes contribute to a cleaner and more streamlined response handling mechanism.

packages/database/package.json (2)

50-50: LGTM!

Adding a comma at the end of the script definition is a good practice to maintain consistent formatting and prepare for future additions.


51-51: Approve the addition of the new data migration script.

The addition of the data-migration:add-display-id-to-response script follows the existing naming convention and expands the data migration capabilities of the application.

To better understand the purpose and impact of this data migration script, please provide more information about the changes made in the ./data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts file.

  • What is the goal of adding display IDs to responses?
  • How does this refactoring improve the display-response relationship?
  • Are there any potential risks or side effects associated with this data migration?

Answering these questions will help ensure a smooth integration of the changes and maintain the overall stability of the application.

packages/lib/display/tests/display.test.ts (6)

14-14: LGTM!

The import statement is necessary for the tests and does not introduce any issues.


17-17: LGTM!

The import statement is necessary for the newly added tests for deleting a display and does not introduce any issues.


134-141: LGTM!

The happy path test for deleting a display is well-structured, uses appropriate mocking and assertions, and aligns with the changes mentioned in the AI-generated summary.


153-153: LGTM!

The sad path test for handling a PrismaClientKnownRequestError when deleting a display is well-structured, uses appropriate mocking and assertions, and aligns with the changes mentioned in the AI-generated summary.


160-160: LGTM!

The sad path test for handling unexpected exceptions when deleting a display is well-structured, uses appropriate mocking and assertions, and aligns with the changes mentioned in the AI-generated summary.


Line range hint 1-163: Comprehensive test coverage!

The tests in this file comprehensively cover the functionality of the display services, including both happy path and sad path scenarios. The removal of updateDisplay tests and the addition of deleteDisplay tests align with the changes mentioned in the AI-generated summary, suggesting a consistent change in the functionality being tested. There are no apparent missing tests or inconsistencies.

packages/types/responses.ts (3)

229-229: LGTM!

The addition of the optional displayId field to the ZResponse schema is a valid change. It provides an additional identifier that can be used in various contexts, potentially improving the flexibility and usability of the response data. The field is correctly defined as a nullable string using z.string().nullish().


250-250: Looks good!

The addition of the optional displayId field to the ZResponseInput schema is a valid change. It provides an additional identifier that can be used when creating or updating responses, potentially improving the flexibility and usability of the response input data. The field is correctly defined as a nullable string using z.string().nullish().


306-306: Approved!

The addition of the optional displayId field to the ZResponseUpdate schema is a valid change. It provides an additional identifier that can be used when updating responses, potentially improving the flexibility and usability of the response update data. The field is correctly defined as a nullable string using z.string().nullish().

packages/js-core/src/app/lib/widget.ts (1)

196-196: LGTM! This is a valuable addition.

Adding the displayId property to the response update object is a great way to associate responses with specific displays of the survey. This can provide valuable insights and analytics, such as:

  • Tracking user responses across multiple displays of the same survey.
  • Analyzing response rates and completion rates per display.
  • Understanding how different displays (e.g., timing, placement) affect user engagement.

Good job on implementing this!

packages/js-core/src/website/lib/widget.ts (1)

191-191: LGTM!

The addition of the displayId property to the response update object is a good change that allows for better tracking and correlation between response updates and their corresponding display instances. This could be useful for analytics, debugging, or other scenarios where knowing the specific display instance associated with a response update is important.

The change appears to be self-contained and is unlikely to introduce any breaking changes or negative side effects.

apps/web/app/s/[surveyId]/components/LinkSurvey.tsx (1)

281-281: LGTM!

The addition of the displayId property to the response object is a good enhancement. It allows for better tracking and identification of surveys in the application without altering the existing logic or control flow.

packages/react-native/src/survey-web-view.tsx (1)

99-99: LGTM!

The addition of the displayId property to the response object is a valid enhancement. It allows the SurveyWebView component to utilize the display ID for further processing or rendering logic, potentially impacting how surveys are displayed or identified in the web view.

packages/lib/survey/tests/survey.test.ts (2)

2-2: LGTM!

The import statement is syntactically correct and the imported mocks are used appropriately in the getSyncSurveys tests to enhance the test coverage.


307-308: LGTM!

The mocked return values simulate the behavior of the Prisma methods and allow the "Returns synced surveys" test case to handle scenarios involving responses and response notes.

packages/database/schema.prisma (1)

135-136: LGTM!

The addition of the displayId field in the Response model is consistent with the past review comments and correctly establishes the relationship with the Display model.

packages/lib/response/service.ts (5)

65-65: LGTM!

The addition of the displayId property to the responseSelection object is a valid change to include the associated display ID when querying responses.


258-258: LGTM!

The addition of the displayId property to the responseInput object in the createResponse function is a valid change to allow associating a response with a display record during creation.


297-297: LGTM!

The conditional addition of the display property to the prismaData object based on the presence of displayId is a valid way to establish the relationship between the response and the display record in the database.


806-808: Addressed the concern raised in the past review comment.

The addition of the if statement to check for the existence of response.displayId before calling the deleteDisplay function resolves the concern raised by gupta-piyush19 about potential issues for responses without a display.

The explicit check and deletion of the display record is a valid approach, and the cascade delete suggestion is not necessary here.


25-25: Verify the usage of the renamed deleteDisplay function.

The import statement suggests that the deleteDisplayByResponseId function has been renamed to deleteDisplay. Ensure that the function is being called with the correct arguments throughout the codebase.

Run the following script to verify the function usage:

Verification successful

deleteDisplay function usage verified

The deleteDisplay function is consistently called with a single argument (display ID) throughout the codebase. This confirms that the renaming from deleteDisplayByResponseId to deleteDisplay has been properly implemented, and the function is being used correctly.

Occurrences found:

  • In packages/lib/response/service.ts: deleteDisplay(response.displayId);
  • In packages/lib/display/tests/display.test.ts: deleteDisplay(mockDisplay.id)

The usage is consistent with the expected behavior of deleting a display by its ID.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `deleteDisplay` have the correct arguments.

# Test: Search for the function usage. Expect: Only occurrences with a single argument.
rg --type typescript -A 5 $'deleteDisplay'

Length of output: 76


Script:

#!/bin/bash
# Description: Verify all function calls to `deleteDisplay` have the correct arguments.

# Search for the function usage using rg with explicit file extensions
echo "Searching with ripgrep:"
rg --type-add 'ts:*.{ts,tsx}' --type ts -A 5 'deleteDisplay\('

# Search for the function usage using ast-grep
echo "Searching with ast-grep:"
ast-grep --lang typescript --pattern 'deleteDisplay($_)'

Length of output: 2356

packages/lib/survey/service.ts (2)

1138-1141: LGTM!

The changes to the "displayMultiple" case logic are correct. The survey is now eligible for display only if there are no existing responses for the specific person.


1148-1149: Please add a comment explaining the purpose of this check.

The past review comment is still valid:

I think it should still be dependent on the displays, as displaySome is to find out if any display for a particular survey exists for this user or not.

Please add a comment clarifying the purpose of this check and consider if it should still depend on displays as suggested.

personId: z.string().cuid2().nullable(),
surveyId: z.string().cuid2(),
responseId: z.string().cuid2().nullable(),
personId: z.string().cuid().nullable(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Based on the analysis, I will now generate the final response:

Inconsistent ID generation and nullable property for personId

The change from cuid2() to cuid() for personId in packages/types/displays.ts introduces inconsistency in the codebase. Most other ID fields, including id, environmentId, and surveyId, use cuid2(). Additionally, the nullable() property on personId is unique among ID definitions.

Consider the following:

  • Revert the change to use cuid2() for personId to maintain consistency with other ID fields.
  • If cuid() is intentional for personId, ensure this decision is documented and applied consistently where needed.
  • Justify the use of nullable() for personId or remove it to align with other ID field definitions.

These changes will help maintain consistency across the codebase and prevent potential issues with ID generation and handling.

Analysis chain

Verify the impact of the validation change and the nullable property.

The change from cuid2() to cuid() for the personId field implies a shift in the expected format for this identifier. Ensure that this change is consistently applied across the codebase to avoid compatibility issues.

Additionally, confirm that allowing null values for personId aligns with the business requirements and does not introduce any unexpected behavior or inconsistencies.

Run the following script to verify the usage of personId:


To gather more information about the usage of cuid() and cuid2() and to investigate the relationship between personId and personIdentifier, let's run additional scripts:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `personId` in the codebase.

# Test 1: Search for occurrences of `personId` in TypeScript files.
# Expect: Consistent usage of `cuid()` validation and proper handling of nullable values.
rg --type ts $'personId'

# Test 2: Search for occurrences of `personId` in JavaScript files.
# Expect: Consistent usage of `cuid()` validation and proper handling of nullable values.
rg --type js $'personId'

Length of output: 25473


Script:

#!/bin/bash
# Search for cuid() and cuid2() usage
echo "Searching for cuid() usage:"
rg --type ts --type js 'cuid\(\)'

echo "\nSearching for cuid2() usage:"
rg --type ts --type js 'cuid2\(\)'

echo "\nSearching for personIdentifier usage:"
rg --type ts --type js 'personIdentifier'

Length of output: 5521

surveyId: z.string().cuid2(),
responseId: z.string().cuid2().nullable(),
personId: z.string().cuid().nullable(),
surveyId: z.string().cuid(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Inconsistent surveyId validation may lead to issues across the codebase.

The change from cuid2() to cuid() for the surveyId field in packages/types/displays.ts creates an inconsistency with other parts of the codebase. Most other files, including the ZId type definition, still use cuid2(). This inconsistency could lead to validation issues and potential bugs.

Recommendations:

  • Choose either cuid() or cuid2() consistently for surveyId validation across all files.
  • If the intention is to switch to cuid(), update the ZId type definition in packages/types/common.ts.
  • Review the optional surveyId usage in packages/lib/display/cache.ts and packages/lib/response/cache.ts to ensure they're not affected by the removal of nullable().
Analysis chain

Verify the impact of the validation change and the removal of the nullable property.

The change from cuid2() to cuid() for the surveyId field implies a shift in the expected format for this identifier. Ensure that this change is consistently applied across the codebase to avoid compatibility issues.

Additionally, confirm that making the surveyId field strictly required (by removing the nullable() property) does not break any existing functionality that relies on the field being optional.

Run the following script to verify the usage of surveyId:


To gather more specific information about the usage of surveyId and its validation, let's run the following scripts:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `surveyId` in the codebase.

# Test 1: Search for occurrences of `surveyId` in TypeScript files.
# Expect: Consistent usage of `cuid()` validation and no reliance on nullable values.
rg --type ts $'surveyId'

# Test 2: Search for occurrences of `surveyId` in JavaScript files.
# Expect: Consistent usage of `cuid()` validation and no reliance on nullable values.
rg --type js $'surveyId'

Length of output: 78236


Script:

#!/bin/bash
# Search for cuid() and cuid2() usage with surveyId
echo "Searching for cuid() usage with surveyId:"
rg 'surveyId.*cuid\(\)'

echo "\nSearching for cuid2() usage with surveyId:"
rg 'surveyId.*cuid2\(\)'

echo "\nSearching for nullable surveyId:"
rg 'surveyId.*nullable\(\)'

echo "\nSearching for optional surveyId:"
rg 'surveyId\?:'

echo "\nExamining ZId definition:"
rg 'export const ZId'

Length of output: 1146

Comment on lines +35 to +65
await Promise.all(
displays.map(async (display) => {
if (!display.responseId) {
return Promise.resolve();
}

const response = await tx.response.findUnique({
where: { id: display.responseId },
select: { id: true },
});

if (response) {
totalResponseTransformed++;
return Promise.all([
tx.response.update({
where: { id: response.id },
data: { display: { connect: { id: display.id } } },
}),
tx.display.update({
where: { id: display.id },
data: { responseId: null },
}),
]);
}

totalDisplaysDeleted++;
return tx.display.delete({
where: { id: display.id },
});
})
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize the Promise.all block by returning the promises directly.

You can simplify the Promise.all block by directly returning the promises, without using Promise.resolve() for the cases where display.responseId is falsy.

Apply this diff to optimize the code:

-        displays.map(async (display) => {
-          if (!display.responseId) {
-            return Promise.resolve();
-          }
+        displays.map(async (display) => {
+          if (!display.responseId) {
+            return;
+          }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await Promise.all(
displays.map(async (display) => {
if (!display.responseId) {
return Promise.resolve();
}
const response = await tx.response.findUnique({
where: { id: display.responseId },
select: { id: true },
});
if (response) {
totalResponseTransformed++;
return Promise.all([
tx.response.update({
where: { id: response.id },
data: { display: { connect: { id: display.id } } },
}),
tx.display.update({
where: { id: display.id },
data: { responseId: null },
}),
]);
}
totalDisplaysDeleted++;
return tx.display.delete({
where: { id: display.id },
});
})
);
await Promise.all(
displays.map(async (display) => {
if (!display.responseId) {
return;
}
const response = await tx.response.findUnique({
where: { id: display.responseId },
select: { id: true },
});
if (response) {
totalResponseTransformed++;
return Promise.all([
tx.response.update({
where: { id: response.id },
data: { display: { connect: { id: display.id } } },
}),
tx.display.update({
where: { id: display.id },
data: { responseId: null },
}),
]);
}
totalDisplaysDeleted++;
return tx.display.delete({
where: { id: display.id },
});
})
);

Comment on lines +203 to +205
responseId String? @unique //deprecated
status DisplayStatus?
response Response?
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Caution: responseId is still widely used despite being marked as deprecated

The responseId field, although marked as deprecated in the schema, is still extensively used throughout the codebase. This includes core functionalities, database operations, and API endpoints across multiple packages.

Key observations:

  • Present in numerous TypeScript and JavaScript files
  • Used in database migrations and schema definitions
  • Integral to response-related operations and display logic

Recommendations:

  1. Conduct a thorough impact analysis before removing or replacing responseId
  2. Plan a gradual, phased approach for deprecation and replacement
  3. Update all affected components, ensuring backward compatibility during the transition
  4. Revise the existing migration strategy to fully address the responseId usage
Analysis chain

Verify the usage of the deprecated responseId field.

The changes to the Display model, including marking the responseId field as deprecated and introducing the new response field, are consistent with the provided summary.

Please ensure that all references to the deprecated responseId field are updated to use the new response field throughout the codebase.

Run the following script to verify the usage of the deprecated responseId field:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the deprecated `responseId` field is not being used in the codebase.

# Test: Search for the usage of `responseId` in TypeScript and JavaScript files.
# Expect: No occurrences of `responseId` usage.
rg --type-add 'ts:*.ts' --type-add 'js:*.js' -w responseId

Length of output: 21862

@gupta-piyush19 gupta-piyush19 added this pull request to the merge queue Sep 18, 2024
Merged via the queue into main with commit e4009d5 Sep 18, 2024
@gupta-piyush19 gupta-piyush19 deleted the refactor-display-response-relationship branch September 18, 2024 11:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants