perf: easy to define fieldName of response data (#5442)

This commit is contained in:
Netfan
2025-01-20 18:38:49 +08:00
committed by GitHub
parent 5611f6c7f5
commit 22e6f28464
7 changed files with 80 additions and 46 deletions

View File

@@ -2,9 +2,48 @@ import type { RequestClient } from './request-client';
import type { MakeErrorMessageFn, ResponseInterceptorConfig } from './types';
import { $t } from '@vben/locales';
import { isFunction } from '@vben/utils';
import axios from 'axios';
export const defaultResponseInterceptor = ({
codeField = 'code',
dataField = 'data',
successCode = 0,
}: {
/** 响应数据中代表访问结果的字段名 */
codeField: string;
/** 响应数据中装载实际数据的字段名,或者提供一个函数从响应数据中解析需要返回的数据 */
dataField: ((response: any) => any) | string;
/** 当codeField所指定的字段值与successCode相同时代表接口访问成功。如果提供一个函数则返回true代表接口访问成功 */
successCode: ((code: any) => boolean) | number | string;
}): ResponseInterceptorConfig => {
return {
fulfilled: (response) => {
const { config, data: responseData, status } = response;
if (config.responseReturn === 'raw') {
return response;
}
const code = responseData[codeField];
if (
status >= 200 && status < 400 && isFunction(successCode)
? successCode(code)
: code === successCode
) {
if (config.responseReturn === 'body') {
return responseData;
} else {
return isFunction(dataField)
? dataField(responseData)
: responseData[dataField];
}
}
throw Object.assign({}, response, { response });
},
};
};
export const authenticateResponseInterceptor = ({
client,
doReAuthenticate,