import qs from 'qs'; import { message } from 'antd'; import { ApiMaps } from '@/constants/apis'; import { generateId } from '.'; import { redirectToLogin } from './user'; export interface RequestOptions extends Omit { params?: Record; query?: Record; body?: FormData | Record | string; hideError?: boolean; } interface ResponseData { success: boolean; data?: any; message?: string; errorCode?: number; } function checkStatus(response: Response) { switch (response.status) { case 418: { redirectToLogin(); return Promise.reject(new Error('用户未登录')); } case 200: default: { return response.json(); } } } function handleSuccess(response: ResponseData) { if (response?.success) { return response.data || response.success; } if (response.errorCode) { return response; } return Promise.reject(new Error(response.message)); } export async function request( url: T, options?: RequestOptions, ): Promise { let [method, path] = url.split(' '); if (!method) { path = method; method = 'GET'; } const { query = {}, params = {}, headers = {}, hideError, } = (options || {}) as { query?: any; params: any; headers: any; hideError: boolean }; let { body } = (options || {}) as { body: any }; Object.keys(params).forEach((key) => { path = path.replace(`{${key}}`, params[key]); }); if (qs.stringify(query)) { path += `${path.includes('?') ? '&' : '?'}${qs.stringify(query)}`; } if (!(body instanceof FormData) && typeof body !== 'string') { body = JSON.stringify(body); } const defaultHeaders = { 'x-request-id': generateId(), }; function handleError(error: Error) { if (error?.name !== 'AbortError') { if (!hideError) { message.error(error.message); } return Promise.reject(error); } return Promise.resolve(''); } return fetch(path, { ...options, method, body, headers: { ...defaultHeaders, ...(body instanceof FormData ? {} : { 'content-type': 'application/json' }), ...headers, }, }) .then(checkStatus) .then(handleSuccess) .catch(handleError); } export default {};