ai-bot/app/_lib/request.ts

40 lines
891 B
TypeScript

/**
* 发送请求
* @param method
* @param url
* @param requestConfig
*/
export async function mRequest<T>(
method: 'GET' | 'POST' | 'DELETE' | 'PUT',
url: string,
data?: any,
responseType: 'json' | 'text' | 'blob' = 'json'
): Promise<T> {
const options: RequestInit = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
if (data) {
options.body = JSON.stringify(data);
}
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
if (responseType === 'json') {
return response.json() as Promise<T>;
} else if (responseType === 'text') {
return response.text() as Promise<T>;
} else if (responseType === 'blob') {
return response.blob() as Promise<T>;
} else {
throw new Error('Invalid response type specified');
}
}