* This file is part of the MindStudio project.
* Copyright (c) 2026 Huawei Technologies Co.,Ltd.
*
* MindStudio is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*/
import axios, { AxiosResponse, AxiosError } from 'axios';
interface RequestOptions {
url: string;
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
data?: any;
params?: any;
headers?: Record<string, string>;
timeout?: number;
}
interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: string;
}
export default async function request<T = any>(options: RequestOptions): Promise<ApiResponse<T>> {
const { url, method = 'GET', data = null, params = null, headers = {}, timeout = 60000 * 3 } = options;
try {
const controller = new AbortController();
const signal = controller.signal;
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response: AxiosResponse<T> = await axios({
url,
method,
data,
params,
headers: {
'Content-Type': 'application/json',
...headers,
},
maxBodyLength: Infinity,
signal,
});
clearTimeout(timeoutId);
if (response.status >= 200 && response.status < 300) {
return response.data as ApiResponse<T>;
} else {
return {
success: false,
error: `HTTP Error: ${response.status} - ${response.statusText}`,
};
}
} catch (error) {
if (axios.isAxiosError(error)) {
const axiosError = error as AxiosError;
if (axiosError.code === 'ECONNABORTED') {
return {
success: false,
error: '请求超时,请稍后重试。',
};
} else if (axiosError.response) {
const { status, statusText } = axiosError.response;
return {
success: false,
error: `HTTP Error: ${status} - ${statusText}`,
};
} else if (axiosError.request) {
return {
success: false,
error: '网络错误,未收到服务器响应。',
};
} else {
return {
success: false,
error: axiosError.message || '未知错误',
};
}
} else {
return {
success: false,
error: (error as Error).message || '未知错误',
};
}
}
}