提交 a821d9a3 编写于 作者: V Vben

perf: imporve axios logic

上级 7c2f8516
import { defHttp } from '/@/utils/http/axios';
import { GetAccountInfoModel } from './model/accountModel';
const { get } = defHttp;
enum Api {
ACCOUNT_INFO = '/account/getAccountInfo',
}
// Get personal center-basic settings
export function accountInfoApi() {
return defHttp.request<GetAccountInfoModel>({
url: Api.ACCOUNT_INFO,
method: 'GET',
});
}
export const accountInfoApi = () => get<GetAccountInfoModel>({ url: Api.ACCOUNT_INFO });
import { defHttp } from '/@/utils/http/axios';
const { get } = defHttp;
enum Api {
// The address does not exist
Error = '/error',
......@@ -8,9 +10,5 @@ enum Api {
/**
* @description: Trigger ajax error
*/
export function fireErrorApi() {
return defHttp.request({
url: Api.Error,
method: 'GET',
});
}
export const fireErrorApi = () => get({ url: Api.Error });
import { defHttp } from '/@/utils/http/axios';
import { DemoOptionsGetResultModel } from './model/optionsModel';
const { get } = defHttp;
enum Api {
OPTIONS_LIST = '/select/getDemoOptions',
......@@ -8,9 +9,4 @@ enum Api {
/**
* @description: Get sample options value
*/
export function optionsListApi() {
return defHttp.request<DemoOptionsGetResultModel>({
url: Api.OPTIONS_LIST,
method: 'GET',
});
}
export const optionsListApi = () => get<DemoOptionsGetResultModel>({ url: Api.OPTIONS_LIST });
import { defHttp } from '/@/utils/http/axios';
import { DemoParams, DemoListGetResultModel } from './model/tableModel';
const { get } = defHttp;
enum Api {
DEMO_LIST = '/table/getDemoList',
}
......@@ -8,13 +10,12 @@ enum Api {
/**
* @description: Get sample list value
*/
export function demoListApi(params: DemoParams) {
return defHttp.request<DemoListGetResultModel>({
export const demoListApi = (params: DemoParams) =>
get<DemoListGetResultModel>({
url: Api.DEMO_LIST,
method: 'GET',
params,
headers: {
ignoreCancelToken: true,
},
});
}
import { defHttp } from '/@/utils/http/axios';
import { getMenuListByIdParams, getMenuListByIdParamsResultModel } from './model/menuModel';
const { get } = defHttp;
enum Api {
GetMenuListById = '/getMenuListById',
}
......@@ -9,10 +10,7 @@ enum Api {
/**
* @description: Get user menu based on id
*/
export function getMenuListById(params: getMenuListByIdParams) {
return defHttp.request<getMenuListByIdParamsResultModel>({
url: Api.GetMenuListById,
method: 'GET',
params,
});
}
export const getMenuListById = (params: getMenuListByIdParams) => {
return get<getMenuListByIdParamsResultModel>({ url: Api.GetMenuListById, params });
};
......@@ -7,6 +7,7 @@ import {
} from './model/userModel';
import { ErrorMessageMode } from '/@/utils/http/axios/types';
const { post, get } = defHttp;
enum Api {
Login = '/login',
GetUserInfoById = '/getUserInfoById',
......@@ -17,10 +18,9 @@ enum Api {
* @description: user login api
*/
export function loginApi(params: LoginParams, mode: ErrorMessageMode = 'modal') {
return defHttp.request<LoginResultModel>(
return post<LoginResultModel>(
{
url: Api.Login,
method: 'POST',
params,
},
{
......@@ -33,17 +33,15 @@ export function loginApi(params: LoginParams, mode: ErrorMessageMode = 'modal')
* @description: getUserInfoById
*/
export function getUserInfoById(params: GetUserInfoByUserIdParams) {
return defHttp.request<GetUserInfoByUserIdModel>({
return get<GetUserInfoByUserIdModel>({
url: Api.GetUserInfoById,
method: 'GET',
params,
});
}
export function getPermCodeByUserId(params: GetUserInfoByUserIdParams) {
return defHttp.request<string[]>({
return get<string[]>({
url: Api.GetPermCodeByUserId,
method: 'GET',
params,
});
}
......@@ -165,6 +165,22 @@ export class VAxios {
};
}
get<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
return this.request({ ...config, method: 'GET' }, options);
}
post<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
return this.request({ ...config, method: 'POST' }, options);
}
put<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
return this.request({ ...config, method: 'PUT' }, options);
}
delete<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
return this.request({ ...config, method: 'DELETE' }, options);
}
request<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
let conf: AxiosRequestConfig = cloneDeep(config);
const transform = this.getTransform();
......@@ -173,7 +189,7 @@ export class VAxios {
const opt: RequestOptions = Object.assign({}, requestOptions, options);
const { beforeRequestHook, requestCatch, transformRequestData } = transform || {};
const { beforeRequestHook, requestCatchHook, transformRequestHook } = transform || {};
if (beforeRequestHook && isFunction(beforeRequestHook)) {
conf = beforeRequestHook(conf, opt);
}
......@@ -183,16 +199,16 @@ export class VAxios {
this.axiosInstance
.request<any, AxiosResponse<Result>>(conf)
.then((res: AxiosResponse<Result>) => {
if (transformRequestData && isFunction(transformRequestData)) {
const ret = transformRequestData(res, opt);
if (transformRequestHook && isFunction(transformRequestHook)) {
const ret = transformRequestHook(res, opt);
ret !== errorResult ? resolve(ret) : reject(new Error('request error!'));
return;
}
resolve((res as unknown) as Promise<T>);
})
.catch((e: Error) => {
if (requestCatch && isFunction(requestCatch)) {
reject(requestCatch(e));
if (requestCatchHook && isFunction(requestCatchHook)) {
reject(requestCatchHook(e));
return;
}
reject(e);
......
......@@ -3,14 +3,14 @@ import axios from 'axios';
import { isFunction } from '/@/utils/is';
// 声明一个 Map 用于存储每个请求的标识 和 取消函数
// Used to store the identification and cancellation function of each request
let pendingMap = new Map<string, Canceler>();
export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&');
export class AxiosCanceler {
/**
* 添加请求
* Add request
* @param {Object} config
*/
addPending(config: AxiosRequestConfig) {
......@@ -20,14 +20,14 @@ export class AxiosCanceler {
config.cancelToken ||
new axios.CancelToken((cancel) => {
if (!pendingMap.has(url)) {
// 如果 pending 中不存在当前请求,则添加进去
// If there is no current request in pending, add it
pendingMap.set(url, cancel);
}
});
}
/**
* @description: 清空所有pending
* @description: Clear all pending
*/
removeAllPending() {
pendingMap.forEach((cancel) => {
......@@ -37,14 +37,15 @@ export class AxiosCanceler {
}
/**
* 移除请求
* Removal request
* @param {Object} config
*/
removePending(config: AxiosRequestConfig) {
const url = getPendingUrl(config);
if (pendingMap.has(url)) {
// 如果在 pending 中存在当前请求标识,需要取消当前请求,并且移除
// If there is a current request identifier in pending,
// the current request needs to be cancelled and removed
const cancel = pendingMap.get(url);
cancel && cancel(url);
pendingMap.delete(url);
......@@ -52,7 +53,7 @@ export class AxiosCanceler {
}
/**
* @description: 重置
* @description: reset
*/
reset(): void {
pendingMap = new Map<string, Canceler>();
......
/**
* 数据处理类,可以根据项目自行配置
* Data processing class, can be configured according to the project
*/
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import type { RequestOptions, Result } from './types';
export abstract class AxiosTransform {
/**
* @description: 请求之前处理配置
* @description: Process configuration before request
* @description: Process configuration before request
*/
beforeRequestHook?: (config: AxiosRequestConfig, options: RequestOptions) => AxiosRequestConfig;
/**
* @description: 请求成功处理
* @description: Request successfully processed
*/
transformRequestData?: (res: AxiosResponse<Result>, options: RequestOptions) => any;
transformRequestHook?: (res: AxiosResponse<Result>, options: RequestOptions) => any;
/**
* @description: 请求失败处理
*/
requestCatch?: (e: Error) => Promise<any>;
requestCatchHook?: (e: Error) => Promise<any>;
/**
* @description: 请求之前的拦截器
......
// 接口返回值data不能为这个,否则会判为请求失败
// The interface return value data cannot be this, otherwise the request will be judged as a failure
export const errorResult = '__ERROR_RESULT__';
......@@ -13,15 +13,12 @@ export function createNow(join: boolean, restful = false): string | object {
if (restful) {
return `?_t=${now}`;
}
return {
_t: now,
};
return { _t: now };
}
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm';
/**
* @description: 格式化请求参数时间
* @description: Format request parameter time
*/
export function formatRequestDate(params: any) {
for (const key in params) {
......
......@@ -32,7 +32,7 @@ const transform: AxiosTransform = {
/**
* @description: 处理请求数据
*/
transformRequestData: (res: AxiosResponse<Result>, options: RequestOptions) => {
transformRequestHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
const { t } = useI18n();
const { isTransformRequestResult } = options;
// 不进行任何处理,直接返回
......
import type { AxiosRequestConfig } from 'axios';
import { AxiosTransform } from './axiosTransform';
import type { AxiosTransform } from './axiosTransform';
export type ErrorMessageMode = 'none' | 'modal' | 'message' | undefined;
export interface RequestOptions {
// 请求参数拼接到url
// Splicing request parameters to url
joinParamsToUrl?: boolean;
// 格式化请求参数时间
// Format request parameter time
formatDate?: boolean;
// 是否处理请求结果
// Whether to process the request result
isTransformRequestResult?: boolean;
// 是否加入url
// Whether to join url
joinPrefix?: boolean;
// 接口地址, 不填则使用默认apiUrl
// Interface address, use the default apiUrl if you leave it blank
apiUrl?: string;
// 错误消息提示类型
// Error message prompt type
errorMessageMode?: ErrorMessageMode;
// 是否加入时间戳
// Whether to add a timestamp
joinTime?: boolean;
}
......@@ -32,15 +31,16 @@ export interface Result<T = any> {
message: string;
result: T;
}
// multipart/form-data:上传文件
// multipart/form-data: upload file
export interface UploadFileParams {
// 其他参数
// Other parameters
data?: Indexable;
// 文件参数的接口字段名
// File parameter interface field name
name?: string;
// 文件
// file name
file: File | Blob;
// 文件名
// file name
filename?: string;
[key: string]: any;
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册