Skip to content

Commit

Permalink
feat(router): add sortRoutesByOrder function
Browse files Browse the repository at this point in the history
  • Loading branch information
Azir-11 committed Jan 11, 2024
1 parent 748cfa2 commit 0cf09ba
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/store/modules/route/index.ts
Expand Up @@ -18,6 +18,7 @@ import {
getGlobalMenusByAuthRoutes,
getSelectedMenuKeyPathByKey,
isRouteExistByRouteName,
sortRoutesByOrder,
updateLocaleOfGlobalMenus
} from './shared';

Expand Down Expand Up @@ -185,11 +186,13 @@ export const useRouteStore = defineStore(SetupStoreId.Route, () => {
* @param routes Auth routes
*/
function handleAuthRoutes(routes: ElegantConstRoute[]) {
const vueRoutes = getAuthVueRoutes(routes);
const sortRoutes = sortRoutesByOrder(routes);

const vueRoutes = getAuthVueRoutes(sortRoutes);

addRoutesToVueRouter(vueRoutes);

getGlobalMenus(routes);
getGlobalMenus(sortRoutes);

getCacheRoutes(vueRoutes);
}
Expand Down
16 changes: 16 additions & 0 deletions src/store/modules/route/shared.ts
Expand Up @@ -44,6 +44,22 @@ function filterAuthRouteByRoles(route: ElegantConstRoute, roles: string[]) {
return hasPermission ? [filterRoute] : [];
}

/**
* Sort routes by order
*
* @param routes An array of routes
* @returns A new array of routes sorted by order
*
* This function sorts the routes by their order property, which is a number. If the order property is missing or
* invalid, it is treated as 0. The routes with lower order values are placed before the routes with higher order
* values. The function also sorts the children routes recursively, if any.
*/
export const sortRoutesByOrder = (routes: ElegantConstRoute[]): ElegantConstRoute[] => {
return routes
.sort((next, prev) => (Number(next.meta?.order) || 0) - (Number(prev.meta?.order) || 0))
.map(route => (route.children ? { ...route, children: sortRoutesByOrder(route.children) } : route));
};

/**
* Get global menus by auth routes
*
Expand Down

0 comments on commit 0cf09ba

Please sign in to comment.