ist-fetch
v1.0.9
Published
@ist - fetch
Readme
快熟下载
npm install ist-fetch --save快速使用
推荐用法
- 单例用法 创建公共拦截 demo
import {FetchCommon} from 'ist-fetch';
import type {FetchRequestOptions} from 'ist-fetch';
export class FetchIstabs extends FetchCommon {
private static _instance: FetchIstabs;
private constructor(host: string) {
super(host);
}
// 重写响应拦截 一般不建议重写 自己处理可能不全
_responseInterceptor<T>(r: Response, options: FetchRequestOptions){
return r.json() as Promise<T>;
}
async createFetch<T, P = unknown>(url: string, options: FetchRequestOptions): Promise<T> {
const {method = 'GET', headers = {}} = options;
const client_kx = await getSessionAsync<CryptoKxInterface>(CACHE_SESSION.CLIENT_SPUB_KEY);
const _headers = {
'Content-Type': method.toUpperCase() === 'GET' ? 'application/x-www-form-urlencoded' : 'application/json',
...headers,
};
return await this.fetchCommon(url, {...options, headers: _headers});
}
public static _getInstance(host: string = 'api/'): FetchIstabs {
if (!FetchIstabs._instance) {
FetchIstabs._instance = new FetchIstabs(host);
}
return FetchIstabs._instance;
}
}- 快速使用已创建的实例
const fetchIstabs = FetchIstabs._getInstance();
const fetchDemo = async () => {
return fetchIstabs.createFetch('/api/test', {
method: 'GET',
params: {
a: 1,
b: 2
},
// 可选参数
interceptor: {
// 请求拦截
request: (config) => {
return {
headers: {
'x-ddd': '..s.xxx'
}
}
},
// 响应拦截
response: (response: Response) => {
return response.json();
}
}
})
}