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