fetch+typescript+拦截器 封装
时间: 2023-08-10 07:04:31 浏览: 236
下面是一个使用Typescript对fetch进行封装,并添加了拦截器的例子:
```typescript
interface ApiOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS';
headers?: HeadersInit;
body?: BodyInit;
credentials?: RequestCredentials;
mode?: RequestMode;
cache?: RequestCache;
}
interface ApiResponse<T = any> {
code: number;
message: string;
data: T;
}
interface Interceptor {
request?: (options: ApiOptions) => ApiOptions | Promise<ApiOptions>;
response?: <T>(response: ApiResponse<T>) => ApiResponse<T> | Promise<ApiResponse<T>>;
}
class FetchApi {
private baseUrl: string;
private interceptors: Interceptor;
constructor(baseUrl: string, interceptors?: Interceptor) {
this.baseUrl = baseUrl;
this.interceptors = interceptors || {};
}
public async get<T = any>(url: string, options?: ApiOptions): Promise<ApiResponse<T>> {
return await this.request<T>(url, { ...options, method: 'GET' });
}
public async post<T = any>(url: string, options?: ApiOptions): Promise<ApiResponse<T>> {
return await this.request<T>(url, { ...options, method: 'POST' });
}
public async put<T = any>(url: string, options?: ApiOptions): Promise<ApiResponse<T>> {
return await this.request<T>(url, { ...options, method: 'PUT' });
}
public async delete<T = any>(url: string, options?: ApiOptions): Promise<ApiResponse<T>> {
return await this.request<T>(url, { ...options, method: 'DELETE' });
}
private async request<T>(url: string, options: ApiOptions): Promise<ApiResponse<T>> {
const requestOptions = await this.interceptRequest(options);
const requestUrl = this.baseUrl + url;
const response = await fetch(requestUrl, requestOptions);
const responseData = await response.json();
const apiResponse = { code: response.status, message: responseData.message, data: responseData.data };
return await this.interceptResponse(apiResponse);
}
private async interceptRequest(options: ApiOptions): Promise<ApiOptions> {
if (this.interceptors.request) {
const interceptedOptions = await this.interceptors.request(options);
return interceptedOptions || options;
}
return options;
}
private async interceptResponse<T>(response: ApiResponse<T>): Promise<ApiResponse<T>> {
if (this.interceptors.response) {
const interceptedResponse = await this.interceptors.response(response);
return interceptedResponse || response;
}
return response;
}
}
```
在这个例子中,我们创建了一个FetchApi类,它具有get、post、put、delete四个方法,用于发送对应的请求。在构造函数中,我们传入了baseUrl和interceptors两个参数,interceptors表示拦截器对象,它包含request和response两个方法,用于在请求和响应过程中进行拦截。
在get、post、put、delete四个方法中,我们调用了request方法,并传入了对应的请求方法。request方法内部首先调用interceptRequest方法,用于拦截请求。然后使用fetch函数发送请求,并解析响应体。最后调用interceptResponse方法,用于拦截响应,并解析响应体。
在interceptRequest和interceptResponse方法中,我们判断了拦截器对象是否存在,并分别调用了request和response方法,用于进行拦截。如果拦截器对象未定义对应的方法,则直接返回原始参数。
使用方法如下:
```typescript
const api = new FetchApi('https://example.com', {
request: (options) => {
options.headers = { 'Authorization': 'Bearer token' };
return options;
},
response: (response) => {
if (response.code === 401) {
// 处理未授权的情况
}
return response;
}
});
api.get('/user').then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
```
在这个例子中,我们首先创建了一个FetchApi对象,传入了baseUrl和interceptors参数。在interceptors参数中,我们定义了request和response方法,用于在请求和响应过程中进行拦截。
然后我们使用get方法发送了一个请求,并在then方法中处理响应。如果发生错误,我们则在catch方法中进行处理。
阅读全文