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: Handle errors in app content library #14430

Merged
merged 5 commits into from
Jan 21, 2025
Merged

Conversation

TomasEng
Copy link
Contributor

@TomasEng TomasEng commented Jan 15, 2025

Description

This pull request splits the AppContentLibrary component in two, so that the second part and all its dependencies are only rendered when data has finished loading. It also adds an error message that is shown when the queries fail.

Here is the error message:
image
It may of course be improved with more details, but that's a task for another pull request. This pull request solves the problem that the component may call functions with undefined values since it doesn't handle the error state of the queries.

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)

Summary by CodeRabbit

  • New Features

    • Enhanced option lists management in the App Content Library.
    • Added a new custom hook for uploading option lists.
    • Improved error handling and data fetching mechanisms.
  • Bug Fixes

    • Added error message handling for data retrieval issues.
  • Documentation

    • Updated Norwegian language error message for data fetching problems.
  • Tests

    • Refactored test cases for the AppContentLibrary component.
    • Added new test scenarios for error handling and option lists.

Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

📝 Walkthrough

Walkthrough

This pull request introduces modifications to the AppContentLibrary component and its associated tests. Key changes include the refactoring of the test file to enhance asynchronous testing capabilities, the introduction of a new rendering function for option lists, and improvements in the main component for better data fetching and error management. Additionally, a new error message in Norwegian has been added to inform users about data retrieval issues.

Changes

File Change Summary
frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx - Added waitFor for async testing
- Refactored renderAppContentLibrary to accept queryClient
- Introduced renderAppContentLibraryWithOptionLists
- Updated test cases to handle option lists and error scenarios
- Renamed type renderAppContentLibraryProps to RenderAppContentLibraryProps
- Removed shouldPutDataOnCache and optionListsData properties
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx - Added useOptionListsReferencesQuery
- Introduced AppContentLibraryWithData component
- Created useUploadOptionList hook
- Enhanced error handling and data fetching logic
- Updated variable names for consistency
frontend/language/src/nb.json - Added new error message for data fetching issues

Possibly related issues

Possibly related PRs

Suggested labels

area/content-library, quality/testing

Suggested reviewers

  • ErlingHauan

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c78eb2 and 5b7a8c3.

📒 Files selected for processing (1)
  • frontend/language/src/nb.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/language/src/nb.json

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 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@github-actions github-actions bot added area/ui-editor Area: Related to the designer tool for assembling app UI in Altinn Studio. solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Jan 15, 2025
@TomasEng TomasEng changed the title Split app contnet library refactor: Split app content library Jan 15, 2025
Copy link

codecov bot commented Jan 15, 2025

Codecov Report

Attention: Patch coverage is 95.23810% with 1 line in your changes missing coverage. Please review.

Project coverage is 95.68%. Comparing base (6ec1b07) to head (53aa3e8).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...t/features/appContentLibrary/AppContentLibrary.tsx 95.23% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14430   +/-   ##
=======================================
  Coverage   95.68%   95.68%           
=======================================
  Files        1891     1891           
  Lines       24583    24588    +5     
  Branches     2823     2822    -1     
=======================================
+ Hits        23523    23528    +5     
  Misses        799      799           
  Partials      261      261           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@TomasEng TomasEng force-pushed the split-app-contnet-library branch from de49ab3 to fea943f Compare January 15, 2025 15:35
@TomasEng TomasEng force-pushed the split-app-contnet-library branch from fea943f to 5a67361 Compare January 20, 2025 07:40
@TomasEng TomasEng changed the title refactor: Split app content library fix: Handle errors in app content library Jan 20, 2025
@TomasEng TomasEng marked this pull request as ready for review January 20, 2025 07:58
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: 2

🧹 Nitpick comments (1)
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (1)

78-80: Ensure consistent return type annotations for functions

The function handleUpdateCodeListId explicitly specifies a return type void, while handleUpdate does not. For consistency and readability, consider annotating the return type of handleUpdate or relying on type inference uniformly across your codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 026ec9d and 5a67361.

📒 Files selected for processing (3)
  • frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (9 hunks)
  • frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (4 hunks)
  • frontend/language/src/nb.json (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx

[warning] 112-112: frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx#L112
Added line #L112 was not covered by tests

🔇 Additional comments (2)
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (1)

112-112: Add unit tests to cover the 'hideDefaultError' handling

Line 112 introduces the hideDefaultError option in the useAddOptionListMutation. This logic is not covered by tests. Adding unit tests for this case will improve test coverage and ensure error handling works as expected.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 112-112: frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx#L112
Added line #L112 was not covered by tests

frontend/language/src/nb.json (1)

45-45: LGTM!

The new translation key app_content_library.fetch_error is correctly added and follows the existing naming conventions.

@TomasEng TomasEng added skip-releasenotes Issues that do not make sense to list in our release notes skip-documentation Issues where updating documentation is not relevant kind/bug Used when there is a defect / something is not working as it should. quality/code Violations from current rules for code, best practices, etc. Or just bad code. quality/debt Shortcuts made for saving time. Fixing this will make us more efficient going forward. labels Jan 20, 2025
…Library.test.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@TomasEng
Copy link
Contributor Author

The line that is not covered by tests according to Codecov belongs to code that was already present. It is out of scope of this pull request to fix that.

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

🧹 Nitpick comments (2)
frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (2)

156-165: Add JSDoc comments to describe the type and its properties.

The type definition is clear, but adding documentation would improve maintainability.

Add JSDoc comments like this:

+/**
+ * Props for rendering the AppContentLibrary component in tests
+ */
 type RenderAppContentLibraryProps = {
+  /** Optional service context overrides */
   queries?: Partial<ServicesContextProps>;
+  /** Query client instance for managing test data */
   queryClient?: QueryClient;
 };

168-182: Document the purpose of initializing OptionListsUsage with an empty array.

The helper functions are well-structured, but it would be helpful to document why OptionListsUsage is initialized with an empty array.

Add a comment explaining the initialization:

 function createQueryClientWithOptionsDataList(
   optionListDataList: OptionListData[] | undefined,
 ): QueryClient {
   const queryClient = createQueryClientMock();
   queryClient.setQueryData([QueryKey.OptionLists, org, app], optionListDataList);
+  // Initialize usage data as empty since it's not relevant for these tests
   queryClient.setQueryData([QueryKey.OptionListsUsage, org, app], []);
   return queryClient;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a67361 and 70ae759.

📒 Files selected for processing (1)
  • frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: CodeQL
  • GitHub Check: Testing
🔇 Additional comments (3)
frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (3)

2-2: LGTM: Import changes are appropriate.

The added imports support the new async testing functionality and type definitions.

Also applies to: 15-15


72-78: LGTM: Error handling test is well-structured.

The test case properly verifies both the loading state removal and error message display. The use of a proper Error object for rejection is good practice.

Note: Based on the past review discussion, the current waitFor usage is correct as it passes the function reference without immediate execution (no parentheses).


55-55: LGTM: Test cases consistently use the new rendering helper.

The refactoring improves test consistency by using renderAppContentLibraryWithOptionLists across all test cases.

Also applies to: 67-67, 82-82, 92-92, 105-105, 117-117, 132-132

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

🧹 Nitpick comments (2)
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (2)

Line range hint 64-108: Consider memoizing event handlers for better performance.

The handlers like handleUpdateCodeListId and handleUpdate could be memoized using useCallback to prevent unnecessary re-renders of child components.

-  const handleUpdateCodeListId = (optionListId: string, newOptionListId: string): void => {
+  const handleUpdateCodeListId = useCallback((optionListId: string, newOptionListId: string): void => {
     updateOptionListId({ optionListId, newOptionListId });
-  };
+  }, [updateOptionListId]);

-  const handleUpdate = ({ title, codeList }: CodeListWithMetadata): void => {
+  const handleUpdate = useCallback(({ title, codeList }: CodeListWithMetadata): void => {
     updateOptionList({ optionListId: title, optionList: codeList });
-  };
+  }, [updateOptionList]);

110-130: Consider enhancing error handling with specific error messages.

While the current error handling is good, it could be more informative by handling specific error cases (e.g., file size limits, format validation) instead of using a generic error message.

         onError: (error: AxiosError<ApiError>) => {
-          if (isErrorUnknown(error)) {
+          if (error.response?.status === 413) {
+            toast.error(t('ux_editor.modal_properties_code_list_upload_size_error'));
+          } else if (error.response?.status === 415) {
+            toast.error(t('ux_editor.modal_properties_code_list_upload_format_error'));
+          } else if (isErrorUnknown(error)) {
             toast.error(t('ux_editor.modal_properties_code_list_upload_generic_error'));
           }
         },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70ae759 and 4c78eb2.

📒 Files selected for processing (1)
  • frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: CodeQL
🔇 Additional comments (3)
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (3)

Line range hint 1-28: LGTM! Well-organized imports.

The imports are logically grouped and all imported entities are utilized in the code.


30-57: Excellent implementation of loading states and error handling!

The component effectively:

  • Separates data fetching from rendering
  • Handles all possible query states
  • Uses translations for user messages

Line range hint 99-105: Verify if empty image handlers are intentional.

The images section contains empty handlers. Is this intentional or should there be actual implementation here?

✅ Verification successful

Empty image handlers are intentional

The empty handlers in the images section appear to be intentional, following React's best practices for defining unused or disabled features. This matches the pattern seen in the codebase where similar no-op handlers are used in mock configurations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for image-related functionality in the codebase
rg -g '!*.{json,lock}' -i "onUpdateImage|handleUpdateImage" .

Length of output: 1781


Script:

#!/bin/bash
# Get the context of AppContentLibrary.tsx
rg -B 10 -A 10 "onUpdateImage" ./frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx

Length of output: 670

@TomasEng
Copy link
Contributor Author

TomasEng commented Jan 20, 2025

Dear @coderabbitai, please don't encourage us to add comments to the code unless there's a really good reason to do so. Our team considers comments to be bad practice since they may become outdated and lead to more confusion than clarification.

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Tip

For best results, initiate chat on the files or code changes.

@TomasEng Thank you for this important clarification about the team's coding practices. I understand that comments should be avoided unless absolutely necessary, as they can become outdated and potentially misleading. I'll adjust my future reviews accordingly.


✏️ Learnings added
Learnt from: TomasEng
URL: https://github.com/Altinn/altinn-studio/pull/14430

Timestamp: 2025-01-20T08:41:07.829Z
Learning: For the Altinn Studio repository, code comments should be avoided unless there is a compelling reason, as they may become outdated and cause confusion. The team prefers self-documenting code over comments.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Tip

For best results, initiate chat on the files or code changes.

@TomasEng Thank you for this important clarification about the team's coding practices. I understand that comments should be avoided unless absolutely necessary, as they can become outdated and potentially misleading. I'll adjust my future reviews accordingly.


🧠 Learnings used
Learnt from: TomasEng
PR: Altinn/altinn-studio#0
File: :0-0
Timestamp: 2025-01-20T08:41:07.941Z
Learning: For the Altinn Studio repository, code comments should be avoided unless there is a compelling reason, as they may become outdated and cause confusion. The team prefers self-documenting code over comments.

@standeren standeren self-assigned this Jan 20, 2025
Copy link
Contributor

@standeren standeren left a comment

Choose a reason for hiding this comment

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

Looks good!
I have one question for future implementations tho; should we "disable" the whole library if hypothetically only one of the queries fails? 🤔 We might should consider splitting the queriers for each menu-item in the library so we are able to render the other library resources that does not have a failing query.
And maybe for this stage in the development when we only have one menu-item that is functional, in addition to the landingpage, we should be able to see the library, but the error should be shown when clicking on the code list menu item?

@standeren standeren assigned TomasEng and unassigned standeren Jan 20, 2025
@TomasEng
Copy link
Contributor Author

You've got some good suggestions there, @standeren. But I believe that would require a more extensive refactor of our library package, since it currently doesn't deal with pending and error states. Maybe we won't even need it when we start implementing it in other places. So I'm not sure if it's worth the effort, in particular because it will also increase the complexity of the library tool, including its API.

@TomasEng TomasEng assigned standeren and unassigned TomasEng Jan 20, 2025
@standeren
Copy link
Contributor

You've got some good suggestions there, @standeren. But I believe that would require a more extensive refactor of our library package, since it currently doesn't deal with pending and error states. Maybe we won't even need it when we start implementing it in other places. So I'm not sure if it's worth the effort, in particular because it will also increase the complexity of the library tool, including its API.

Then we should consider a refactor in the future if/when the library grows in size. But I guess we can go for this simplification for now 🤝

@standeren standeren assigned TomasEng and unassigned standeren Jan 20, 2025
@TomasEng TomasEng removed their assignment Jan 20, 2025
@standeren standeren self-assigned this Jan 21, 2025
@standeren standeren removed their assignment Jan 21, 2025
@standeren standeren added the skip-manual-testing PRs that do not need to be tested manually label Jan 21, 2025
@standeren
Copy link
Contributor

Since this is a small and simple PR, I tested it as well - works as expected 🤝
Added skip-manual-testing to be able to merge since I was the one doing the code review as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/ui-editor Area: Related to the designer tool for assembling app UI in Altinn Studio. frontend kind/bug Used when there is a defect / something is not working as it should. quality/code Violations from current rules for code, best practices, etc. Or just bad code. quality/debt Shortcuts made for saving time. Fixing this will make us more efficient going forward. skip-documentation Issues where updating documentation is not relevant skip-manual-testing PRs that do not need to be tested manually skip-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-domain1
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants