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(core): 17734 fixes for tokens, routing, sidebar, config caching #788

Conversation

vkozio
Copy link
Contributor

@vkozio vkozio commented Jul 10, 2024

  • invalid credentials during login don't trigger page reload
  • correct current route detection
  • app config fetch bypasses cache
  • api error parser converts html to text for clean notifications
  • refactor usage and remove unecessary atoms userStateAtom, autoClearAtom
  • refactor and simplify parts of init flow

Summary by CodeRabbit

  • Dependency Updates

    • Updated dependencies to the latest versions for improved performance and security.
  • New Features

    • Introduced unique route IDs and updated route hierarchy for better navigation management.
  • Bug Fixes

    • Improved error handling logic for more accurate error descriptions.
  • Refactor

    • Replaced parentRoute references with parentRouteId across various modules for more consistent route identification.
    • Updated logging and token refresh mechanisms for enhanced reliability.
  • Tests

    • Updated tests to reflect new route ID implementations and parent route ID changes.

Copy link
Contributor

coderabbitai bot commented Jul 10, 2024

Walkthrough

This update focuses on refining route and configuration management, enhancing error and logging functionality, and updating dependencies. Key changes include replacing parentRoute with parentRouteId for route identification, adjusting token refresh logic, and improving error handling. The updates also introduce unique route IDs and additional logging controls, ensuring a more robust and maintainable codebase.

Changes

File/Path Change Summary
package.json Updated dependencies for @reatom/npm-react, @types/node, react-router, react-router-dom, and vite.
src/core/api_client/apiClient.ts Introduced constant TIME_TO_REFRESH_MS and updated token refresh logic.
src/core/api_client/errors.ts Enhanced error parsing and handling for specific HTTP statuses.
src/core/app/authHooks.ts Modified import statements and updated feature flags logic.
src/core/app/postAppInit.ts Removed autoClearAtom and associated calls.
src/core/auth/client/AuthClient.ts Removed userStateAtom references and adjusted loginHook and logoutHook.
src/core/auth/index.ts Removed export of userStateAtom.
src/core/config/loaders/appConfigLoader.ts Added timestamp parameter to getAppConfig to bypass caching.
src/core/logical_layers/index.ts Removed export of autoClearAtom.
src/core/metrics/app-metrics.ts Changed route parameter to routeId in AppMetrics class.
src/core/metrics/constants.ts Updated buildWatchList function to fetch features directly from configRepo.
src/core/postInit.ts Refactored PostInit function to use routeId parameter and access data from configRepo.
src/core/router/.../availableRoutes.ts Updated getAvailableRoutes function to use parentRouteId.
src/core/router/.../currentRoute.ts Added stripBasename function and refined currentRouteAtom.
src/core/router/.../Router.tsx Removed PostInit from Layout, updated route mapping, and added postInit call in initRouter.
src/core/router/.../getAbsoluteRoute.ts Updated parentRoute parameter to parentRouteId.
src/core/router/routes.tsx Added unique IDs to route objects and updated parentRoute to parentRouteId.
src/core/router/types.ts Added id field and renamed parentRoute to parentRouteId in AppRoute interface.
src/core/store/store.ts Updated logger function URL transformation logic and removed debug log statement.
src/core/metrics/index.ts Changed route parameter to routeId in initMetricsOnce function.
src/utils/map/.../getRequirements.ts Added conditional logging based on DEBUG_MAPCSS flag.
src/views/Profile/Profile.tsx Updated to use configRepo instead of userStateAtom.
src/features/side_bar/.../routeVisibilityChecker.ts Updated visibility checker to use parentRouteId for route identification and tree construction.

Poem

Amid the code, a rabbit's glee, 🐰
With changes fresh for all to see.
Parent routes now with IDs bright,
Error logs refined, what a delight!
Tokens refresh with timely flair,
Features set with utmost care.
In the warren of code we hop,
With each update, we never stop! 🌟

Tip

You can customize the tone of the comments in your PRs

Specify the tone of the comments in your PRs by configuring the tone-instructions setting in your project's settings in CodeRabbit.


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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

Language To Recheck Fuzzy Untranslated Total
ar 3 24 101 128
de 2 24 101 127
es 3 24 101 128
id 2 24 101 127
ko 3 24 101 128
uk 0 7 8 15

Copy link

github-actions bot commented Jul 10, 2024

Bundle size diff

Old size New size Diff
4.94 MB 4.94 MB 4.18 KB (0.08%)

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

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between d483d45 and 0ff18b0.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (25)
  • package.json (4 hunks)
  • src/core/api_client/apiClient.ts (7 hunks)
  • src/core/api_client/errors.ts (3 hunks)
  • src/core/app/authHooks.ts (2 hunks)
  • src/core/app/postAppInit.ts (2 hunks)
  • src/core/auth/client/AuthClient.ts (3 hunks)
  • src/core/auth/index.ts (1 hunks)
  • src/core/config/loaders/appConfigLoader.ts (1 hunks)
  • src/core/logical_layers/index.ts (1 hunks)
  • src/core/metrics/app-metrics.ts (2 hunks)
  • src/core/metrics/index.ts (1 hunks)
  • src/core/postInit.ts (1 hunks)
  • src/core/router/atoms/availableRoutes.ts (1 hunks)
  • src/core/router/atoms/currentRoute.ts (2 hunks)
  • src/core/router/components/Router.tsx (3 hunks)
  • src/core/router/getAbsoluteRoute.ts (1 hunks)
  • src/core/router/routes.tsx (3 hunks)
  • src/core/router/types.ts (2 hunks)
  • src/core/store/store.ts (2 hunks)
  • src/features/layers_in_area/atoms/areaLayersDetailsResource/areaLayersDetailsResourceAtomCache.ts (2 hunks)
  • src/features/side_bar/components/SideBar/NavButton.tsx (1 hunks)
  • src/features/side_bar/components/SideBar/routeVisibilityChecker.test.ts (1 hunks)
  • src/features/side_bar/components/SideBar/routeVisibilityChecker.ts (2 hunks)
  • src/utils/map/mapCSSToMapBoxPropertiesConverter/getRequirements.ts (2 hunks)
  • src/views/Profile/Profile.tsx (1 hunks)
Additional context used
Biome
src/features/side_bar/components/SideBar/routeVisibilityChecker.ts

[error] 29-29: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 30-32: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

Additional comments not posted (43)
src/core/logical_layers/index.ts (1)

1-1: LGTM!

The export statement is correct and no issues are present.

src/core/auth/index.ts (1)

1-2: LGTM!

The export statements are correct and align with the refactoring mentioned in the PR summary.

src/views/Profile/Profile.tsx (1)

1-1: LGTM!

The updated code correctly uses configRepo to get the user object and conditionally renders the LoginForm or SettingsForm based on the user's presence.

Also applies to: 6-6, 8-18

src/core/postInit.ts (1)

7-10: LGTM!

The PostInit function correctly initializes metrics using routeId and configRepo. The function is clear and correctly isolates initialization tasks.

src/utils/map/mapCSSToMapBoxPropertiesConverter/getRequirements.ts (2)

1-1: Verify the usage of globalThis.localStorage.

Ensure that globalThis.localStorage is supported in all the environments where this code will run. If not, add a check for its existence to avoid potential runtime errors.


13-13: LGTM! Conditional logging is correctly implemented.

The conditional logging based on DEBUG_MAPCSS flag is correctly implemented and should not impact performance significantly.

src/core/router/getAbsoluteRoute.ts (2)

19-19: LGTM! Property name change is consistent.

The change from parentRoute to parentRouteId is consistent with the new property naming convention.


20-20: LGTM! Conditional property name change is consistent.

The change from parentRoute to parentRouteId in the conditional statement is consistent with the new property naming convention.

src/core/app/postAppInit.ts (1)

Line range hint 1-12:
LGTM! Removal of autoClearAtom initialization.

The removal of autoClearAtom initialization seems appropriate and should not introduce issues. Ensure that this atom is no longer required in the initialization flow.

src/core/app/authHooks.ts (2)

2-2: LGTM! Import path change is correct.

The change in the import path for currentUserAtom is correct and consistent with the project's structure.


13-13: LGTM! Usage change is correct.

The change from setFeatures to featureFlagsAtom.set.dispatch is correct and consistent with the updated logic.

src/core/router/types.ts (1)

4-4: LGTM!

The changes to add the id field and update parentRoute to parentRouteId are clear and correctly implemented.

Also applies to: 17-17

src/core/router/atoms/availableRoutes.ts (1)

29-29: LGTM!

The change to use parentRouteId instead of parentRoute is consistent with the refactor.

src/core/metrics/index.ts (1)

16-17: LGTM!

The changes to use routeId instead of route in the initMetricsOnce function are correctly implemented.

Also applies to: 25-25

src/core/config/loaders/appConfigLoader.ts (1)

27-27: LGTM!

The addition of the ts parameter to bypass the cache is correctly implemented.

src/core/router/atoms/currentRoute.ts (2)

20-27: Ensure correct usage of configRepo for base URL.

The changes correctly use configRepo to get the base URL. This ensures that the base URL is dynamically fetched.


35-40: Function stripBasename looks good.

The function correctly strips the basename from the pathname.

src/features/side_bar/components/SideBar/NavButton.tsx (1)

29-35: Changes to NavButton look good.

The changes correctly replace parentRoute with parentRouteId.

src/core/auth/client/AuthClient.ts (1)

Line range hint 27-27:
Ensure correct logout behavior.

The logout method no longer requires async/await. Ensure that this change does not impact the behavior of the method.

src/features/side_bar/components/SideBar/routeVisibilityChecker.test.ts (4)

29-29: Approved: Added id field to foo route.

This change is consistent with the new requirement for routes to have an id field.


35-35: Approved: Added id field to bar route.

This change is consistent with the new requirement for routes to have an id field.


41-42: Approved: Added id and parentRouteId fields to bar_child route.

This change is consistent with the new requirement for routes to have an id and parentRouteId field.


48-49: Approved: Added id and parentRouteId fields to bar_child_neighbor route.

This change is consistent with the new requirement for routes to have an id and parentRouteId field.

src/core/store/store.ts (1)

39-39: Approved: Removed unnecessary debug log statement.

This change removes unnecessary debug logging, which is a good practice for production code.

src/features/layers_in_area/atoms/areaLayersDetailsResource/areaLayersDetailsResourceAtomCache.ts (1)

34-34: Approved: Simplified cache structure by removing the user property.

This change simplifies the cache structure, which should improve maintainability and performance.

src/core/router/components/Router.tsx (2)

57-58: Approved: Replaced parentRoute with parentRouteId and added id field to route objects.

This change is consistent with the new requirement for routes to have an id and parentRouteId field.


97-97: Approved: Updated PostInit function call to pass the route.id as an argument.

This change ensures that the PostInit function receives the correct route ID.

src/core/router/routes.tsx (6)

33-33: LGTM! Adding an id field for the 'map' route.

The addition of an id field helps in uniquely identifying routes and enhances maintainability.


42-42: LGTM! Adding an id field for the 'reports' route.

This addition maintains consistency and improves route identification.


50-56: LGTM! Adding an id field and updating to parentRouteId for the 'report' route.

The introduction of parentRouteId and id fields enhances route management and consistency.


68-68: LGTM! Adding an id field for the 'profile' route.

This change ensures consistency across route configurations and enhances maintainability.


93-98: LGTM! Adding an id field and updating to parentRouteId for the 'privacy' route.

The introduction of parentRouteId and id fields aligns with the updated route management strategy.


103-108: LGTM! Adding an id field and updating to parentRouteId for the 'cookies' route.

This change is consistent with other route configurations and improves maintainability.

src/core/api_client/errors.ts (3)

28-28: LGTM! Improved error description parsing.

Using the error_description field from the error data enhances the clarity of error messages.


53-61: LGTM! Enhanced error message parsing for HTML responses.

Converting HTML to text ensures cleaner and more readable notifications.


78-81: LGTM! Refined error handling for status codes 400 and 401.

Providing specific problem descriptions for different status codes enhances error handling and user feedback.

src/core/metrics/app-metrics.ts (2)

62-64: LGTM! Updated init function to use routeId.

Using routeId instead of route aligns with the updated route management strategy and improves clarity.


82-86: LGTM! Updated debug log to include routeId.

Ensuring consistency in logging and debugging helps maintain clarity and traceability.

package.json (3)

99-99: Dependency Update: Verify compatibility for @reatom/npm-react.

Ensure the updated version is compatible with the rest of the project and does not introduce breaking changes.


116-116: Dependency Update: Verify compatibility for @types/node.

Ensure the updated version is compatible with the rest of the project and does not introduce breaking changes.


185-186: Dependency Update: Verify compatibility for react-router and react-router-dom.

Ensure the updated versions are compatible with the rest of the project and do not introduce breaking changes.

src/core/api_client/apiClient.ts (2)

25-25: Introduction of TIME_TO_REFRESH_MS improves maintainability.

The introduction of the constant TIME_TO_REFRESH_MS for token refresh intervals improves code maintainability and readability.


274-274: Modification of logout method.

The logout method is no longer async, which is appropriate since it is not performing any asynchronous operations.

@albaranau albaranau requested a review from a team July 10, 2024 12:43
src/core/api_client/apiClient.ts Outdated Show resolved Hide resolved
src/core/metrics/app-metrics.ts Outdated Show resolved Hide resolved
src/core/postInit.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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 0ff18b0 and c1d0e7b.

Files selected for processing (7)
  • src/core/api_client/apiClient.ts (7 hunks)
  • src/core/metrics/app-metrics.ts (3 hunks)
  • src/core/metrics/constants.ts (2 hunks)
  • src/core/metrics/index.ts (1 hunks)
  • src/core/postInit.ts (1 hunks)
  • src/core/router/components/Router.tsx (4 hunks)
  • src/features/side_bar/components/SideBar/routeVisibilityChecker.test.ts (1 hunks)
Additional comments not posted (12)
src/core/postInit.ts (1)

6-7: Consider renaming the function to start with a lowercase letter.

Since this is not a component, it might be better to start the function name with a lowercase letter (postInit).

- export function postInit(routeId: string) {
+ export function postInit(routeId: string) {

Likely invalid or redundant comment.

src/core/metrics/index.ts (1)

14-27: LGTM!

The initMetricsOnce function initializes metrics correctly, checks for development mode, and conditionally initializes external metrics.

src/core/metrics/constants.ts (1)

33-37: LGTM!

The buildWatchList function builds an effective watch list based on configuration features.

src/core/router/components/Router.tsx (3)

57-58: Enhancement: Added unique IDs for routes.

Adding unique IDs to routes helps in better route identification and management.


58-58: Improvement: Modified path construction logic.

Changing the path construction logic to use parentRouteId instead of parentRoute improves the hierarchy and readability of routes.


96-97: Initialization Step: Added postInit call.

Calling postInit after router initialization ensures that any remaining app initialization steps that depend on the router are executed.

src/core/metrics/app-metrics.ts (3)

61-63: Enhancement: Added routeId parameter to init method.

Including the routeId parameter allows conditional initialization of metrics based on the route, which is a good way to optimize metric tracking.


70-70: Improvement: Building the watch list.

Building the watch list ensures that all necessary metrics are tracked from the beginning.


80-84: Debugging: Added debug logs for metrics initialization.

Including debug logs helps in troubleshooting and verifying that the metrics are initialized correctly.

src/core/api_client/apiClient.ts (3)

94-100: Debugging: Added debug logs for token information.

Including debug logs helps in verifying that the tokens are decoded and stored correctly.


136-141: Improvement: Set timeToRefresh based on token lifetime.

Ensuring timeToRefresh is shorter than the token lifetime helps in timely refreshing the token, thus preventing token expiration issues.


274-274: Simplification: Removed async keyword from logout method.

Simplifying the logout method makes the code cleaner and easier to maintain.

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

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between c1d0e7b and 1057d52.

Files selected for processing (1)
  • src/features/side_bar/components/SideBar/routeVisibilityChecker.ts (2 hunks)
Additional context used
Biome
src/features/side_bar/components/SideBar/routeVisibilityChecker.ts

[error] 29-29: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 30-32: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 33-35: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 36-36: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

Additional comments not posted (2)
src/features/side_bar/components/SideBar/routeVisibilityChecker.ts (2)

6-11: Ensure correct type and initialization for routesTree.

The changes to use parentRouteId and id are consistent with the PR objectives. However, consider wrapping this logic in a block to restrict access as suggested by static analysis.

  const routesTree = routes.reduce((tree, route) => {
+    {
      if (route.parentRouteId) {
        if (!tree[route.parentRouteId]) tree[route.parentRouteId] = {};
        tree[route.parentRouteId][route.id] = {};
        return tree;
      }
      tree[route.id] = {};
      return tree;
+    }
  }, {} as RoutesTree);

27-36: Wrap switch clause declarations in blocks.

The changes to use parentRouteId and id are consistent with the PR objectives. However, the declarations inside the switch clause should be wrapped in blocks to prevent access from other clauses.

        if (!route.parentRouteId) return true;
        if (currentRoute === null) return false;
+        {
          const isActive = route.id === currentRoute.id;
          const haveActiveParentRoute = route.parentRouteId
            ? currentRoute?.id === route.parentRouteId
            : false;
          const neighbors = route.parentRouteId
            ? Object.keys(routesTree[route.parentRouteId])
            : [];
          const haveActiveNeighbor = neighbors.includes(currentRoute.id);

          return isActive || haveActiveParentRoute || haveActiveNeighbor;
+        }
Tools
Biome

[error] 29-29: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 30-32: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 33-35: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 36-36: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

@vkozio vkozio merged commit 86ca049 into main Jul 11, 2024
7 checks passed
@vkozio vkozio deleted the 17734-fe-page-reloading-when-invalid-credentials-are-entered-during-login branch July 11, 2024 09:14
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