feat(utils): deep fields in the response can be specified in the backendConfig

This commit is contained in:
ljk 2023-02-28 17:32:57 +08:00
parent 506ffb8adf
commit 69092a4529
3 changed files with 19 additions and 6 deletions

View File

@ -7,7 +7,8 @@ import {
handleBackendError,
handleResponseError,
handleServiceResult,
transformRequestData
transformRequestData,
getDeepResponseWithKey
} from '@/utils';
import { handleRefreshToken } from './helpers';
@ -64,13 +65,16 @@ export default class CustomAxiosInstance {
if (status === 200 || status < 300 || status === 304) {
const backend = response.data;
const { codeKey, dataKey, successCode } = this.backendConfig;
const code = getDeepResponseWithKey(backend, codeKey);
// 请求成功
if (backend[codeKey] === successCode) {
return handleServiceResult(null, backend[dataKey]);
if (code === successCode) {
const data = getDeepResponseWithKey(backend, dataKey);
return handleServiceResult(null, data);
}
// token失效, 刷新token
if (REFRESH_TOKEN_CODE.includes(backend[codeKey])) {
if (REFRESH_TOKEN_CODE.includes(code)) {
const config = await handleRefreshToken(response.config);
if (config) {
return this.instance.request(config);

View File

@ -8,6 +8,7 @@ import {
REQUEST_TIMEOUT_CODE,
REQUEST_TIMEOUT_MSG
} from '@/config';
import { getDeepResponseWithKey } from '@/utils';
import { exeStrategyActions } from '../common';
import { showErrorMsg } from './msg';
@ -91,8 +92,8 @@ export function handleBackendError(backendResult: Record<string, any>, config: S
const { codeKey, msgKey } = config;
const error: Service.RequestError = {
type: 'backend',
code: backendResult[codeKey],
msg: backendResult[msgKey]
code: getDeepResponseWithKey(backendResult, codeKey),
msg: getDeepResponseWithKey(backendResult, msgKey)
};
showErrorMsg(error);

View File

@ -59,3 +59,11 @@ async function transformFile(formData: FormData, key: string, file: File[] | Fil
formData.append(key, file);
}
}
export function getDeepResponseWithKey(res: any, key: string) {
let result = res;
key.split('.').forEach(item => {
result = result[item];
});
return result;
}