| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- // utils/request.ts
- interface RequestOptions extends RequestInit {
- params?: Record<string, any>;
- timeout?: number;
- }
- class Request {
- private baseUrl: string;
- private timeout: number;
- constructor(baseUrl: string = '', timeout: number = 10000) {
- this.baseUrl = baseUrl;
- this.timeout = timeout;
- }
- private getUrl(url: string): string {
- if (url.startsWith('http')) return url;
- return this.baseUrl + url;
- }
- private async handleResponse(response: Response) {
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- return response.json();
- }
- private async withTimeout<T>(promise: Promise<T>, timeout: number): Promise<T> {
- return Promise.race([
- promise,
- new Promise<never>((_, reject) =>
- setTimeout(() => reject(new Error('Request timeout')), timeout)
- )
- ]);
- }
- async request<T = any>(url: string, options: RequestOptions = {}): Promise<T> {
- const {
- method = 'GET',
- headers = {},
- body,
- params,
- timeout = this.timeout,
- ...restOptions
- } = options;
- let fullUrl = this.getUrl(url);
-
- // 处理查询参数
- if (params) {
- const searchParams = new URLSearchParams(params);
- fullUrl += (fullUrl.includes('?') ? '&' : '?') + searchParams.toString();
- }
- const config: RequestInit = {
- method,
- headers: {
- 'Content-Type': 'application/json',
- ...headers
- },
- ...restOptions
- };
- if (body) {
- config.body = typeof body === 'string' ? body : JSON.stringify(body);
- }
- try {
- const response = await this.withTimeout(fetch(fullUrl, config), timeout);
- return await this.handleResponse(response);
- } catch (error) {
- throw error;
- }
- }
- get<T = any>(url: string, options?: Omit<RequestOptions, 'method'>) {
- return this.request<T>(url, { ...options, method: 'GET' });
- }
- post<T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'method' | 'body'>) {
- return this.request<T>(url, {
- ...options,
- method: 'POST',
- body: data
- });
- }
- put<T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'method' | 'body'>) {
- return this.request<T>(url, {
- ...options,
- method: 'PUT',
- body: data
- });
- }
- delete<T = any>(url: string, options?: Omit<RequestOptions, 'method'>) {
- return this.request<T>(url, { ...options, method: 'DELETE' });
- }
- }
- // 创建默认实例
- const request = new Request('https://usersource.landwu.com/api');
- export default request;
|