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

perf: 优化 router/guard.ts #4402

Merged
merged 0 commits into from
Sep 18, 2024
Merged

perf: 优化 router/guard.ts #4402

merged 0 commits into from
Sep 18, 2024

Conversation

kkfive
Copy link
Contributor

@kkfive kkfive commented Sep 14, 2024

Description

  1. 主要是将 router/guard.ts 文件进行拆分
  2. 添加了 @vue/language-server 依赖 主要服务 webstorm

20240914160941X7ayPIBQ000834

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Enhanced access control logic with modular functions for improved readability and maintainability.
    • Added support for better handling of routes based on access tokens and user roles.
  • Bug Fixes

    • Streamlined redirection logic for users without access tokens.
  • Chores

    • Updated development dependencies to improve Vue.js language support.

@kkfive kkfive requested review from anncwb, vince292007 and a team as code owners September 14, 2024 08:11
Copy link

changeset-bot bot commented Sep 14, 2024

⚠️ No Changeset found

Latest commit: bfae962

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Sep 14, 2024

Walkthrough

The changes involve a significant refactoring of the access control logic in the setupAccessGuard function across multiple files. The original logic has been modularized by extracting specific functionalities into separate helper functions: handleBaseRoutes, handleNoAccessToken, and generateAndSetAccess. Additionally, a new dependency, @vue/language-server, has been added to the package.json file to enhance the development environment for Vue.js applications.

Changes

File Change Summary
apps/web-antd/src/router/guard.ts Refactored setupAccessGuard by adding handleBaseRoutes, handleNoAccessToken, and generateAndSetAccess.
apps/web-ele/src/router/guard.ts Similar refactoring of setupAccessGuard with the addition of the same helper functions.
apps/web-naive/src/router/guard.ts Refactored setupAccessGuard to include new helper functions for improved structure.
playground/src/router/guard.ts Restructured setupAccessGuard and added the same helper functions to enhance code clarity.
package.json Added dependency @vue/language-server with version ^2.1.6.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Router
    participant AccessGuard
    participant AccessStore

    User->>Router: Request Route
    Router->>AccessGuard: Call setupAccessGuard
    AccessGuard->>AccessGuard: handleBaseRoutes
    AccessGuard->>AccessGuard: handleNoAccessToken
    AccessGuard->>AccessStore: generateAndSetAccess
    AccessStore-->>AccessGuard: Update Access
    AccessGuard-->>Router: Redirect or Allow Access
Loading

🐇 In the code, a hop and a skip,
New functions added, they surely equip.
With clearer paths and roles defined,
Access granted, all aligned!
So let’s cheer for the changes made,
A brighter code, in the glade! 🌼


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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range and nitpick comments (3)
playground/src/router/guard.ts (3)

55-63: Base route handling logic looks good!

The function correctly handles the base route logic by checking if the target route is the login path and if an access token exists, redirecting appropriately. Using the DEFAULT_HOME_PATH constant for redirection is a good practice.

Consider using more specific types for the to and accessStore parameters instead of any to improve type safety.


65-77: No access token handling logic looks good!

The function correctly handles scenarios where no access token is present by checking if access should be ignored based on route metadata and redirecting to the login page if necessary. Using route metadata to determine if access should be ignored is a good practice.

Consider using more specific types for the to and meta parameters instead of any to improve type safety.


79-94: Access generation and setting logic looks good!

The function correctly generates and sets access permissions by using the generateAccess function to generate accessible menus and routes based on user roles and routes, and updating the access store accordingly. Using the generateAccess function for this purpose is a good practice.

Consider using a more specific type for the accessStore parameter instead of any to improve type safety.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d99cad3 and 03c2861.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (5)
  • apps/web-antd/src/router/guard.ts (1 hunks)
  • apps/web-ele/src/router/guard.ts (1 hunks)
  • apps/web-naive/src/router/guard.ts (1 hunks)
  • package.json (1 hunks)
  • playground/src/router/guard.ts (1 hunks)
Additional comments not posted (14)
apps/web-antd/src/router/guard.ts (4)

56-63: LGTM!

The handleBaseRoutes function correctly handles the basic routes and access token checks. It safely decodes the redirect path from the query using decodeURIComponent and returns the appropriate value based on the conditions.


66-77: LGTM!

The handleNoAccessToken function correctly handles the case when there is no access token. It checks if access should be ignored based on the meta.ignoreAccess property and redirects to the login page with the original path encoded in the query using encodeURIComponent if necessary. The function returns the appropriate value based on the conditions.


80-94: LGTM!

The generateAndSetAccess function correctly generates and sets access permissions based on the user roles. It calls the generateAccess function with the necessary parameters to retrieve the accessible menus and routes. The function updates the access store with the retrieved data and sets the isAccessChecked flag to indicate that the access check has been performed.


Line range hint 97-126: Great refactoring!

The changes made to the setupAccessGuard function significantly improve the readability and maintainability of the access guard logic. The extraction of specific functionalities into separate helper functions (handleBaseRoutes, handleNoAccessToken, and generateAndSetAccess) encapsulates responsibilities and makes the main guard function more concise and easier to understand.

The refactoring enhances the code organization while preserving the original functionality of the access guard. The helper functions are well-defined and handle their respective tasks effectively.

Overall, the changes are a positive improvement to the codebase.

apps/web-ele/src/router/guard.ts (4)

56-63: LGTM!

The handleBaseRoutes function is well-structured and correctly handles the base routes based on the provided conditions. The function name and parameters are descriptive, making the code readable and maintainable.


66-77: LGTM!

The handleNoAccessToken function is well-structured and correctly handles the scenarios where no access token is available. It checks the metadata to determine if access should be ignored and redirects to the login page when necessary. The function name and parameters are descriptive, making the code readable and maintainable.


80-94: LGTM!

The generateAndSetAccess function is well-structured and correctly generates and sets the access permissions based on user roles. It utilizes the generateAccess function to obtain the accessible menus and routes and updates the access store accordingly. The function name and parameters are descriptive, making the code readable and maintainable. The use of await ensures that the asynchronous operation is handled correctly.


Line range hint 97-126: Great refactoring!

The refactored setupAccessGuard function is more readable and maintainable due to the separation of concerns into smaller, focused helper functions. The function correctly utilizes the new helper functions to handle base routes, no access token scenarios, and generating access permissions. The use of await ensures that the asynchronous operations are handled correctly, and the function returns the appropriate redirects or true based on the access conditions. This refactoring enhances the clarity and modularity of the access control logic.

apps/web-naive/src/router/guard.ts (4)

56-63: LGTM!

The handleBaseRoutes function correctly handles the redirection logic for core routes. It checks if the route is the login path and an access token exists, then redirects to the original destination or the default home path. The use of decodeURIComponent to safely decode the redirect query parameter is a good practice to prevent potential security issues.


66-77: LGTM!

The handleNoAccessToken function correctly handles the case when no access token is available. It checks if access should be ignored based on route metadata and redirects to the login page if necessary. The use of encodeURIComponent to safely encode the redirect query parameter is a good practice to prevent potential security issues.


80-94: LGTM!

The generateAndSetAccess function correctly generates and sets the accessible menus and routes based on user roles. It uses the generateAccess function to generate the accessible menus and routes, updates the access store with the generated data, and marks access as checked. This function streamlines the process of setting up user permissions.


Line range hint 97-126: LGTM!

The setupAccessGuard function correctly sets up the access guard for the router. It uses the handleBaseRoutes, handleNoAccessToken, and generateAndSetAccess functions to handle different scenarios, which improves the maintainability and readability of the code. It also fetches the user info and roles if access is not checked, which is a good practice to ensure that the user has the necessary permissions.

playground/src/router/guard.ts (1)

Line range hint 96-125: Great job restructuring the setupAccessGuard function!

The restructuring has significantly improved the readability and maintainability of the function. It now primarily orchestrates the access guard flow by calling the appropriate helper functions to handle base routes, no access token scenarios, and access generation.

Using the coreRouteNames array to check for core route names and the router.resolve method to resolve the redirect path are good practices.

Overall, the changes have made the access guard logic easier to follow and maintain.

package.json (1)

79-79: Dependency addition looks good!

The @vue/language-server dependency has been added with an appropriate version constraint. This change aligns with the PR objective of enhancing the development experience for Vue.js applications.

@vince292007 vince292007 merged commit bfae962 into vbenjs:main Sep 18, 2024
40 of 43 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Oct 19, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants