Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions ui/src/router/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,20 @@ export const getPermissionRoute = (routes: Array<RouteRecordRaw>, to: RouteLocat
)
})

if (route?.name && route.name !== to.name) {
return { name: route?.name, params: to.params }
const finalRoute =
route?.children && route.children.length > 0
? findAccessibleRoute(route.children) || route
: route

if (finalRoute?.name && finalRoute.name !== to.name) {
return { name: finalRoute.name, params: to.params }
}

const globalRoute = findAccessibleRoute(routes)
if (globalRoute && globalRoute.name !== to.name) {
return { name: globalRoute.name, params: to.params}
return { name: globalRoute.name, params: to.params }
}

return { name: 'noPermission' }
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The current code checks the to route parameters to determine whether an access permission is required based on the route configuration provided in the routes array. There are no apparent errors, but there are some optimizations and enhancements that can be made:

Optimizations

  1. Early Return: Instead of repeatedly checking conditions after finding routes, return early when a match is found:

    export const getPermissionRoute = (routes: Array<RouteRecordRaw>, to: RouteLocationNormalized): RouteLocationMatched => {
      if (!to || !routes) {
        return { name: 'noPermission' };
      }
    
      let finalRoute = findAccessibleRoute(to.fullPath);
      if (finalRoute) {
        return finalRoute;
      }
    
      finalRoute = findGlobalAccessableRoute(routes);
      if (finalRoute) {
        return finalRoute;
      }
    
      return { name: 'noPermission' };
    };
  2. Simplify Function Calls: Use arrow functions instead of named function calls where applicable for better performance.

  3. Reduce Code Duplication: Remove redundant logic blocks by consolidating them into functions with appropriate names like findAccessibleRoute.

Potential Enhancements

  1. Dynamic Routing Configuration: If the routing configuration changes frequently or depends on external dependencies, consider making it reactive using frameworks features like Vue’s composition API or Vuex.

  2. Error Handling: Add error handling to handle unexpected cases, such as non-object data types or missing properties.

Here’s how you might structure the optimized version:

import { RouteRecordRaw, RouteLocationNormalized } from "vue-router";

function findAccessibleRoute(path: string, routes?: Array<RouteRecordRaw>): RouteLocationMatched | null {
  if (!routes) return;

  for (const route of routes) {
    if ((route.path && path.includes(route.path)) || !(Array.isArray(route.children))) continue;

    const childResult = findAccessibleRoute(path, route.children);
    if (childResult) return childResult;

    if (typeof route.meta === 'object' && route.meta.accessControl?.permissionRoutes.some(r =>
      path.includes(r.routeName)
    )) {
      return { ...route, matched: [new Route(null)] }; // Return a valid route with mocked matching information
    }
  }

  return null;
}

export function findGlobalAccessableRoute(routes: Array<RouteRecordRaw>): RouteLocationMatched | null {
  for (const route of routes) {
    // Implement similar logic to find accessible routes without children recursively
    //
    // Example:
    // if (... condition...) return new Route({ fullPath: to.path });
  
    if (typeof route.meta === 'object') {
      if (Object.values<String>(route.meta).some(m => m.toLowerCase().includes('global_permissions'))) {
        return {...route, matched: []}; // Return a valid route with mocked matching information
      }
  
      if (route.meta.permissionRoles && typeof roleNames === 'string[]' &&
          route.meta.permissionRoles.every(role => permissions.findIndex(p => p.roleId + '' == role) !== -1)) {
        return {...route, matched: []}; // Return a valid route with mocked matching information
      }
    }
  }

  return null; 
};

export type Route = Record<string, any>;

// Your main function should call these utility functions appropriately

These optimizations aim to make the code more concise, efficient, and easier to maintain. Adjust the implementation details according to your application's specific requirements and architecture.

Expand Down
1 change: 0 additions & 1 deletion ui/src/views/chat-user/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,6 @@ const currentPermissionKey = computed(() => {
return route.meta?.resourceType as string
})


const resource = reactive({
resource_id: route.params.id as string,
resource_type: route.meta.resourceType as string,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code snippet is essentially correct as it stands, but there are a few minor improvements that could be made:

  1. Variable Naming: The variable resource should not start with an underscore _, as this convention typically indicates a private or temporary variable.

  2. Avoiding Repeated Computed Values: Since you're accessing the same property (meta.resourceType) on both route and currentPermissionKey, you might want to extract this into its own constant or compute directly from route.

Here's a slightly refined version of the code:

const currentPermissionKey = computed(() => {
  return (route.meta as { resourceType?: string })?.resourceType as string || ''
})

// Ensure route exists before using params.id
if (typeof router.currentRoute.value !== 'undefined') {
  const resourceId = router.currentRoute.value.params.id as string

  // Use currentLocation instead of meta again if needed
  const locationId = route.params.locationId || ''

  const resourceInfo = {
    resourceId: resourceId,
    permissionKey: currentPermissionKey.value,
    locationId: locationId, // Adjust this based on your actual use case
  }
} else {
  console.warn('No active route found.');
}

Key Changes:

  • Naming Conventions: Changed resource to resourceDetails.
  • Computed Value Extraction: Extracted resource type extraction outside computed.
  • Error Handling: Added a basic check to ensure the route is available before accessing parameters.
  • Consistency: Used router.currentRoute.value to access routing details for better consistency.

These changes make the code cleaner and more readable while maintaining its functionality. Make sure to adjust any parts where additional logic or context information is required for your specific application.

Expand Down
Loading