import { routeTopologyStore } from "../stores/route-topology.store"; import { beanUtilsService } from "../services/bean-utils.service"; /** * @description: 路由拓扑服务 * @author ChenRui * @date 2020/7/29 18:47 */ export class RouteTopologyService { /** * @description: 初始化 * @author ChenRui * @date 2020/8/29 19:56 */ init(router: any): any { const routes: any[] = router.options.routes; const treeRoutes: any[] = this.treeRecursion(routes); // 树形结构 const horizontalRoutes: any[] = this.horizontalRecursion(treeRoutes); // 水平结构 routeTopologyStore.inited = true; routeTopologyStore.treeRoutes = treeRoutes; routeTopologyStore.horizontalRoutes = horizontalRoutes; } /** * @description: 是否已初始化 * @author ChenRui * @date 2020/8/29 19:57 */ isInit(): boolean { return routeTopologyStore.inited; } /** * @description: 检查初始化状态 * @author ChenRui * @date 2020/8/29 19:57 */ checkAndInit(router: any): void { if (!this.isInit()) { this.init(router); } } /** * @description: 树形结构 * @author ChenRui * @date 2020/8/29 19:58 */ treeRecursion(routes: any[], parentPath = "", treeRoutes: any[] = []): any[] { parentPath = parentPath + (parentPath === "" ? "" : "/"); routes.forEach((item) => { let parent = ""; if (item.meta && item.meta.parent) { if (item.meta.parent.indexOf("./") === 0) { parent = parentPath + item.meta.parent.replace("./", ""); } else { parent = item.meta.parent; } } const it: any = { path: parentPath + item.path, meta: item.meta, parent: parent, }; if (item.children != null && item.children.length > 0) { it.children = []; this.treeRecursion(item.children, it.path, it.children); } treeRoutes.push(it); }); return treeRoutes; } /** * @description: 逻辑结构 * @author ChenRui * @date 2020/8/29 19:58 */ horizontalRecursion(treeRoutes: any[], horizontalRoutes: any[] = []): any { treeRoutes.forEach((item) => { horizontalRoutes.push({ path: item.path, meta: item.meta, parent: item.parent, }); if (item.children != null && item.children.length > 0) { this.horizontalRecursion(item.children, horizontalRoutes); } }); return horizontalRoutes; } /** * @description: 查找节点 * @author ChenRui * @date 2020/8/29 19:58 */ fetchNodes(path: string, nodes: any[] = []): any[] { const horizontalRoutes: any[] = routeTopologyStore.horizontalRoutes || []; const node = horizontalRoutes.find((it: any) => it.path === path); if (node != null) { nodes.push(beanUtilsService.copy(node)); if (node.parent) { this.fetchNodes(node.parent, nodes); } } return nodes; } } const routeTopologyService = new RouteTopologyService(); export { routeTopologyService };