1.1.7 • Published 10 months ago
@deot/http-core v1.1.7
@deot/http-core
可适配任何端的网络控制,具体的请求实现provider
控制
在Request/MDN基础上新增api
可全局注册或单次注册
provider
: 适配任何端的网络控制localData
: 本地mocktimeout
: 超时控制maxTries
: 最大尝试次数interval
: maxTries > 1时,间隔时间shared
: 共享请求(多个相同发起,等待同一个请求)onStart
: 发起回调onFinish
: 结束回调onRequest
: 请求拦截onResponse
: 响应拦截[custom]
: 自行定义的api, 可以在on*
的回调中做特殊处理
import { HTTPController, HTTPRequest, HTTPResponse } from '@deot/http-core';
const baseURL = 'https://xxx.com';
const apis = {
A_GET: '/api.json'
};
const Network = new HTTPController({
provider: (request: HTTPRequest) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(new HTTPResponse({ body: request.body }));
}, 300);
});
},
onRequest(leaf) {
const request = new HTTPRequest(leaf.request);
if (request.url && !/[a-zA-z]+:\/\/[^\s]*/.test(request.url)) {
const [key, query] = request.url.split('?'); // 避免before带上?token=*之类
request.url = `${apis[key] ? `${baseURL}${apis[key]}` : ''}${query ? `?${query}` : ''}`;
}
return request;
}
});
await Network.http(`A_GET`);
await Network.http(`https://xxx.com/api.json`);
await Network.http({
url: `https://xxx.com/api.json`
});
await Network.http({
url: `A_GET`,
body: {}
});
// cancel 1
const leaf = Network.http(`A_GET`);
await leaf.cancel();
// cancel 2
const shell = Network.custom(`A_GET`);
shell.send();
await shell.cancel();
扩展
on*
执行顺序
type HTTPHook<T = any> = (leaf: HTTPShellLeaf) => T | {
enforce: 'pre' | 'post' | null;
handler: (leaf: HTTPShellLeaf) => T;
};
- 带有
enforce: 'pre'
的用户钩子 - 带有
enforce: 'pre'
的全局钩子 - 没有
enforce
的用户钩子 - 没有
enforce
的全局钩子 - 带有
enforce: 'post'
的用户钩子 - 带有
enforce: 'post'
的全局钩子