Match-id-070ea3249956cd5688ed8a3839c7ea002b9ed9ab
This commit is contained in:
parent
c558290682
commit
a56f236320
|
@ -53,21 +53,21 @@
|
||||||
<script src="../../dist/bundle.js"></script>
|
<script src="../../dist/bundle.js"></script>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// 创建使用拦截器的 HR 实例
|
// 创建使用拦截器的 IR 实例
|
||||||
const hrInstance = horizonRequest.create();
|
const irInstance = inulaRequest.create();
|
||||||
|
|
||||||
// 添加请求拦截器
|
// 添加请求拦截器
|
||||||
hrInstance.interceptors.request.use(function(config) {
|
irInstance.interceptors.request.use(function(config) {
|
||||||
// 为请求添加自定义请求头
|
// 为请求添加自定义请求头
|
||||||
config.headers['HR-Custom-Header'] = 'CustomHeaderValue';
|
config.headers['IR-Custom-Header'] = 'CustomHeaderValue';
|
||||||
document.getElementById('requestInterceptorFeedback').textContent = '请求已拦截,并添加请求头HR-Custom-Header';
|
document.getElementById('requestInterceptorFeedback').textContent = '请求已拦截,并添加请求头IR-Custom-Header';
|
||||||
return config;
|
return config;
|
||||||
}, function(error) {
|
}, function(error) {
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 添加响应拦截器
|
// 添加响应拦截器
|
||||||
hrInstance.interceptors.response.use(function(response) {
|
irInstance.interceptors.response.use(function(response) {
|
||||||
// 更新响应状态码
|
// 更新响应状态码
|
||||||
response.status = 404;
|
response.status = 404;
|
||||||
document.getElementById('responseStatusWithInterceptor').textContent = String(response.status);
|
document.getElementById('responseStatusWithInterceptor').textContent = String(response.status);
|
||||||
|
@ -79,7 +79,7 @@
|
||||||
|
|
||||||
// 使用拦截器的请求
|
// 使用拦截器的请求
|
||||||
document.getElementById('sendRequestWithInterceptor').addEventListener('click', function () {
|
document.getElementById('sendRequestWithInterceptor').addEventListener('click', function () {
|
||||||
hrInstance.get('http://localhost:3001/')
|
irInstance.get('http://localhost:3001/')
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
document.getElementById('responseDataWithInterceptor').textContent = JSON.stringify(response.data, null, 2);
|
document.getElementById('responseDataWithInterceptor').textContent = JSON.stringify(response.data, null, 2);
|
||||||
}).catch(function (error) {
|
}).catch(function (error) {
|
||||||
|
@ -101,4 +101,4 @@
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
@ -85,8 +85,8 @@
|
||||||
const resetButton = document.getElementById('resetButton');
|
const resetButton = document.getElementById('resetButton');
|
||||||
|
|
||||||
queryButton.addEventListener('click', function () {
|
queryButton.addEventListener('click', function () {
|
||||||
const hrInstance = horizonRequest.create();
|
const inulaRequest = inulaRequest.create();
|
||||||
hrInstance.request('http://localhost:3001/', {method: 'GET', data: {}})
|
inulaRequest.request('http://localhost:3001/', {method: 'GET', data: {}})
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
requestResult.innerHTML = JSON.stringify(response.data, null, 2);
|
requestResult.innerHTML = JSON.stringify(response.data, null, 2);
|
||||||
})
|
})
|
||||||
|
@ -94,7 +94,7 @@
|
||||||
requestResult.innerHTML = JSON.stringify(error, null, 2);
|
requestResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
})
|
})
|
||||||
|
|
||||||
horizonRequest.default.get('http://localhost:3001/')
|
inulaRequest.default.get('http://localhost:3001/')
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
getResult.innerHTML = JSON.stringify(response.data, null, 2);
|
getResult.innerHTML = JSON.stringify(response.data, null, 2);
|
||||||
})
|
})
|
||||||
|
@ -102,7 +102,7 @@
|
||||||
getResult.innerHTML = JSON.stringify(error, null, 2);
|
getResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest('http://localhost:3001/', {method:'POST', name: 'Alice'})
|
inulaRequest('http://localhost:3001/', {method:'POST', name: 'Alice'})
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
postResult.innerHTML = JSON.stringify(response.data, null, 2);
|
postResult.innerHTML = JSON.stringify(response.data, null, 2);
|
||||||
})
|
})
|
||||||
|
@ -110,7 +110,7 @@
|
||||||
postResult.innerHTML = JSON.stringify(error, null, 2);
|
postResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest.put('http://localhost:3001/users', {id: 1, name: 'Bob'})
|
inulaRequest.put('http://localhost:3001/users', {id: 1, name: 'Bob'})
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
putResult.innerHTML = JSON.stringify(response.data, null, 2);
|
putResult.innerHTML = JSON.stringify(response.data, null, 2);
|
||||||
})
|
})
|
||||||
|
@ -118,7 +118,7 @@
|
||||||
putResult.innerHTML = JSON.stringify(error, null, 2);
|
putResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest.delete('http://localhost:3001/users', {params: {id: 1}})
|
inulaRequest.delete('http://localhost:3001/users', {params: {id: 1}})
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
deleteResult.innerHTML = JSON.stringify(response.data, null, 2);
|
deleteResult.innerHTML = JSON.stringify(response.data, null, 2);
|
||||||
})
|
})
|
||||||
|
@ -126,7 +126,7 @@
|
||||||
deleteResult.innerHTML = JSON.stringify(error, null, 2);
|
deleteResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest.head('http://localhost:3001/')
|
inulaRequest.head('http://localhost:3001/')
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
headResult.innerHTML = 'Header: ' + JSON.stringify(response.headers['x-powered-by'], null, 2); // IE 浏览器不支持 HEAD 方式访问响应头
|
headResult.innerHTML = 'Header: ' + JSON.stringify(response.headers['x-powered-by'], null, 2); // IE 浏览器不支持 HEAD 方式访问响应头
|
||||||
})
|
})
|
||||||
|
@ -134,7 +134,7 @@
|
||||||
headResult.innerHTML = JSON.stringify(error, null, 2);
|
headResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest.options('http://localhost:3001/', {
|
inulaRequest.options('http://localhost:3001/', {
|
||||||
headers: {
|
headers: {
|
||||||
'Access-Control-Request-Method': 'POST'
|
'Access-Control-Request-Method': 'POST'
|
||||||
}
|
}
|
||||||
|
@ -146,7 +146,7 @@
|
||||||
optionsResult.innerHTML = JSON.stringify(error, null, 2);
|
optionsResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest.patch('http://localhost:3001/', {name: 'HR'})
|
inulaRequest.patch('http://localhost:3001/', {name: 'IR'})
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
patchResult.innerHTML = JSON.stringify(response.data, null, 2);
|
patchResult.innerHTML = JSON.stringify(response.data, null, 2);
|
||||||
})
|
})
|
||||||
|
@ -154,7 +154,7 @@
|
||||||
patchResult.innerHTML = JSON.stringify(error, null, 2);
|
patchResult.innerHTML = JSON.stringify(error, null, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
horizonRequest.get('http://localhost:3001/download', {
|
inulaRequest.get('http://localhost:3001/download', {
|
||||||
responseType: 'text',
|
responseType: 'text',
|
||||||
onDownloadProgress: function (progressEvent) {
|
onDownloadProgress: function (progressEvent) {
|
||||||
const loaded = progressEvent.loaded;
|
const loaded = progressEvent.loaded;
|
||||||
|
|
|
@ -13,7 +13,7 @@ app.use(bodyParser.urlencoded({ extended: true }));
|
||||||
const corsOptions = {
|
const corsOptions = {
|
||||||
origin: '*',
|
origin: '*',
|
||||||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
|
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
|
||||||
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'X-Requested-With,content-type', 'HR-Custom-Header'],
|
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'X-Requested-With,content-type', 'IR-Custom-Header'],
|
||||||
exposedHeaders: ['X-Powered-By'],
|
exposedHeaders: ['X-Powered-By'],
|
||||||
optionsSuccessStatus: 200, // 设置 OPTIONS 请求成功时的状态码为 200
|
optionsSuccessStatus: 200, // 设置 OPTIONS 请求成功时的状态码为 200
|
||||||
credentials: true
|
credentials: true
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import Horizon, { useState } from '@cloudsop/horizon';
|
import Horizon, { useState } from '@cloudsop/horizon';
|
||||||
import { useHR } from '../../index';
|
import { useIR } from '../../index';
|
||||||
|
|
||||||
const App = () => {
|
const App = () => {
|
||||||
|
|
||||||
|
@ -10,7 +10,7 @@ const App = () => {
|
||||||
enablePollingOptimization: true,
|
enablePollingOptimization: true,
|
||||||
limitation: {minInterval: 500, maxInterval: 4000}
|
limitation: {minInterval: 500, maxInterval: 4000}
|
||||||
};
|
};
|
||||||
const {data} = useHR('http://localhost:3001/', null, options);
|
const {data} = useIR('http://localhost:3001/', null, options);
|
||||||
|
|
||||||
const handleClick = () => {
|
const handleClick = () => {
|
||||||
setSend(true);
|
setSend(true);
|
||||||
|
@ -18,7 +18,7 @@ const App = () => {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<header>useHR Test</header>
|
<header>useIR Test</header>
|
||||||
<div className="container">
|
<div className="container">
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<h2 style={{whiteSpace: "pre-wrap"}}>{options ? `实时数据流已激活\n更新间隔:${options?.pollingInterval} ms`
|
<h2 style={{whiteSpace: "pre-wrap"}}>{options ? `实时数据流已激活\n更新间隔:${options?.pollingInterval} ms`
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<title>useHR Test</title>
|
<title>useIR Test</title>
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {
|
||||||
font-family: Arial, sans-serif;
|
font-family: Arial, sans-serif;
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import horizonRequest from './src/horizonRequest';
|
import inulaRequest from './src/inulaRequest';
|
||||||
import useHR from './src/core/useHR/useHR';
|
import useIR from './src/core/useIR/useIR';
|
||||||
|
|
||||||
const {
|
const {
|
||||||
create,
|
create,
|
||||||
|
@ -10,22 +10,22 @@ const {
|
||||||
['delete']: propToDelete,
|
['delete']: propToDelete,
|
||||||
head,
|
head,
|
||||||
options,
|
options,
|
||||||
HorizonRequest,
|
InulaRequest,
|
||||||
HrError,
|
IrError,
|
||||||
CanceledError,
|
CanceledError,
|
||||||
isCancel,
|
isCancel,
|
||||||
CancelToken,
|
CancelToken,
|
||||||
all,
|
all,
|
||||||
Cancel,
|
Cancel,
|
||||||
isHrError,
|
isIrError,
|
||||||
spread,
|
spread,
|
||||||
HrHeaders,
|
IrHeaders,
|
||||||
// 兼容axios
|
// 兼容axios
|
||||||
Axios,
|
Axios,
|
||||||
AxiosError,
|
AxiosError,
|
||||||
AxiosHeaders,
|
AxiosHeaders,
|
||||||
isAxiosError,
|
isAxiosError,
|
||||||
} = horizonRequest;
|
} = inulaRequest;
|
||||||
|
|
||||||
export {
|
export {
|
||||||
create,
|
create,
|
||||||
|
@ -36,17 +36,17 @@ export {
|
||||||
propToDelete as delete,
|
propToDelete as delete,
|
||||||
head,
|
head,
|
||||||
options,
|
options,
|
||||||
HorizonRequest,
|
InulaRequest,
|
||||||
HrError,
|
IrError,
|
||||||
CanceledError,
|
CanceledError,
|
||||||
isCancel,
|
isCancel,
|
||||||
CancelToken,
|
CancelToken,
|
||||||
all,
|
all,
|
||||||
Cancel,
|
Cancel,
|
||||||
isHrError,
|
isIrError,
|
||||||
spread,
|
spread,
|
||||||
HrHeaders,
|
IrHeaders,
|
||||||
useHR,
|
useIR,
|
||||||
// 兼容axios
|
// 兼容axios
|
||||||
Axios,
|
Axios,
|
||||||
AxiosError,
|
AxiosError,
|
||||||
|
@ -54,4 +54,4 @@ export {
|
||||||
isAxiosError,
|
isAxiosError,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default horizonRequest;
|
export default inulaRequest;
|
||||||
|
|
|
@ -19,7 +19,7 @@
|
||||||
"url": "ssh://git@szv-open.codehub.huawei.com:2222/innersource/fenghuang/horizon/horizon-ecosystem.git"
|
"url": "ssh://git@szv-open.codehub.huawei.com:2222/innersource/fenghuang/horizon/horizon-ecosystem.git"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"horizon-request"
|
"inula-request"
|
||||||
],
|
],
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
|
@ -61,7 +61,7 @@
|
||||||
"webpack-dev-server": "^4.13.3"
|
"webpack-dev-server": "^4.13.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cloudsop/horizon": "0.0.50"
|
"inulajs": "0.0.11"
|
||||||
},
|
},
|
||||||
"exclude": [
|
"exclude": [
|
||||||
"node_modules"
|
"node_modules"
|
||||||
|
|
|
@ -3,11 +3,11 @@ import resolve from 'rollup-plugin-node-resolve'; // 解析第三方模块,并
|
||||||
import commonjs from 'rollup-plugin-commonjs'; // 将 CommonJS 模块转换为 ES6 模块
|
import commonjs from 'rollup-plugin-commonjs'; // 将 CommonJS 模块转换为 ES6 模块
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
input: './src/horizonRequest.ts',
|
input: './src/inulaRequest.ts',
|
||||||
output: {
|
output: {
|
||||||
file: 'dist/bundle.js',
|
file: 'dist/bundle.js',
|
||||||
format: 'umd',
|
format: 'umd',
|
||||||
name: 'horizonRequest',
|
name: 'inulaRequest',
|
||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
typescript({
|
typescript({
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
import HrError from '../core/HrError';
|
import IrError from '../core/IrError';
|
||||||
import { HrRequestConfig } from '../types/interfaces';
|
import { IrRequestConfig } from '../types/interfaces';
|
||||||
|
|
||||||
class CancelError extends HrError {
|
class CancelError extends IrError {
|
||||||
constructor(message: string | undefined, config: HrRequestConfig, request?: any) {
|
constructor(message: string | undefined, config: IrRequestConfig, request?: any) {
|
||||||
const errorMessage = message || 'canceled';
|
const errorMessage = message || 'canceled';
|
||||||
super(errorMessage, (HrError as any).ERR_CANCELED, config, request);
|
super(errorMessage, (IrError as any).ERR_CANCELED, config, request);
|
||||||
this.name = 'CanceledError';
|
this.name = 'CanceledError';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,102 +0,0 @@
|
||||||
import utils from '../utils/commonUtils/utils';
|
|
||||||
import { HrErrorInterface, HrInstance, HrRequestConfig, HrResponse } from '../types/interfaces';
|
|
||||||
|
|
||||||
class HrError extends Error implements HrErrorInterface {
|
|
||||||
code?: string;
|
|
||||||
config?: HrRequestConfig;
|
|
||||||
request?: HrInstance;
|
|
||||||
response?: HrResponse;
|
|
||||||
|
|
||||||
constructor(message: string, code?: string, config?: HrRequestConfig, request?: any, response?: HrResponse) {
|
|
||||||
super(message);
|
|
||||||
|
|
||||||
this.message = message;
|
|
||||||
this.name = 'HrError';
|
|
||||||
this.code = code;
|
|
||||||
this.config = config;
|
|
||||||
this.request = request;
|
|
||||||
this.response = response;
|
|
||||||
}
|
|
||||||
|
|
||||||
toJSON() {
|
|
||||||
return {
|
|
||||||
message: this.message,
|
|
||||||
name: this.name,
|
|
||||||
config: utils.toJSONSafe(this.config as Record<string, any>),
|
|
||||||
code: this.code,
|
|
||||||
status: this.response && this.response.status ? this.response.status : null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 从现有的 Error 对象创建一个新的 HrError 对象
|
|
||||||
static from(
|
|
||||||
error: Error,
|
|
||||||
code: string,
|
|
||||||
config: HrRequestConfig,
|
|
||||||
request: any,
|
|
||||||
response: HrResponse,
|
|
||||||
customProps?: Record<string, any>
|
|
||||||
): HrError {
|
|
||||||
// 由传入的 Error 对象属性初始化 HrError 实例化对象
|
|
||||||
const hrError = new HrError(error.message, code, config, request, response);
|
|
||||||
|
|
||||||
// 将现有的 Error 对象的属性复制到新创建的对象中
|
|
||||||
utils.flattenObject(
|
|
||||||
error,
|
|
||||||
hrError,
|
|
||||||
obj => obj !== Error.prototype,
|
|
||||||
prop => prop !== 'isHrError'
|
|
||||||
);
|
|
||||||
|
|
||||||
// 设置基本错误类型属性
|
|
||||||
hrError.name = error.name;
|
|
||||||
|
|
||||||
if (customProps) {
|
|
||||||
Object.assign(hrError, customProps);
|
|
||||||
}
|
|
||||||
|
|
||||||
return hrError;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 在 HrError 类的原型链中添加 Error 类的原型,使 HrError 成为 Error 的子类
|
|
||||||
Object.setPrototypeOf(HrError.prototype, Error.prototype);
|
|
||||||
Object.defineProperties(HrError.prototype, {
|
|
||||||
toJSON: {
|
|
||||||
value: HrError.prototype.toJSON,
|
|
||||||
},
|
|
||||||
isHrError: {
|
|
||||||
value: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const errorTypes = [
|
|
||||||
'ERR_BAD_OPTION_VALUE',
|
|
||||||
'ERR_BAD_OPTION',
|
|
||||||
'ECONNABORTED',
|
|
||||||
'ETIMEDOUT',
|
|
||||||
'ERR_NETWORK',
|
|
||||||
'ERR_FR_TOO_MANY_REDIRECTS',
|
|
||||||
'ERR_DEPRECATED',
|
|
||||||
'ERR_BAD_RESPONSE',
|
|
||||||
'ERR_BAD_REQUEST',
|
|
||||||
'ERR_CANCELED',
|
|
||||||
'ERR_NOT_SUPPORT',
|
|
||||||
'ERR_INVALID_URL',
|
|
||||||
];
|
|
||||||
|
|
||||||
const descriptors: PropertyDescriptorMap = errorTypes.reduce((acc, code) => {
|
|
||||||
acc[code] = { value: code };
|
|
||||||
return acc;
|
|
||||||
}, {});
|
|
||||||
|
|
||||||
// 将 descriptors 对象中定义的属性添加到 HrError 类上
|
|
||||||
Object.defineProperties(HrError, descriptors);
|
|
||||||
|
|
||||||
// 在 HrError 类的原型上定义了一个名为 isHrError 的属性,用于判断错误对象是否为 HrError
|
|
||||||
Object.defineProperty(HrError.prototype, 'isHrError', { value: true });
|
|
||||||
|
|
||||||
// 判断输入值是否为 HrError
|
|
||||||
export const isHrError = (value: any) => !!value.isHrError;
|
|
||||||
|
|
||||||
export default HrError;
|
|
|
@ -1,5 +1,5 @@
|
||||||
import getMergedConfig from '../utils/configUtils/getMergedConfig';
|
import getMergedConfig from '../utils/configUtils/getMergedConfig';
|
||||||
import HrHeaders from './HrHeaders';
|
import IrHeaders from './IrHeaders';
|
||||||
import InterceptorManager from '../interceptor/InterceptorManager';
|
import InterceptorManager from '../interceptor/InterceptorManager';
|
||||||
import processRequest from '../request/processRequest';
|
import processRequest from '../request/processRequest';
|
||||||
import getRequestInterceptorsInfo from '../interceptor/getRequestInterceptorsInfo';
|
import getRequestInterceptorsInfo from '../interceptor/getRequestInterceptorsInfo';
|
||||||
|
@ -9,19 +9,19 @@ import handleSyncInterceptor from '../interceptor/handleSyncInterceptor';
|
||||||
import defaultConfig from '../config/defaultConfig';
|
import defaultConfig from '../config/defaultConfig';
|
||||||
import { Method } from '../types/types';
|
import { Method } from '../types/types';
|
||||||
import {
|
import {
|
||||||
HrRequestConfig,
|
IrRequestConfig,
|
||||||
HrResponse,
|
IrResponse,
|
||||||
HrInterface,
|
IrInterface,
|
||||||
HrInstance,
|
IrInstance,
|
||||||
Interceptors,
|
Interceptors,
|
||||||
} from '../types/interfaces';
|
} from '../types/interfaces';
|
||||||
|
|
||||||
class HorizonRequest implements HrInterface {
|
class InulaRequest implements IrInterface {
|
||||||
defaultConfig: HrRequestConfig;
|
defaultConfig: IrRequestConfig;
|
||||||
interceptors: Interceptors;
|
interceptors: Interceptors;
|
||||||
processRequest: (config: HrRequestConfig) => Promise<any>;
|
processRequest: (config: IrRequestConfig) => Promise<any>;
|
||||||
|
|
||||||
constructor(config: HrRequestConfig) {
|
constructor(config: IrRequestConfig) {
|
||||||
this.defaultConfig = config;
|
this.defaultConfig = config;
|
||||||
// 初始化拦截器
|
// 初始化拦截器
|
||||||
this.interceptors = {
|
this.interceptors = {
|
||||||
|
@ -31,7 +31,7 @@ class HorizonRequest implements HrInterface {
|
||||||
this.processRequest = processRequest;
|
this.processRequest = processRequest;
|
||||||
}
|
}
|
||||||
|
|
||||||
request<T = unknown>(requestParam: string | Record<string, any>, config?: HrRequestConfig): Promise<HrResponse<T>> {
|
request<T = unknown>(requestParam: string | Record<string, any>, config?: IrRequestConfig): Promise<IrResponse<T>> {
|
||||||
// 1. 解析参数
|
// 1. 解析参数
|
||||||
const mergedConfig = this.preprocessing(requestParam, config);
|
const mergedConfig = this.preprocessing(requestParam, config);
|
||||||
|
|
||||||
|
@ -63,7 +63,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private preprocessing(requestParam: string | Record<string, any>, config?: HrRequestConfig) {
|
private preprocessing(requestParam: string | Record<string, any>, config?: IrRequestConfig) {
|
||||||
let configOperation: Record<string, any> = {};
|
let configOperation: Record<string, any> = {};
|
||||||
|
|
||||||
if (typeof requestParam === 'object') {
|
if (typeof requestParam === 'object') {
|
||||||
|
@ -73,7 +73,7 @@ class HorizonRequest implements HrInterface {
|
||||||
configOperation = { ...configOperation, ...config };
|
configOperation = { ...configOperation, ...config };
|
||||||
}
|
}
|
||||||
|
|
||||||
const mergedConfig: HrRequestConfig = getMergedConfig(this.defaultConfig, configOperation);
|
const mergedConfig: IrRequestConfig = getMergedConfig(this.defaultConfig, configOperation);
|
||||||
mergedConfig.method = (mergedConfig.method || this.defaultConfig.method || 'GET').toUpperCase() as Method;
|
mergedConfig.method = (mergedConfig.method || this.defaultConfig.method || 'GET').toUpperCase() as Method;
|
||||||
|
|
||||||
const { headers } = mergedConfig;
|
const { headers } = mergedConfig;
|
||||||
|
@ -91,13 +91,13 @@ class HorizonRequest implements HrInterface {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
mergedConfig.headers = HrHeaders.concat(contextHeaders, headers);
|
mergedConfig.headers = IrHeaders.concat(contextHeaders, headers);
|
||||||
}
|
}
|
||||||
|
|
||||||
return mergedConfig;
|
return mergedConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
get<T = unknown>(url: string, config: HrRequestConfig) {
|
get<T = unknown>(url: string, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'get',
|
method: 'get',
|
||||||
|
@ -107,7 +107,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
delete<T = unknown>(url: string, config: HrRequestConfig) {
|
delete<T = unknown>(url: string, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
|
@ -117,7 +117,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
head<T = unknown>(url: string, config: HrRequestConfig) {
|
head<T = unknown>(url: string, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'head',
|
method: 'head',
|
||||||
|
@ -127,7 +127,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
options<T = unknown>(url: string, config: HrRequestConfig) {
|
options<T = unknown>(url: string, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'options',
|
method: 'options',
|
||||||
|
@ -137,7 +137,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
post<T = unknown>(url: string, data: any, config: HrRequestConfig) {
|
post<T = unknown>(url: string, data: any, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'post',
|
method: 'post',
|
||||||
|
@ -147,7 +147,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
postForm<T = unknown>(url: string, data: any, config: HrRequestConfig) {
|
postForm<T = unknown>(url: string, data: any, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'post',
|
method: 'post',
|
||||||
|
@ -158,7 +158,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
put<T = unknown>(url: string, data: any, config: HrRequestConfig) {
|
put<T = unknown>(url: string, data: any, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'put',
|
method: 'put',
|
||||||
|
@ -168,7 +168,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
putForm<T = unknown>(url: string, data: any, config: HrRequestConfig) {
|
putForm<T = unknown>(url: string, data: any, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'put',
|
method: 'put',
|
||||||
|
@ -179,7 +179,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
patch<T = unknown>(url: string, data: any, config: HrRequestConfig) {
|
patch<T = unknown>(url: string, data: any, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'patch',
|
method: 'patch',
|
||||||
|
@ -189,7 +189,7 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
patchForm<T = unknown>(url: string, data: any, config: HrRequestConfig) {
|
patchForm<T = unknown>(url: string, data: any, config: IrRequestConfig) {
|
||||||
return this.request<T>(
|
return this.request<T>(
|
||||||
getMergedConfig(config || {}, {
|
getMergedConfig(config || {}, {
|
||||||
method: 'patch',
|
method: 'patch',
|
||||||
|
@ -200,12 +200,12 @@ class HorizonRequest implements HrInterface {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建 Hr 实例
|
// 创建 Ir 实例
|
||||||
static create(instanceConfig?: HrRequestConfig): HrInstance {
|
static create(instanceConfig?: IrRequestConfig): IrInstance {
|
||||||
const config = getMergedConfig(defaultConfig, instanceConfig || {});
|
const config = getMergedConfig(defaultConfig, instanceConfig || {});
|
||||||
|
|
||||||
return new HorizonRequest(config) as unknown as HrInstance;
|
return new InulaRequest(config) as unknown as IrInstance;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default HorizonRequest;
|
export default InulaRequest;
|
|
@ -0,0 +1,102 @@
|
||||||
|
import utils from '../utils/commonUtils/utils';
|
||||||
|
import { IrErrorInterface, IrInstance, IrRequestConfig, IrResponse } from '../types/interfaces';
|
||||||
|
|
||||||
|
class IrError extends Error implements IrErrorInterface {
|
||||||
|
code?: string;
|
||||||
|
config?: IrRequestConfig;
|
||||||
|
request?: IrInstance;
|
||||||
|
response?: IrResponse;
|
||||||
|
|
||||||
|
constructor(message: string, code?: string, config?: IrRequestConfig, request?: any, response?: IrResponse) {
|
||||||
|
super(message);
|
||||||
|
|
||||||
|
this.message = message;
|
||||||
|
this.name = 'IrError';
|
||||||
|
this.code = code;
|
||||||
|
this.config = config;
|
||||||
|
this.request = request;
|
||||||
|
this.response = response;
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON() {
|
||||||
|
return {
|
||||||
|
message: this.message,
|
||||||
|
name: this.name,
|
||||||
|
config: utils.toJSONSafe(this.config as Record<string, any>),
|
||||||
|
code: this.code,
|
||||||
|
status: this.response && this.response.status ? this.response.status : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从现有的 Error 对象创建一个新的 IrError 对象
|
||||||
|
static from(
|
||||||
|
error: Error,
|
||||||
|
code: string,
|
||||||
|
config: IrRequestConfig,
|
||||||
|
request: any,
|
||||||
|
response: IrResponse,
|
||||||
|
customProps?: Record<string, any>
|
||||||
|
): IrError {
|
||||||
|
// 由传入的 Error 对象属性初始化 IrError 实例化对象
|
||||||
|
const irError = new IrError(error.message, code, config, request, response);
|
||||||
|
|
||||||
|
// 将现有的 Error 对象的属性复制到新创建的对象中
|
||||||
|
utils.flattenObject(
|
||||||
|
error,
|
||||||
|
irError,
|
||||||
|
obj => obj !== Error.prototype,
|
||||||
|
prop => prop !== 'isIrError'
|
||||||
|
);
|
||||||
|
|
||||||
|
// 设置基本错误类型属性
|
||||||
|
irError.name = error.name;
|
||||||
|
|
||||||
|
if (customProps) {
|
||||||
|
Object.assign(irError, customProps);
|
||||||
|
}
|
||||||
|
|
||||||
|
return irError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 在 IrError 类的原型链中添加 Error 类的原型,使 IrError 成为 Error 的子类
|
||||||
|
Object.setPrototypeOf(IrError.prototype, Error.prototype);
|
||||||
|
Object.defineProperties(IrError.prototype, {
|
||||||
|
toJSON: {
|
||||||
|
value: IrError.prototype.toJSON,
|
||||||
|
},
|
||||||
|
isIrError: {
|
||||||
|
value: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const errorTypes = [
|
||||||
|
'ERR_BAD_OPTION_VALUE',
|
||||||
|
'ERR_BAD_OPTION',
|
||||||
|
'ECONNABORTED',
|
||||||
|
'ETIMEDOUT',
|
||||||
|
'ERR_NETWORK',
|
||||||
|
'ERR_FR_TOO_MANY_REDIRECTS',
|
||||||
|
'ERR_DEPRECATED',
|
||||||
|
'ERR_BAD_RESPONSE',
|
||||||
|
'ERR_BAD_REQUEST',
|
||||||
|
'ERR_CANCELED',
|
||||||
|
'ERR_NOT_SUPPORT',
|
||||||
|
'ERR_INVALID_URL',
|
||||||
|
];
|
||||||
|
|
||||||
|
const descriptors: PropertyDescriptorMap = errorTypes.reduce((acc, code) => {
|
||||||
|
acc[code] = { value: code };
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
// 将 descriptors 对象中定义的属性添加到 IrError 类上
|
||||||
|
Object.defineProperties(IrError, descriptors);
|
||||||
|
|
||||||
|
// 在 IrError 类的原型上定义了一个名为 isIrError 的属性,用于判断错误对象是否为 IrError
|
||||||
|
Object.defineProperty(IrError.prototype, 'isIrError', { value: true });
|
||||||
|
|
||||||
|
// 判断输入值是否为 IrError
|
||||||
|
export const isIrError = (value: any) => !!value.isIrError;
|
||||||
|
|
||||||
|
export default IrError;
|
|
@ -5,12 +5,12 @@ import checkHeaderName from '../utils/headerUtils/checkHeaderName';
|
||||||
import processValueByParser from '../utils/headerUtils/processValueByParser';
|
import processValueByParser from '../utils/headerUtils/processValueByParser';
|
||||||
import deleteHeader from '../utils/headerUtils/deleteHeader';
|
import deleteHeader from '../utils/headerUtils/deleteHeader';
|
||||||
|
|
||||||
class HrHeaders {
|
class IrHeaders {
|
||||||
// 定义 HrHeaders 类索引签名
|
// 定义 IrHeaders 类索引签名
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
|
|
||||||
constructor(headers?: Record<string, string | string[]> | HrHeaders) {
|
constructor(headers?: Record<string, string | string[]> | IrHeaders) {
|
||||||
// 将默认响应头加入 HrHeaders
|
// 将默认响应头加入 IrHeaders
|
||||||
this.defineAccessor();
|
this.defineAccessor();
|
||||||
|
|
||||||
if (headers) {
|
if (headers) {
|
||||||
|
@ -19,7 +19,7 @@ class HrHeaders {
|
||||||
}
|
}
|
||||||
|
|
||||||
private _setHeader(
|
private _setHeader(
|
||||||
header: Record<string, string | string[]> | HrHeaders | string,
|
header: Record<string, string | string[]> | IrHeaders | string,
|
||||||
_value: string | string[],
|
_value: string | string[],
|
||||||
_header: string
|
_header: string
|
||||||
) {
|
) {
|
||||||
|
@ -32,14 +32,14 @@ class HrHeaders {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
private _setHeaders(headers: Record<string, string | string[]> | HrHeaders | string) {
|
private _setHeaders(headers: Record<string, string | string[]> | IrHeaders | string) {
|
||||||
return utils.forEach(headers, (_value: string | string[], _header: string) => {
|
return utils.forEach(headers, (_value: string | string[], _header: string) => {
|
||||||
return this._setHeader(headers, _value, _header);
|
return this._setHeader(headers, _value, _header);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
set(header: Record<string, string | string[]> | HrHeaders | string): this {
|
set(header: Record<string, string | string[]> | IrHeaders | string): this {
|
||||||
// 通过传入的 headers 创建 HrHeaders 对象
|
// 通过传入的 headers 创建 IrHeaders 对象
|
||||||
if (utils.checkPlainObject(header) || header instanceof this.constructor) {
|
if (utils.checkPlainObject(header) || header instanceof this.constructor) {
|
||||||
this._setHeaders(header);
|
this._setHeaders(header);
|
||||||
} else if (utils.checkString(header) && (header = header.trim()) && !checkHeaderName(header as string)) {
|
} else if (utils.checkString(header) && (header = header.trim()) && !checkHeaderName(header as string)) {
|
||||||
|
@ -103,8 +103,8 @@ class HrHeaders {
|
||||||
return deleted;
|
return deleted;
|
||||||
}
|
}
|
||||||
|
|
||||||
concat(...items: (Record<string, string | string[]> | HrHeaders)[]): HrHeaders {
|
concat(...items: (Record<string, string | string[]> | IrHeaders)[]): IrHeaders {
|
||||||
return HrHeaders.concat(this, ...items);
|
return IrHeaders.concat(this, ...items);
|
||||||
}
|
}
|
||||||
|
|
||||||
toJSON(arrayToStr?: boolean): Record<string, string | string[]> {
|
toJSON(arrayToStr?: boolean): Record<string, string | string[]> {
|
||||||
|
@ -168,7 +168,7 @@ class HrHeaders {
|
||||||
// 定义默认头部
|
// 定义默认头部
|
||||||
const defaultHeaders = ['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent'];
|
const defaultHeaders = ['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent'];
|
||||||
|
|
||||||
// 将默认响应头加入 HrHeaders
|
// 将默认响应头加入 IrHeaders
|
||||||
defaultHeaders.forEach(header => {
|
defaultHeaders.forEach(header => {
|
||||||
if (!accessors[header]) {
|
if (!accessors[header]) {
|
||||||
Object.defineProperty(this, header, {
|
Object.defineProperty(this, header, {
|
||||||
|
@ -182,11 +182,11 @@ class HrHeaders {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
static from(thing: Record<string, string | string[]> | HrHeaders): HrHeaders {
|
static from(thing: Record<string, string | string[]> | IrHeaders): IrHeaders {
|
||||||
if (thing instanceof HrHeaders) {
|
if (thing instanceof IrHeaders) {
|
||||||
return thing;
|
return thing;
|
||||||
} else {
|
} else {
|
||||||
const newInstance = new HrHeaders(thing);
|
const newInstance = new IrHeaders(thing);
|
||||||
|
|
||||||
// 删除值为 undefined 请求头, fetch 进行自动配置
|
// 删除值为 undefined 请求头, fetch 进行自动配置
|
||||||
for (const key in newInstance) {
|
for (const key in newInstance) {
|
||||||
|
@ -200,11 +200,11 @@ class HrHeaders {
|
||||||
}
|
}
|
||||||
|
|
||||||
static concat(
|
static concat(
|
||||||
firstItem: Record<string, string | string[]> | HrHeaders,
|
firstItem: Record<string, string | string[]> | IrHeaders,
|
||||||
...otherItems: (Record<string, string | string[]> | HrHeaders)[]
|
...otherItems: (Record<string, string | string[]> | IrHeaders)[]
|
||||||
): HrHeaders {
|
): IrHeaders {
|
||||||
// 初始化一个 HrHeaders 对象实例
|
// 初始化一个 IrHeaders 对象实例
|
||||||
const newInstance = new HrHeaders(firstItem);
|
const newInstance = new IrHeaders(firstItem);
|
||||||
const mergedObject = Object.assign({}, newInstance, ...otherItems);
|
const mergedObject = Object.assign({}, newInstance, ...otherItems);
|
||||||
|
|
||||||
for (const key in mergedObject) {
|
for (const key in mergedObject) {
|
||||||
|
@ -224,4 +224,4 @@ class HrHeaders {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default HrHeaders;
|
export default IrHeaders;
|
|
@ -1,5 +1,5 @@
|
||||||
import horizonRequest from '../../horizonRequest';
|
import inulaRequest from '../../inulaRequest';
|
||||||
import { CacheItem, HrRequestConfig, Limitation, QueryOptions } from '../../types/interfaces';
|
import { CacheItem, IrRequestConfig, Limitation, QueryOptions } from '../../types/interfaces';
|
||||||
import utils from "../../utils/commonUtils/utils";
|
import utils from "../../utils/commonUtils/utils";
|
||||||
|
|
||||||
// 兼容 IE 上没有 CustomEvent 对象
|
// 兼容 IE 上没有 CustomEvent 对象
|
||||||
|
@ -10,12 +10,12 @@ function createCustomEvent(eventName: string, options?: Record<string, any>) {
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
class HRClient {
|
class IRClient {
|
||||||
private cache: Map<string, CacheItem> = new Map();
|
private cache: Map<string, CacheItem> = new Map();
|
||||||
private historyData: string[] = [];
|
private historyData: string[] = [];
|
||||||
public requestEvent = utils.isIE() ? createCustomEvent('request') : new CustomEvent('request');
|
public requestEvent = utils.isIE() ? createCustomEvent('request') : new CustomEvent('request');
|
||||||
|
|
||||||
public async query(url: string, config?: HrRequestConfig, options: QueryOptions = {}): Promise<any> {
|
public async query(url: string, config?: IrRequestConfig, options: QueryOptions = {}): Promise<any> {
|
||||||
const {
|
const {
|
||||||
pollingInterval,
|
pollingInterval,
|
||||||
enablePollingOptimization,
|
enablePollingOptimization,
|
||||||
|
@ -29,7 +29,7 @@ class HRClient {
|
||||||
return cacheItem.data; // 返回缓存中的数据
|
return cacheItem.data; // 返回缓存中的数据
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await horizonRequest.get(url, config);
|
const response = await inulaRequest.get(url, config);
|
||||||
const data = response.data;
|
const data = response.data;
|
||||||
|
|
||||||
// 如果轮询已配置,设置一个定时器
|
// 如果轮询已配置,设置一个定时器
|
||||||
|
@ -143,4 +143,4 @@ class HRClient {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default HRClient;
|
export default IRClient;
|
|
@ -1,13 +1,13 @@
|
||||||
import Horizon from '@cloudsop/horizon';
|
import Inula from 'inulajs';
|
||||||
import HRClient from './HRClient';
|
import IRClient from './IRClient';
|
||||||
import { HrRequestConfig, QueryOptions } from '../../types/interfaces';
|
import { IrRequestConfig, QueryOptions } from '../../types/interfaces';
|
||||||
|
|
||||||
// 全局初始化一个 HRClient 实例
|
// 全局初始化一个 IRClient 实例
|
||||||
const hrClient = new HRClient();
|
const irClient = new IRClient();
|
||||||
|
|
||||||
const useHR = <T = unknown>(url: string, config?: HrRequestConfig, options?: QueryOptions): { data?: T; error?: any } => {
|
const useIR = <T = unknown>(url: string, config?: IrRequestConfig, options?: QueryOptions): { data?: T; error?: any } => {
|
||||||
const [data, setData] = Horizon.useState<T>(null as unknown as T);
|
const [data, setData] = Inula.useState<T>(null as unknown as T);
|
||||||
const [error, setError] = Horizon.useState<any>(null);
|
const [error, setError] = Inula.useState<any>(null);
|
||||||
|
|
||||||
function handleRequest(result: any) {
|
function handleRequest(result: any) {
|
||||||
return (event: any) => {
|
return (event: any) => {
|
||||||
|
@ -16,10 +16,10 @@ const useHR = <T = unknown>(url: string, config?: HrRequestConfig, options?: Que
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
Horizon.useEffect(() => {
|
Inula.useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
try {
|
||||||
let result = await hrClient.query(url, config, options);
|
let result = await irClient.query(url, config, options);
|
||||||
document.addEventListener('request', handleRequest(result));
|
document.addEventListener('request', handleRequest(result));
|
||||||
|
|
||||||
setData(result); // 未设置轮询查询时展示一次
|
setData(result); // 未设置轮询查询时展示一次
|
||||||
|
@ -32,7 +32,7 @@ const useHR = <T = unknown>(url: string, config?: HrRequestConfig, options?: Que
|
||||||
|
|
||||||
// 清除缓存
|
// 清除缓存
|
||||||
return () => {
|
return () => {
|
||||||
hrClient.invalidateCache(url);
|
irClient.invalidateCache(url);
|
||||||
document.removeEventListener('request', handleRequest);
|
document.removeEventListener('request', handleRequest);
|
||||||
};
|
};
|
||||||
}, [url, config]);
|
}, [url, config]);
|
||||||
|
@ -40,4 +40,4 @@ const useHR = <T = unknown>(url: string, config?: HrRequestConfig, options?: Que
|
||||||
return { data, error };
|
return { data, error };
|
||||||
};
|
};
|
||||||
|
|
||||||
export default useHR;
|
export default useIR;
|
|
@ -1,5 +1,5 @@
|
||||||
import utils from '../utils/commonUtils/utils';
|
import utils from '../utils/commonUtils/utils';
|
||||||
import HrHeaders from '../core/HrHeaders';
|
import IrHeaders from '../core/IrHeaders';
|
||||||
import getJSONByFormData from '../utils/dataUtils/getJSONByFormData';
|
import getJSONByFormData from '../utils/dataUtils/getJSONByFormData';
|
||||||
import getFormData from '../utils/dataUtils/getFormData';
|
import getFormData from '../utils/dataUtils/getFormData';
|
||||||
import { Strategy } from '../types/types';
|
import { Strategy } from '../types/types';
|
||||||
|
@ -29,7 +29,7 @@ const strategies: Record<string, Strategy> = {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function transformRequest(data: any, headers: HrHeaders): any {
|
function transformRequest(data: any, headers: IrHeaders): any {
|
||||||
const contentType = headers['Content-Type'] || '';
|
const contentType = headers['Content-Type'] || '';
|
||||||
const hasJSONContentType = contentType.indexOf('application/json') > -1;
|
const hasJSONContentType = contentType.indexOf('application/json') > -1;
|
||||||
const isObjectPayload = utils.checkObject(data);
|
const isObjectPayload = utils.checkObject(data);
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import { HrRequestConfig, HrResponse, TransitionalOptions } from '../types/interfaces';
|
import { IrRequestConfig, IrResponse, TransitionalOptions } from '../types/interfaces';
|
||||||
import HrError from '../core/HrError';
|
import IrError from '../core/IrError';
|
||||||
import defaultConfig from '../config/defaultConfig';
|
import defaultConfig from '../config/defaultConfig';
|
||||||
|
|
||||||
// this 需要拿到上下文的config,processRequest 是动态调用的,直接将 config 当参数传入会拿到错误的 config
|
// this 需要拿到上下文的config,processRequest 是动态调用的,直接将 config 当参数传入会拿到错误的 config
|
||||||
function transformResponse<T>(this: HrRequestConfig, data: any): T | string | null {
|
function transformResponse<T>(this: IrRequestConfig, data: any): T | string | null {
|
||||||
const transitional: TransitionalOptions = this.transitional || defaultConfig.transitional;
|
const transitional: TransitionalOptions = this.transitional || defaultConfig.transitional;
|
||||||
|
|
||||||
// 判断是否需要强制 JSON 解析
|
// 判断是否需要强制 JSON 解析
|
||||||
|
@ -21,7 +21,7 @@ function transformResponse<T>(this: HrRequestConfig, data: any): T | string | nu
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (enableStrictJSONParsing) {
|
if (enableStrictJSONParsing) {
|
||||||
if ((error as Error).name !== 'SyntaxError') {
|
if ((error as Error).name !== 'SyntaxError') {
|
||||||
throw HrError.from(error as Error, (HrError as any).ERR_BAD_RESPONSE, this, null, (this as any).response); // 使用拦截器可能会将 response 写入 config 中
|
throw IrError.from(error as Error, (IrError as any).ERR_BAD_RESPONSE, this, null, (this as any).response); // 使用拦截器可能会将 response 写入 config 中
|
||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,61 +0,0 @@
|
||||||
import HorizonRequest from './core/HorizonRequest';
|
|
||||||
import utils from './utils/commonUtils/utils';
|
|
||||||
import { CancelTokenStatic, HrInterface, HrRequestConfig } from './types/interfaces';
|
|
||||||
import defaultConfig from './config/defaultConfig';
|
|
||||||
import fetchLike from './request/ieCompatibility/fetchLike';
|
|
||||||
import CancelToken from './cancel/CancelToken';
|
|
||||||
import checkCancel from './cancel/checkCancel';
|
|
||||||
import HrError, { isHrError } from './core/HrError';
|
|
||||||
import buildInstance from './utils/instanceUtils/buildInstance';
|
|
||||||
import HrHeaders from './core/HrHeaders';
|
|
||||||
import CancelError from './cancel/CancelError';
|
|
||||||
import 'core-js/stable';
|
|
||||||
|
|
||||||
// 使用默认配置创建 hr 对象实例
|
|
||||||
const horizonRequest = buildInstance(defaultConfig as HrRequestConfig);
|
|
||||||
|
|
||||||
// 提供 Hr 类继承
|
|
||||||
horizonRequest.HorizonRequest = HorizonRequest as unknown as HrInterface;
|
|
||||||
|
|
||||||
// 创建 hr 实例的工厂函数
|
|
||||||
horizonRequest.create = HorizonRequest.create;
|
|
||||||
|
|
||||||
// 提供取消请求令牌
|
|
||||||
horizonRequest.CancelToken = CancelToken as CancelTokenStatic;
|
|
||||||
|
|
||||||
horizonRequest.isCancel = checkCancel;
|
|
||||||
|
|
||||||
horizonRequest.Cancel = CancelError;
|
|
||||||
|
|
||||||
horizonRequest.all = utils.all;
|
|
||||||
|
|
||||||
horizonRequest.spread = utils.spread;
|
|
||||||
|
|
||||||
horizonRequest.default = horizonRequest;
|
|
||||||
|
|
||||||
horizonRequest.CanceledError = CancelError;
|
|
||||||
|
|
||||||
horizonRequest.HrError = HrError;
|
|
||||||
|
|
||||||
horizonRequest.isHrError = isHrError;
|
|
||||||
|
|
||||||
horizonRequest.HrHeaders = HrHeaders;
|
|
||||||
|
|
||||||
horizonRequest.defaults = defaultConfig as HrRequestConfig;
|
|
||||||
|
|
||||||
/*--------------------------------兼容axios-----------------------------------*/
|
|
||||||
|
|
||||||
horizonRequest.Axios = HorizonRequest;
|
|
||||||
|
|
||||||
horizonRequest.AxiosError = HrError;
|
|
||||||
|
|
||||||
horizonRequest.isAxiosError = isHrError;
|
|
||||||
|
|
||||||
horizonRequest.AxiosHeaders = HrHeaders;
|
|
||||||
|
|
||||||
export default horizonRequest;
|
|
||||||
|
|
||||||
// 兼容 IE 浏览器 fetch
|
|
||||||
if (utils.isIE()) {
|
|
||||||
(window as any).fetch = fetchLike;
|
|
||||||
}
|
|
|
@ -1,8 +1,8 @@
|
||||||
import utils from '../utils/commonUtils/utils';
|
import utils from '../utils/commonUtils/utils';
|
||||||
import { InterceptorHandler, HrInterceptorManager } from '../types/interfaces';
|
import { InterceptorHandler, IrInterceptorManager } from '../types/interfaces';
|
||||||
import { FulfilledFn, RejectedFn } from '../types/types';
|
import { FulfilledFn, RejectedFn } from '../types/types';
|
||||||
|
|
||||||
class InterceptorManager<V> implements HrInterceptorManager<V> {
|
class InterceptorManager<V> implements IrInterceptorManager<V> {
|
||||||
private handlers: (InterceptorHandler<V> | null)[];
|
private handlers: (InterceptorHandler<V> | null)[];
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
|
@ -42,4 +42,4 @@ class InterceptorManager<V> implements HrInterceptorManager<V> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default InterceptorManager;
|
export default InterceptorManager;
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
import { HrRequestConfig, InterceptorHandler, Interceptors } from '../types/interfaces';
|
import { IrRequestConfig, InterceptorHandler, Interceptors } from '../types/interfaces';
|
||||||
import { FulfilledFn } from '../types/types';
|
import { FulfilledFn } from '../types/types';
|
||||||
|
|
||||||
// 获取请求拦截器链以及是否异步信息
|
// 获取请求拦截器链以及是否异步信息
|
||||||
function getRequestInterceptorsInfo(
|
function getRequestInterceptorsInfo(
|
||||||
interceptors: Interceptors,
|
interceptors: Interceptors,
|
||||||
config: HrRequestConfig | undefined,
|
config: IrRequestConfig | undefined,
|
||||||
isSync: boolean | undefined
|
isSync: boolean | undefined
|
||||||
) {
|
) {
|
||||||
const requestInterceptorChain: (FulfilledFn<any> | undefined)[] = [];
|
const requestInterceptorChain: (FulfilledFn<any> | undefined)[] = [];
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
import { FulfilledFn } from '../types/types';
|
import { FulfilledFn } from '../types/types';
|
||||||
import { HrRequestConfig } from '../types/interfaces';
|
import { IrRequestConfig } from '../types/interfaces';
|
||||||
|
|
||||||
// 处理含有异步拦截器情况
|
// 处理含有异步拦截器情况
|
||||||
function handleAsyncInterceptor(
|
function handleAsyncInterceptor(
|
||||||
processFunc: (value: any) => any,
|
processFunc: (value: any) => any,
|
||||||
requestInterceptorChain: (FulfilledFn<any> | undefined)[],
|
requestInterceptorChain: (FulfilledFn<any> | undefined)[],
|
||||||
responseInterceptorChain: (FulfilledFn<any> | undefined)[],
|
responseInterceptorChain: (FulfilledFn<any> | undefined)[],
|
||||||
mergedConfig: HrRequestConfig
|
mergedConfig: IrRequestConfig
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
// undefined 占位 rejected 回调函数
|
// undefined 占位 rejected 回调函数
|
||||||
const chain = [...requestInterceptorChain, processFunc, undefined, ...responseInterceptorChain];
|
const chain = [...requestInterceptorChain, processFunc, undefined, ...responseInterceptorChain];
|
||||||
|
|
|
@ -0,0 +1,61 @@
|
||||||
|
import InulaRequest from './core/InulaRequest';
|
||||||
|
import utils from './utils/commonUtils/utils';
|
||||||
|
import { CancelTokenStatic, IrInterface, IrRequestConfig } from './types/interfaces';
|
||||||
|
import defaultConfig from './config/defaultConfig';
|
||||||
|
import fetchLike from './request/ieCompatibility/fetchLike';
|
||||||
|
import CancelToken from './cancel/CancelToken';
|
||||||
|
import checkCancel from './cancel/checkCancel';
|
||||||
|
import IrError, { isIrError } from './core/IrError';
|
||||||
|
import buildInstance from './utils/instanceUtils/buildInstance';
|
||||||
|
import IrHeaders from './core/IrHeaders';
|
||||||
|
import CancelError from './cancel/CancelError';
|
||||||
|
import 'core-js/stable';
|
||||||
|
|
||||||
|
// 使用默认配置创建 ir 对象实例
|
||||||
|
const inulaRequest = buildInstance(defaultConfig as IrRequestConfig);
|
||||||
|
|
||||||
|
// 提供 Ir 类继承
|
||||||
|
inulaRequest.InulaRequest = InulaRequest as unknown as IrInterface;
|
||||||
|
|
||||||
|
// 创建 ir 实例的工厂函数
|
||||||
|
inulaRequest.create = InulaRequest.create;
|
||||||
|
|
||||||
|
// 提供取消请求令牌
|
||||||
|
inulaRequest.CancelToken = CancelToken as CancelTokenStatic;
|
||||||
|
|
||||||
|
inulaRequest.isCancel = checkCancel;
|
||||||
|
|
||||||
|
inulaRequest.Cancel = CancelError;
|
||||||
|
|
||||||
|
inulaRequest.all = utils.all;
|
||||||
|
|
||||||
|
inulaRequest.spread = utils.spread;
|
||||||
|
|
||||||
|
inulaRequest.default = inulaRequest;
|
||||||
|
|
||||||
|
inulaRequest.CanceledError = CancelError;
|
||||||
|
|
||||||
|
inulaRequest.IrError = IrError;
|
||||||
|
|
||||||
|
inulaRequest.isIrError = isIrError;
|
||||||
|
|
||||||
|
inulaRequest.IrHeaders = IrHeaders;
|
||||||
|
|
||||||
|
inulaRequest.defaults = defaultConfig as IrRequestConfig;
|
||||||
|
|
||||||
|
/*--------------------------------兼容axios-----------------------------------*/
|
||||||
|
|
||||||
|
inulaRequest.Axios = InulaRequest;
|
||||||
|
|
||||||
|
inulaRequest.AxiosError = IrError;
|
||||||
|
|
||||||
|
inulaRequest.isAxiosError = isIrError;
|
||||||
|
|
||||||
|
inulaRequest.AxiosHeaders = IrHeaders;
|
||||||
|
|
||||||
|
export default inulaRequest;
|
||||||
|
|
||||||
|
// 兼容 IE 浏览器 fetch
|
||||||
|
if (utils.isIE()) {
|
||||||
|
(window as any).fetch = fetchLike;
|
||||||
|
}
|
|
@ -1,11 +1,11 @@
|
||||||
import utils from '../utils/commonUtils/utils';
|
import utils from '../utils/commonUtils/utils';
|
||||||
import HrError from '../core/HrError';
|
import IrError from '../core/IrError';
|
||||||
import { HrRequestConfig, HrResponse, Cancel } from '../types/interfaces';
|
import { IrRequestConfig, IrResponse, Cancel } from '../types/interfaces';
|
||||||
import { Method, ResponseType } from '../types/types';
|
import { Method, ResponseType } from '../types/types';
|
||||||
import processUploadProgress from './processUploadProgress';
|
import processUploadProgress from './processUploadProgress';
|
||||||
import processDownloadProgress from './processDownloadProgress';
|
import processDownloadProgress from './processDownloadProgress';
|
||||||
|
|
||||||
export const fetchRequest = (config: HrRequestConfig): Promise<HrResponse> => {
|
export const fetchRequest = (config: IrRequestConfig): Promise<IrResponse> => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let {
|
let {
|
||||||
method = 'GET',
|
method = 'GET',
|
||||||
|
@ -62,7 +62,7 @@ export const fetchRequest = (config: HrRequestConfig): Promise<HrResponse> => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
controller.abort();
|
controller.abort();
|
||||||
const errorMsg = timeoutErrorMessage ?? `timeout of ${timeout}ms exceeded`;
|
const errorMsg = timeoutErrorMessage ?? `timeout of ${timeout}ms exceeded`;
|
||||||
const error = new HrError(errorMsg, '', config, undefined, undefined);
|
const error = new IrError(errorMsg, '', config, undefined, undefined);
|
||||||
reject(error);
|
reject(error);
|
||||||
}, timeout);
|
}, timeout);
|
||||||
}
|
}
|
||||||
|
@ -85,7 +85,7 @@ export const fetchRequest = (config: HrRequestConfig): Promise<HrResponse> => {
|
||||||
|
|
||||||
config.method = config.method!.toLowerCase() as Method;
|
config.method = config.method!.toLowerCase() as Method;
|
||||||
|
|
||||||
const responseData: HrResponse = {
|
const responseData: IrResponse = {
|
||||||
data: '',
|
data: '',
|
||||||
status: response.status,
|
status: response.status,
|
||||||
statusText: response.statusText,
|
statusText: response.statusText,
|
||||||
|
@ -142,11 +142,11 @@ export const fetchRequest = (config: HrRequestConfig): Promise<HrResponse> => {
|
||||||
if (responseData.config.validateStatus!(responseData.status)) {
|
if (responseData.config.validateStatus!(responseData.status)) {
|
||||||
resolve(responseData);
|
resolve(responseData);
|
||||||
} else {
|
} else {
|
||||||
const error = new HrError(responseData.statusText, '', responseData.config, responseData.request, responseData);
|
const error = new IrError(responseData.statusText, '', responseData.config, responseData.request, responseData);
|
||||||
reject(error);
|
reject(error);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((error: HrError) => {
|
.catch((error: IrError) => {
|
||||||
if (error.name === 'AbortError') {
|
if (error.name === 'AbortError') {
|
||||||
reject(error.message);
|
reject(error.message);
|
||||||
} else {
|
} else {
|
||||||
|
@ -154,7 +154,7 @@ export const fetchRequest = (config: HrRequestConfig): Promise<HrResponse> => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch((error: HrError) => {
|
.catch((error: IrError) => {
|
||||||
if (error.name === 'AbortError') {
|
if (error.name === 'AbortError') {
|
||||||
reject(error.message);
|
reject(error.message);
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
import utils from '../utils/commonUtils/utils';
|
import utils from '../utils/commonUtils/utils';
|
||||||
import HrError from '../core/HrError';
|
import IrError from '../core/IrError';
|
||||||
import CustomAbortController from './ieCompatibility/CustomAbortController';
|
import CustomAbortController from './ieCompatibility/CustomAbortController';
|
||||||
import { HrRequestConfig, HrResponse, Cancel } from '../types/interfaces';
|
import { IrRequestConfig, IrResponse, Cancel } from '../types/interfaces';
|
||||||
import { Method, ResponseType } from '../types/types';
|
import { Method, ResponseType } from '../types/types';
|
||||||
|
|
||||||
export const ieFetchRequest = (config: HrRequestConfig): Promise<HrResponse> => {
|
export const ieFetchRequest = (config: IrRequestConfig): Promise<IrResponse> => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let {
|
let {
|
||||||
method = 'get',
|
method = 'get',
|
||||||
|
@ -76,7 +76,7 @@ export const ieFetchRequest = (config: HrRequestConfig): Promise<HrResponse> =>
|
||||||
|
|
||||||
config.method = config.method!.toLowerCase() as Method;
|
config.method = config.method!.toLowerCase() as Method;
|
||||||
|
|
||||||
const responseData: HrResponse = {
|
const responseData: IrResponse = {
|
||||||
data: '',
|
data: '',
|
||||||
status: response.status,
|
status: response.status,
|
||||||
statusText: response.statusText,
|
statusText: response.statusText,
|
||||||
|
@ -130,7 +130,7 @@ export const ieFetchRequest = (config: HrRequestConfig): Promise<HrResponse> =>
|
||||||
responseData.data = parsedData;
|
responseData.data = parsedData;
|
||||||
resolve(responseData);
|
resolve(responseData);
|
||||||
})
|
})
|
||||||
.catch((error: HrError) => {
|
.catch((error: IrError) => {
|
||||||
if (error.name === 'AbortError') {
|
if (error.name === 'AbortError') {
|
||||||
reject(error.message);
|
reject(error.message);
|
||||||
} else {
|
} else {
|
||||||
|
@ -138,7 +138,7 @@ export const ieFetchRequest = (config: HrRequestConfig): Promise<HrResponse> =>
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch((error: HrError) => {
|
.catch((error: IrError) => {
|
||||||
if (error.name === 'AbortError') {
|
if (error.name === 'AbortError') {
|
||||||
reject(error.message);
|
reject(error.message);
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import CancelError from '../cancel/CancelError';
|
import CancelError from '../cancel/CancelError';
|
||||||
import { HrRequestConfig, HrResponse } from '../types/interfaces';
|
import { IrRequestConfig, IrResponse } from '../types/interfaces';
|
||||||
import HrHeaders from '../core/HrHeaders';
|
import IrHeaders from '../core/IrHeaders';
|
||||||
import transformData from '../utils/dataUtils/transformData';
|
import transformData from '../utils/dataUtils/transformData';
|
||||||
import { fetchRequest } from './fetchRequest';
|
import { fetchRequest } from './fetchRequest';
|
||||||
import transformRequest from '../dataTransformers/transformRequest';
|
import transformRequest from '../dataTransformers/transformRequest';
|
||||||
|
@ -9,7 +9,7 @@ import checkCancel from '../cancel/checkCancel';
|
||||||
import { ieFetchRequest } from './ieFetchRequest';
|
import { ieFetchRequest } from './ieFetchRequest';
|
||||||
import utils from '../utils/commonUtils/utils';
|
import utils from '../utils/commonUtils/utils';
|
||||||
|
|
||||||
export default function processRequest(config: HrRequestConfig): Promise<HrResponse> {
|
export default function processRequest(config: IrRequestConfig): Promise<IrResponse> {
|
||||||
if (config.cancelToken) {
|
if (config.cancelToken) {
|
||||||
config.cancelToken.throwIfRequested();
|
config.cancelToken.throwIfRequested();
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,7 @@ export default function processRequest(config: HrRequestConfig): Promise<HrRespo
|
||||||
}
|
}
|
||||||
|
|
||||||
// 拦截可能会传入普通对象
|
// 拦截可能会传入普通对象
|
||||||
config.headers = HrHeaders.from(config.headers as Record<string, any>);
|
config.headers = IrHeaders.from(config.headers as Record<string, any>);
|
||||||
|
|
||||||
// 转换请求数据
|
// 转换请求数据
|
||||||
if (config.data) {
|
if (config.data) {
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
import { HrRequestConfig, HrResponse } from '../types/interfaces';
|
import { IrRequestConfig, IrResponse } from '../types/interfaces';
|
||||||
import HrError from "../core/HrError";
|
import IrError from "../core/IrError";
|
||||||
|
|
||||||
function processUploadProgress(
|
function processUploadProgress(
|
||||||
onUploadProgress: Function | null,
|
onUploadProgress: Function | null,
|
||||||
data: FormData,
|
data: FormData,
|
||||||
reject: (reason?: any) => void,
|
reject: (reason?: any) => void,
|
||||||
resolve: (value: PromiseLike<HrResponse<any>> | HrResponse<any>) => void,
|
resolve: (value: PromiseLike<IrResponse<any>> | IrResponse<any>) => void,
|
||||||
method: string,
|
method: string,
|
||||||
url: string | undefined,
|
url: string | undefined,
|
||||||
config: HrRequestConfig,
|
config: IrRequestConfig,
|
||||||
) {
|
) {
|
||||||
if (onUploadProgress && data instanceof FormData) {
|
if (onUploadProgress) {
|
||||||
let totalBytesToUpload = 0; // 上传的总字节数
|
let totalBytesToUpload = 0; // 上传的总字节数
|
||||||
data.forEach(value => {
|
data.forEach(value => {
|
||||||
if (value instanceof Blob) {
|
if (value instanceof Blob) {
|
||||||
|
@ -47,7 +47,7 @@ function processUploadProgress(
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
reject('parse error');
|
reject('parse error');
|
||||||
}
|
}
|
||||||
const response: HrResponse = {
|
const response: IrResponse = {
|
||||||
data: parsedText,
|
data: parsedText,
|
||||||
status: xhr.status,
|
status: xhr.status,
|
||||||
statusText: xhr.statusText,
|
statusText: xhr.statusText,
|
||||||
|
@ -59,7 +59,7 @@ function processUploadProgress(
|
||||||
// 如果 fetch 请求已经成功或者拒绝,则此处不生效
|
// 如果 fetch 请求已经成功或者拒绝,则此处不生效
|
||||||
resolve(response);
|
resolve(response);
|
||||||
} else {
|
} else {
|
||||||
const error = new HrError(xhr.statusText, '', config, xhr, response);
|
const error = new IrError(xhr.statusText, '', config, xhr, response);
|
||||||
reject(error);
|
reject(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -72,13 +72,13 @@ function processUploadProgress(
|
||||||
xhr.ontimeout = function () {
|
xhr.ontimeout = function () {
|
||||||
xhr.abort();
|
xhr.abort();
|
||||||
const errorMsg = config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`;
|
const errorMsg = config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`;
|
||||||
throw new HrError(errorMsg, '', config, xhr, undefined);
|
throw new IrError(errorMsg, '', config, xhr, undefined);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const header in config.headers) {
|
for (const header in config.headers) {
|
||||||
if (
|
if (
|
||||||
!['Content-Length', 'Accept-Encoding', 'User-Agent', 'Content-Type'].includes(header) // 过滤不安全的请求头设置
|
!['Content-Length', 'Accept-Encoding', 'User-Agent'].includes(header) // 过滤不安全的请求头设置
|
||||||
&& Object.prototype.hasOwnProperty.call(config.headers, header) // 不遍历请求头原型上的方法
|
&& Object.prototype.hasOwnProperty.call(config.headers, header) // 不遍历请求头原型上的方法
|
||||||
) {
|
) {
|
||||||
xhr.setRequestHeader(header, config.headers[header]);
|
xhr.setRequestHeader(header, config.headers[header]);
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
import HrError from '../core/HrError';
|
import IrError from '../core/IrError';
|
||||||
import HrHeaders from '../core/HrHeaders';
|
import IrHeaders from '../core/IrHeaders';
|
||||||
import { Method, ResponseType, HrTransformer, FulfilledFn, RejectedFn, Callback } from './types';
|
import { Method, ResponseType, IrTransformer, FulfilledFn, RejectedFn, Callback } from './types';
|
||||||
import CancelError from "../cancel/CancelError";
|
import CancelError from "../cancel/CancelError";
|
||||||
import { CanceledError } from "../../index";
|
import { CanceledError } from "../../index";
|
||||||
|
|
||||||
// 请求配置
|
// 请求配置
|
||||||
export interface HrRequestConfig {
|
export interface IrRequestConfig {
|
||||||
url?: string;
|
url?: string;
|
||||||
|
|
||||||
method?: Method;
|
method?: Method;
|
||||||
|
@ -59,7 +59,7 @@ export interface TransitionalOptions {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 请求响应
|
// 请求响应
|
||||||
export type HrResponse<T = any> = {
|
export type IrResponse<T = any> = {
|
||||||
// 响应数据
|
// 响应数据
|
||||||
data: T;
|
data: T;
|
||||||
|
|
||||||
|
@ -73,7 +73,7 @@ export type HrResponse<T = any> = {
|
||||||
headers: any;
|
headers: any;
|
||||||
|
|
||||||
// 请求配置
|
// 请求配置
|
||||||
config: HrRequestConfig;
|
config: IrRequestConfig;
|
||||||
|
|
||||||
// 请求对象
|
// 请求对象
|
||||||
request?: any;
|
request?: any;
|
||||||
|
@ -82,39 +82,39 @@ export type HrResponse<T = any> = {
|
||||||
event?: string;
|
event?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Hr 类接口类型
|
// Ir 类接口类型
|
||||||
export interface HrInterface {
|
export interface IrInterface {
|
||||||
request<T = unknown>(url: string | Record<string, any>, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
request<T = unknown>(url: string | Record<string, any>, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
get<T = unknown>(url: string, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
get<T = unknown>(url: string, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
post<T = unknown>(url: string, data?: any, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
post<T = unknown>(url: string, data?: any, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
put<T = unknown>(url: string, data?: any, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
put<T = unknown>(url: string, data?: any, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
delete<T = unknown>(url: string, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
delete<T = unknown>(url: string, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
head<T = unknown>(url: string, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
head<T = unknown>(url: string, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
options<T = unknown>(url: string, config?: HrRequestConfig): Promise<HrResponse<T>>;
|
options<T = unknown>(url: string, config?: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
postForm<T = unknown>(url: string, data: any, config: HrRequestConfig): Promise<HrResponse<T>>;
|
postForm<T = unknown>(url: string, data: any, config: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
putForm<T = unknown>(url: string, data: any, config: HrRequestConfig): Promise<HrResponse<T>>;
|
putForm<T = unknown>(url: string, data: any, config: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
|
|
||||||
patchForm<T = unknown>(url: string, data: any, config: HrRequestConfig): Promise<HrResponse<T>>;
|
patchForm<T = unknown>(url: string, data: any, config: IrRequestConfig): Promise<IrResponse<T>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hr 实例接口类型
|
// Ir 实例接口类型
|
||||||
export interface HrInstance extends HrInterface {
|
export interface IrInstance extends IrInterface {
|
||||||
// Hr 类
|
// Ir 类
|
||||||
HorizonRequest: HrInterface;
|
InulaRequest: IrInterface;
|
||||||
|
|
||||||
// 创建 Hr 实例
|
// 创建 Ir 实例
|
||||||
create: (config?: HrRequestConfig) => HrInstance;
|
create: (config?: IrRequestConfig) => IrInstance;
|
||||||
|
|
||||||
// 使用内置的配置初始化实例属性
|
// 使用内置的配置初始化实例属性
|
||||||
defaults: HrRequestConfig;
|
defaults: IrRequestConfig;
|
||||||
|
|
||||||
// 取消当前正在进行的请求
|
// 取消当前正在进行的请求
|
||||||
CancelToken: CancelTokenStatic;
|
CancelToken: CancelTokenStatic;
|
||||||
|
@ -134,21 +134,21 @@ export interface HrInstance extends HrInterface {
|
||||||
// 封装多个 Promise 至数组,便于作为 all 传入参数
|
// 封装多个 Promise 至数组,便于作为 all 传入参数
|
||||||
spread: <T>(callback: Callback<T>) => (arr: any[]) => T;
|
spread: <T>(callback: Callback<T>) => (arr: any[]) => T;
|
||||||
|
|
||||||
// horizonRequest 对象的默认实例
|
// inulaRequest 对象的默认实例
|
||||||
default: HrInstance;
|
default: IrInstance;
|
||||||
|
|
||||||
CanceledError: typeof CancelError;
|
CanceledError: typeof CancelError;
|
||||||
|
|
||||||
// HrError 错误
|
// IrError 错误
|
||||||
HrError: typeof HrError;
|
IrError: typeof IrError;
|
||||||
|
|
||||||
// 判断输入值是否为 HrError
|
// 判断输入值是否为 IrError
|
||||||
isHrError: (avl: any) => boolean;
|
isIrError: (avl: any) => boolean;
|
||||||
|
|
||||||
// HrHeaders 响应头
|
// IrHeaders 响应头
|
||||||
HrHeaders: typeof HrHeaders;
|
IrHeaders: typeof IrHeaders;
|
||||||
|
|
||||||
useHR: <T = any>(url: string, config?: HrRequestConfig, options?: QueryOptions) => { data?: T; error?: any };
|
useIR: <T = any>(url: string, config?: IrRequestConfig, options?: QueryOptions) => { data?: T; error?: any };
|
||||||
|
|
||||||
/*----------------兼容axios--------------------*/
|
/*----------------兼容axios--------------------*/
|
||||||
Axios: any;
|
Axios: any;
|
||||||
|
@ -161,8 +161,8 @@ export interface HrInstance extends HrInterface {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Interceptors {
|
export interface Interceptors {
|
||||||
request: HrInterceptorManager<HrRequestConfig>;
|
request: IrInterceptorManager<IrRequestConfig>;
|
||||||
response: HrInterceptorManager<HrResponse>;
|
response: IrInterceptorManager<IrResponse>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 拦截器接口类型
|
// 拦截器接口类型
|
||||||
|
@ -181,7 +181,7 @@ export interface InterceptorHandler<T> {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 拦截器管理器接口类型
|
// 拦截器管理器接口类型
|
||||||
export interface HrInterceptorManager<T> {
|
export interface IrInterceptorManager<T> {
|
||||||
// 添加拦截器
|
// 添加拦截器
|
||||||
use(
|
use(
|
||||||
fulfilled?: FulfilledFn<T>,
|
fulfilled?: FulfilledFn<T>,
|
||||||
|
@ -202,18 +202,18 @@ export interface HrInterceptorManager<T> {
|
||||||
forEach(func: Function): void;
|
forEach(func: Function): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HrErrorInterface {
|
export interface IrErrorInterface {
|
||||||
// 产生错误的请求配置对象
|
// 产生错误的请求配置对象
|
||||||
config?: HrRequestConfig;
|
config?: IrRequestConfig;
|
||||||
|
|
||||||
// 表示请求错误的字符串代码。例如,"ECONNABORTED"表示连接被中止。
|
// 表示请求错误的字符串代码。例如,"ECONNABORTED"表示连接被中止。
|
||||||
code?: string;
|
code?: string;
|
||||||
|
|
||||||
// 产生错误的原始请求实例。
|
// 产生错误的原始请求实例。
|
||||||
request?: HrInstance;
|
request?: IrInstance;
|
||||||
|
|
||||||
// 包含错误响应的响应实例。如果请求成功完成,但服务器返回错误状态码(例如404或500),则此属性存在。
|
// 包含错误响应的响应实例。如果请求成功完成,但服务器返回错误状态码(例如404或500),则此属性存在。
|
||||||
response?: HrResponse;
|
response?: IrResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 请求取消令牌
|
// 请求取消令牌
|
||||||
|
@ -273,7 +273,7 @@ export interface Limitation {
|
||||||
maxInterval: number,
|
maxInterval: number,
|
||||||
}
|
}
|
||||||
|
|
||||||
// useHR 缓存
|
// useIR 缓存
|
||||||
export interface CacheItem {
|
export interface CacheItem {
|
||||||
data: any;
|
data: any;
|
||||||
lastUpdated: number;
|
lastUpdated: number;
|
||||||
|
|
|
@ -1,5 +1,4 @@
|
||||||
import HrHeaders from '../core/HrHeaders';
|
import IrHeaders from '../core/IrHeaders';
|
||||||
import { HrRequestConfig, HrResponse } from './interfaces';
|
|
||||||
|
|
||||||
export type Method =
|
export type Method =
|
||||||
| 'get'
|
| 'get'
|
||||||
|
@ -20,7 +19,7 @@ export type Method =
|
||||||
export type ResponseType = 'text' | 'json' | 'blob' | 'arraybuffer';
|
export type ResponseType = 'text' | 'json' | 'blob' | 'arraybuffer';
|
||||||
|
|
||||||
// 请求和响应数据转换器
|
// 请求和响应数据转换器
|
||||||
export type HrTransformer = (data: any, headers?: HrHeaders) => any;
|
export type IrTransformer = (data: any, headers?: IrHeaders) => any;
|
||||||
|
|
||||||
// Headers
|
// Headers
|
||||||
export type HeaderMap = Record<string, string | string[]>;
|
export type HeaderMap = Record<string, string | string[]>;
|
||||||
|
@ -34,8 +33,6 @@ export type RejectedFn = (error: any) => any;
|
||||||
export type FilterFunc = (obj: Record<string, any>, destObj: Record<string, any>) => boolean;
|
export type FilterFunc = (obj: Record<string, any>, destObj: Record<string, any>) => boolean;
|
||||||
export type PropFilterFunc = (prop: string | symbol, obj: Record<string, any>, destObj: Record<string, any>) => boolean;
|
export type PropFilterFunc = (prop: string | symbol, obj: Record<string, any>, destObj: Record<string, any>) => boolean;
|
||||||
|
|
||||||
export type ObjectDescriptor = PropertyDescriptorMap & ThisType<any>;
|
|
||||||
|
|
||||||
// Cancel
|
// Cancel
|
||||||
export type CancelFunction = (message?: string) => void;
|
export type CancelFunction = (message?: string) => void;
|
||||||
export type CancelExecutor = (cancel: CancelFunction) => void;
|
export type CancelExecutor = (cancel: CancelFunction) => void;
|
||||||
|
@ -43,5 +40,5 @@ export type CancelExecutor = (cancel: CancelFunction) => void;
|
||||||
export type Callback<T> = (...args: any[]) => T;
|
export type Callback<T> = (...args: any[]) => T;
|
||||||
|
|
||||||
export type Strategy = {
|
export type Strategy = {
|
||||||
(data: any, headers: HrHeaders, ...args: any[]): any;
|
(data: any, headers: IrHeaders, ...args: any[]): any;
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
import HrHeaders from '../../core/HrHeaders';
|
import IrHeaders from '../../core/IrHeaders';
|
||||||
import defaultConfig from '../../config/defaultConfig';
|
import defaultConfig from '../../config/defaultConfig';
|
||||||
import { HrRequestConfig, HrResponse } from '../../types/interfaces';
|
import { IrRequestConfig, IrResponse } from '../../types/interfaces';
|
||||||
|
|
||||||
function transformData(inputConfig: HrRequestConfig, func: Function, response?: HrResponse) {
|
function transformData(inputConfig: IrRequestConfig, func: Function, response?: IrResponse) {
|
||||||
const config = inputConfig || defaultConfig;
|
const config = inputConfig || defaultConfig;
|
||||||
const context = response || config;
|
const context = response || config;
|
||||||
const headers = HrHeaders.from(context.headers);
|
const headers = IrHeaders.from(context.headers);
|
||||||
|
|
||||||
const transformedData = func.call(config, context.data, headers.normalize(), response ? response.status : undefined);
|
const transformedData = func.call(config, context.data, headers.normalize(), response ? response.status : undefined);
|
||||||
headers.normalize();
|
headers.normalize();
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
import { HrInstance, HrRequestConfig } from '../../types/interfaces';
|
import { IrInstance, IrRequestConfig } from '../../types/interfaces';
|
||||||
import HorizonRequest from '../../core/HorizonRequest';
|
import InulaRequest from '../../core/InulaRequest';
|
||||||
import extendInstance from './extendInstance';
|
import extendInstance from './extendInstance';
|
||||||
|
|
||||||
function buildInstance(config: HrRequestConfig): HrInstance {
|
function buildInstance(config: IrRequestConfig): IrInstance {
|
||||||
// 使用上下文 context 将请求和响应的配置和状态集中在一个地方,使得整个 Hr 实例可以共享这些配置和状态,避免了在多个地方重复定义和管理这些配置和状态
|
// 使用上下文 context 将请求和响应的配置和状态集中在一个地方,使得整个 Ir 实例可以共享这些配置和状态,避免了在多个地方重复定义和管理这些配置和状态
|
||||||
const context = new HorizonRequest(config);
|
const context = new InulaRequest(config);
|
||||||
|
|
||||||
// 将 Hr.prototype.request 方法上下文绑定到 context 上下文,将一个新的函数返回,并将这个新的函数保存到一个 instance 常量中,可以在 instance 实例上使用 Hr 类原型上的方法和属性,同时又可以保证这些方法和属性在当前实例上下文中正确地执行
|
// 将 Ir.prototype.request 方法上下文绑定到 context 上下文,将一个新的函数返回,并将这个新的函数保存到一个 instance 常量中,可以在 instance 实例上使用 Ir 类原型上的方法和属性,同时又可以保证这些方法和属性在当前实例上下文中正确地执行
|
||||||
const instance = extendInstance(context);
|
const instance = extendInstance(context);
|
||||||
|
|
||||||
return instance as any;
|
return instance as any;
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import HorizonRequest from '../../core/HorizonRequest';
|
import InulaRequest from '../../core/InulaRequest';
|
||||||
import utils from '../commonUtils/utils';
|
import utils from '../commonUtils/utils';
|
||||||
|
|
||||||
function extendInstance(context: HorizonRequest): (...arg: any) => any {
|
function extendInstance(context: InulaRequest): (...arg: any) => any {
|
||||||
const instance = utils.bind(HorizonRequest.prototype.request, context);
|
const instance = utils.bind(InulaRequest.prototype.request, context);
|
||||||
utils.extendObject(instance, HorizonRequest.prototype, context, { includeAll: true });
|
utils.extendObject(instance, InulaRequest.prototype, context, { includeAll: true });
|
||||||
utils.extendObject(instance, context, null, { includeAll: true });
|
utils.extendObject(instance, context, null, { includeAll: true });
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,7 @@ const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||||
const {resolve} = require("path");
|
const {resolve} = require("path");
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
entry: './examples/useHR/index.jsx', // 入口文件
|
entry: './examples/useIR/index.jsx', // 入口文件
|
||||||
output: {
|
output: {
|
||||||
path: path.resolve(__dirname, 'dist'), // 输出目录
|
path: path.resolve(__dirname, 'dist'), // 输出目录
|
||||||
filename: 'bundle.js' // 输出文件名
|
filename: 'bundle.js' // 输出文件名
|
||||||
|
@ -33,7 +33,7 @@ module.exports = {
|
||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
new HtmlWebpackPlugin({
|
new HtmlWebpackPlugin({
|
||||||
template: resolve(__dirname, './examples/useHR/index.html'),
|
template: resolve(__dirname, './examples/useIR/index.html'),
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
resolve: {
|
resolve: {
|
||||||
|
|
Loading…
Reference in New Issue