feat(service): 完善request方法

This commit is contained in:
Coffee-crocodile 2023-01-13 16:43:38 +08:00
parent 014f728faf
commit 310dc43830
6 changed files with 127 additions and 104 deletions

View File

@ -6,56 +6,56 @@ import { useRouteStore } from '@/store';
const modules = import.meta.glob('../../views/**/*.vue');
/* 将路由树转换成一维数组 */
function FlatAuthRoutes(routes: AppRoute.Route[]) {
let result: AppRoute.Route[] = [];
// 浅拷贝一层去降维,否则影响原数组
const _routes = JSON.parse(JSON.stringify(routes));
_routes.forEach((item: any) => {
if (item.children) {
const temp = item.children || [];
delete item.children;
result.push(item);
result = [...result, ...FlatAuthRoutes(temp)];
} else {
result.push(item);
}
});
return result;
let result: AppRoute.Route[] = [];
// 浅拷贝一层去降维,否则影响原数组
const _routes = JSON.parse(JSON.stringify(routes));
_routes.forEach((item: any) => {
if (item.children) {
const temp = item.children || [];
delete item.children;
result.push(item);
result = [...result, ...FlatAuthRoutes(temp)];
} else {
result.push(item);
}
});
return result;
}
function createCatheRoutes(routes: AppRoute.Route[]) {
return routes
.filter((item) => {
return item.meta.keepAlive;
})
.map((item) => item.name);
return routes
.filter((item) => {
return item.meta.keepAlive;
})
.map((item) => item.name);
}
export async function createDynamicRoutes(routes: AppRoute.Route[]) {
// 数组降维成一维数组,然后删除所有的childen
const flatRoutes = FlatAuthRoutes(routes);
// 对降维后的数组过滤需要缓存的路由name数组
const routeStore = useRouteStore();
routeStore.cacheRoutes = createCatheRoutes(flatRoutes);
// 生成路由有redirect的不需要引入文件
const mapRoutes = flatRoutes.map((item) => {
if (!item.redirect) {
// 动态加载对应页面
item['component'] = modules[`../../views${item.path}/index.vue`];
}
return item;
});
// 数组降维成一维数组,然后删除所有的childen
const flatRoutes = FlatAuthRoutes(routes);
// 对降维后的数组过滤需要缓存的路由name数组
const routeStore = useRouteStore();
routeStore.cacheRoutes = createCatheRoutes(flatRoutes);
// 生成路由有redirect的不需要引入文件
const mapRoutes = flatRoutes.map((item: any) => {
if (!item.redirect) {
// 动态加载对应页面
item['component'] = modules[`../../views${item.path}/index.vue`];
}
return item;
});
const appRootRoute: RouteRecordRaw = {
path: '/',
name: 'appRoot',
redirect: '/dashboard/workbench',
component: BasicLayout,
meta: {
title: '首页',
icon: 'icon-park-outline:home',
},
children: [],
};
// 根据角色过滤后的插入根路由中
appRootRoute.children = mapRoutes as unknown as RouteRecordRaw[];
return appRootRoute;
const appRootRoute: RouteRecordRaw = {
path: '/',
name: 'appRoot',
redirect: '/dashboard/workbench',
component: BasicLayout,
meta: {
title: '首页',
icon: 'icon-park-outline:home',
},
children: [],
};
// 根据角色过滤后的插入根路由中
appRootRoute.children = mapRoutes as unknown as RouteRecordRaw[];
return appRootRoute;
}

View File

@ -4,15 +4,19 @@ interface Ilogin {
userName: string;
password: string;
}
interface Itoken {
token: string;
refreshToken: string;
}
export function fetchLogin(params: Ilogin) {
return mockRequest.post('/login', params);
return mockRequest.post<any>('/login', params);
}
export function fetchUpdateToken(params: string) {
return mockRequest.post('/updateToken', params);
return mockRequest.post<Itoken>('/updateToken', params);
}
export function fetchUserInfo() {
return mockRequest.get('/getUserInfo');
}
export function fetchUserRoutes(params: string) {
return mockRequest.post('/getUserRoutes', params);
return mockRequest.post<any>('/getUserRoutes', params);
}

View File

@ -14,7 +14,7 @@ export function fetachPost(params: Itest) {
}
/* delete方法测试 */
export function fetachDelete() {
return request.Delete('/deleteAPI');
return request.delete('/deleteAPI');
}
/* put方法测试 */
export function fetachPut(params: Itest) {

View File

@ -24,10 +24,10 @@ export default class createAxiosInstance {
// 基础配置
axiosConfig: AxiosRequestConfig = {};
constructor(axiosConfig: AxiosRequestConfig, backendConfig: Service.BackendResultConfig) {
constructor(axiosConfig: AxiosRequestConfig, backendConfig: Service.BackendResultConfig = DEFAULT_BACKEND_OPTIONS) {
// 设置了axios实例上的一些默认配置,新配置会覆盖默认配置
this.instance = axios.create({ ...DEFAULT_AXIOS_OPTIONS, ...axiosConfig });
this.backendConfig = { ...DEFAULT_BACKEND_OPTIONS, ...backendConfig };
this.instance = axios.create({ ...DEFAULT_AXIOS_OPTIONS, ...axiosConfig });
this.setInterceptor();
}
// 设置类拦截器的函数
@ -39,6 +39,7 @@ export default class createAxiosInstance {
// 数据格式转换
// handleConfig.headers.setContentType('application/json');
// const contentType = handleConfig.headers.get('Content-Type');
const contentType = 'application/json';
handleConfig.data = await transformRequestData(handleConfig.data, contentType);

View File

@ -1,94 +1,112 @@
import type { AxiosRequestConfig } from 'axios';
import type { AxiosRequestConfig, AxiosInstance } from 'axios';
import createAxiosInstance from './instance';
type RequestMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
interface RequestParam {
url: string;
method?: RequestMethod;
data?: any;
config?: AxiosRequestConfig;
}
async function getRequestResponse(params: {
instance: AxiosInstance;
method: RequestMethod;
url: string;
data?: any;
config?: AxiosRequestConfig;
}) {
const { instance, method, url, data, config } = params;
let res: any;
if (method === 'get' || method === 'delete') {
res = await instance[method](url, config);
} else {
res = await instance[method](url, data, config);
}
return res;
}
/**
* @description:
* @param {AxiosRequestConfig} axiosConfig - axios配置
* @param {Service} backendConfig -
* @return {*}
*/
export function createRequest(
axiosConfig: AxiosRequestConfig,
backendConfig?: Service.BackendResultConfig
) {
export function createRequest(axiosConfig: AxiosRequestConfig, backendConfig?: Service.BackendResultConfig) {
const axiosInstance = new createAxiosInstance(axiosConfig, backendConfig);
const { instance } = axiosInstance;
/**
* @description:
* @param {string} url-
* @param {RequestMethod} method -
* @param {any} data -
* @param {AxiosRequestConfig} config -
* @return {*}
* promise请求
* @param param -
* - url: 请求地址
* - method: 请求方法(get)
* - data: 请求的body的data
* - config: axios配置
*/
type RequestMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
const request = async (
url: string,
method: RequestMethod = 'get',
data: any,
config?: AxiosRequestConfig
) => {
return instance(url, { method, data, ...config });
};
async function asyncRequest<T>(param: RequestParam): Promise<Service.RequestResult<T>> {
const { url, method = 'get', data, config } = param;
const { instance } = axiosInstance;
const res = (await getRequestResponse({
instance,
method,
url,
data,
config,
})) as Service.RequestResult<T>;
return res;
}
/**
* @description: get请求
* @param {string} url -
* @return {*}
* get请求
* @param url -
* @param config - axios配置
*/
const get = async (url: string, config?: AxiosRequestConfig) => {
return instance.get(url, config);
};
function get<T>(url: string, config?: AxiosRequestConfig) {
return asyncRequest<T>({ url, config: config });
}
/**
* @description: post请求
* post请求
* @param url -
* @param data - body的data
* @param config - axios配置
*/
const post = async (url: string, data?: any, config?: AxiosRequestConfig) => {
return instance.post(url, data, config);
};
function post<T>(url: string, data?: any, config?: AxiosRequestConfig) {
return asyncRequest<T>({ url, method: 'post', data, config: config });
}
/**
* @description: delete请求
* delete请求
* @param url -
* @param config - axios配置
*/
const Delete = async (url: string, config?: AxiosRequestConfig) => {
return instance.delete(url, config);
};
function handleDelete<T>(url: string, config?: AxiosRequestConfig) {
return asyncRequest<T>({ url, method: 'delete', config: config });
}
/**
* @description: put请求
* put请求
* @param url -
* @param data - body的data
* @param config - axios配置
*/
const put = async (url: string, data?: any, config?: AxiosRequestConfig) => {
return instance.put(url, data, config);
};
function put<T>(url: string, data?: any, config?: AxiosRequestConfig) {
return asyncRequest<T>({ url, method: 'put', data, config: config });
}
/**
* @description: patch请求
* patch请求
* @param url -
* @param data - body的data
* @param config - axios配置
*/
const patch = async (
url: string,
data?: any,
config?: AxiosRequestConfig
) => {
return instance.patch(url, data, config);
};
function patch<T>(url: string, data?: any, config?: AxiosRequestConfig) {
return asyncRequest<T>({ url, method: 'patch', data, config: config });
}
return {
request,
get,
post,
Delete,
delete: handleDelete,
put,
patch,
};

View File

@ -255,7 +255,7 @@ onMounted(() => {
});
async function getUserList() {
startLoading();
await fetchUserList().then((res) => {
await fetchUserList().then((res: any) => {
listData.value = res.data;
endLoading();
});