forked from cloudforet-io/console
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-service-router.ts
81 lines (64 loc) · 2.42 KB
/
use-service-router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { useRouter } from 'vue-router/composables';
import type { Location } from 'vue-router/types/router';
import { useGlobalConfigSchemaStore } from '@/store/global-config-schema/global-config-schema-store';
import type { MenuId } from '@/lib/menu/config';
type RouterOptionsType = {
feature: MenuId;
routeKey: string;
name?: string;
params?: Record<string, any>;
};
type NavigateOptionsType = RouterOptionsType & {
method: 'push' | 'replace';
};
export const useServiceRouter = () => {
const globalConfigSchemaStore = useGlobalConfigSchemaStore();
const globalConfigSchemaState = globalConfigSchemaStore.state;
const transformParams = (
paramConfig: Record<string, any>,
sourceParams: Record<string, any>,
): Record<string, any> => {
const result: Record<string, any> = {};
Object.entries(paramConfig).forEach(([key, targetKey]) => {
if (sourceParams[key] !== undefined) {
result[targetKey] = sourceParams[key];
}
});
return result;
};
const getLocation = (options: RouterOptionsType): Location => {
const {
feature, routeKey, params,
} = options;
const featureMetadata = globalConfigSchemaState.routeMetadataSchema[feature.toUpperCase()];
const convertedParams = params ? transformParams(featureMetadata[routeKey].params || {}, params) : undefined;
if (!featureMetadata) {
return { name: feature, params: convertedParams };
}
const routeConfig = featureMetadata[routeKey];
if (!routeConfig) {
return { name: feature, params: convertedParams };
}
return {
name: routeConfig.name,
params: convertedParams,
};
};
const navigate = async (options: NavigateOptionsType) => {
const router = useRouter();
const { method } = options;
const location = getLocation(options);
return router[method](location);
};
const resolve = (options: RouterOptionsType) => {
const router = useRouter();
const location = getLocation(options);
return router.resolve(location);
};
return {
push: (options: RouterOptionsType) => navigate({ ...options, method: 'push' }),
replace: (options: RouterOptionsType) => navigate({ ...options, method: 'replace' }),
getLocation,
resolve,
};
};