feat(升级包): request、slave

This commit is contained in:
NICE CODE BY DEV 2024-04-07 11:52:34 +08:00
parent b433d5f182
commit 35497d39ad
26 changed files with 1242 additions and 608 deletions

View File

@ -1,5 +1,13 @@
# @zhst/biz # @zhst/biz
## 0.11.3
### Patch Changes
- @zhst/func@0.9.1
- @zhst/hooks@0.8.10
- @zhst/meta@0.9.7
## 0.11.2 ## 0.11.2
### Patch Changes ### Patch Changes

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/biz", "name": "@zhst/biz",
"version": "0.11.2", "version": "0.11.3",
"description": "业务库", "description": "业务库",
"keywords": [ "keywords": [
"business", "business",

View File

@ -1,5 +1,13 @@
# @zhst/utils # @zhst/utils
## 0.9.1
### Patch Changes
- Updated dependencies
- Updated dependencies
- @zhst/request@0.9.0
## 0.9.0 ## 0.9.0
### Minor Changes ### Minor Changes

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/func", "name": "@zhst/func",
"version": "0.9.0", "version": "0.9.1",
"description": "函数合集", "description": "函数合集",
"keywords": [ "keywords": [
"hooks" "hooks"

View File

@ -1,5 +1,11 @@
# @zhst/hooks # @zhst/hooks
## 0.8.10
### Patch Changes
- @zhst/func@0.9.1
## 0.8.9 ## 0.8.9
### Patch Changes ### Patch Changes

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/hooks", "name": "@zhst/hooks",
"version": "0.8.9", "version": "0.8.10",
"description": "hooks合集", "description": "hooks合集",
"keywords": [ "keywords": [
"hooks" "hooks"

View File

@ -1,5 +1,14 @@
# @zhst/material # @zhst/material
## 0.7.5
### Patch Changes
- @zhst/func@0.9.1
- @zhst/biz@0.11.3
- @zhst/hooks@0.8.10
- @zhst/meta@0.9.7
## 0.7.4 ## 0.7.4
### Patch Changes ### Patch Changes

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/material", "name": "@zhst/material",
"version": "0.7.4", "version": "0.7.5",
"description": "物料库", "description": "物料库",
"keywords": [ "keywords": [
"business", "business",

View File

@ -1,5 +1,13 @@
# @zhst/utils # @zhst/utils
## 0.9.7
### Patch Changes
- @zhst/func@0.9.1
- @zhst/hooks@0.8.10
- @zhst/meta@0.9.7
## 0.9.6 ## 0.9.6
### Patch Changes ### Patch Changes

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/meta", "name": "@zhst/meta",
"version": "0.9.6", "version": "0.9.7",
"description": "原子组件", "description": "原子组件",
"keywords": [ "keywords": [
"meta", "meta",

View File

@ -1,5 +1,16 @@
# @zhst/request # @zhst/request
## 0.9.0
### Minor Changes
- 新包发布
- 修改配置
### Patch Changes
- @zhst/func@0.9.1
## 0.8.9 ## 0.8.9
### Patch Changes ### Patch Changes

View File

@ -1,21 +1,36 @@
# @zhst/request # @zhst/request
:::info{title=开发中}
还在构思最佳使用方案...
:::
## 介绍 ## 介绍
zhst 请求库 请求库配置,创建初衷是为了统一项目中引用的 request 和 useRequest 的配置。
## 安装 ## 安装
> pnpm install @zhst/request ```js
pnpm install @zhst/request
```
## 使用 ## 使用
```js ```jsx
import React from 'react'; import React from 'react';
import request from '@zhst/request' import { reqConfig } from '@zhst/request'
const config = reqConfig()
console.log('配置', config)
export default () => {
return (
<div>从控制台打印查看</div>
)
}
``` ```
## API
参数可以参考 umi 的 request 配置
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| baseURL | 请求的根域名 | string | location.host | - |

View File

@ -1,4 +1,28 @@
interface RequestConfig { export interface ReqConfigProps {
timeout?: number;
baseURL?: string;
errorConfig?: {
errorHandler?: (error: any, opts: any) => void;
errorThrower?: (err: any) => void;
};
authorization: string;
showMsg?: boolean;
} }
export declare const request: RequestConfig; export declare const reqConfig: (config: ReqConfigProps) => {
export {}; timeout: number;
baseURL: string;
errorConfig: {
errorHandler?: ((error: any, opts: any) => void) | undefined;
errorThrower?: ((err: any) => void) | undefined;
};
authorization: string;
showMsg?: boolean | undefined;
requestInterceptors: (((url: any, options: any) => {
url: any;
options: any;
}) | ((error: any) => Promise<never>))[][];
responseInterceptors: ((response: {
status: number;
data: any;
}) => any)[][];
};

View File

@ -4,77 +4,90 @@ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t =
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
export var request = { import { message } from 'antd';
timeout: 1000, export var reqConfig = function reqConfig(config) {
// other axios options you want var _ref = config || {},
errorConfig: { authorization = _ref.authorization,
// @ts-ignore showMsg = _ref.showMsg;
errorHandler: function errorHandler(error, opts) { return _objectSpread({
// if (opts?.skipErrorHandler) throw error timeout: 1000,
// try { baseURL: location.origin,
// const { res } = ctx; // other axios options you want
// const d = await res.text(); errorConfig: {
// @ts-ignore
errorHandler: function errorHandler(error, opts) {
console.log('first', error, opts);
// if (opts?.skipErrorHandler) throw error
// try {
// const { res } = ctx;
// const d = await res.text();
// if (res.status === 401 && store.user.isLogin) { // if (res.status === 401 && store.user.isLogin) {
// store.user.resetLoginState(); // store.user.resetLoginState();
// message.warning('登录过期,请重新登录!'); // message.warning('登录过期,请重新登录!');
// return; // return;
// } // }
// const isEmptyRes = d === '' || d.replace(/\s/g,"")=== 'tokenisinvalid'; //有些后端接口成功会返回空 做下兼容 // const isEmptyRes = d === '' || d.replace(/\s/g,"")=== 'tokenisinvalid'; //有些后端接口成功会返回空 做下兼容
// const body = !isEmptyRes ? JSON.parse(d || '{}') : d; // const body = !isEmptyRes ? JSON.parse(d || '{}') : d;
// const sessionCode = sessionStorage.getItem('zhst_errcode') || '{}' // const sessionCode = sessionStorage.getItem('zhst_errcode') || '{}'
// const ERROR_CODE = JSON.parse(sessionCode); // const ERROR_CODE = JSON.parse(sessionCode);
// if (Number(res.status) === 200) { // if (Number(res.status) === 200) {
// ctx.res = body; // ctx.res = body;
// } else { // } else {
// // 先判断Grpc-Metadata-Errorx-Message // // 先判断Grpc-Metadata-Errorx-Message
// let errMsg = ERROR_CODE[body.code]?.value || body.message || '您的网络发生异常,无法连接服务器' // let errMsg = ERROR_CODE[body.code]?.value || body.message || '您的网络发生异常,无法连接服务器'
// toast && message.error(errMsg || body); // toast && message.error(errMsg || body);
// ctx.res = { // ctx.res = {
// code: body.code, // code: body.code,
// message: errMsg // message: errMsg
// }; // };
// } // }
// } catch (error) { // } catch (error) {
// if (get(error, 'type') !== 'CustomError') { // if (get(error, 'type') !== 'CustomError') {
// toast && message.error('您的网络发生异常,无法连接服务器'); // toast && message.error('您的网络发生异常,无法连接服务器');
// } // }
// throw error; // throw error;
// } // }
},
// @ts-ignore
errorThrower: function errorThrower(res) {
console.log('res', res);
}
}, },
// @ts-ignore // 请求
errorThrower: function errorThrower(res) { requestInterceptors: [
console.log('res', res); // 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
} [function (url, options) {
}, var Authorization = authorization || localStorage.getItem('ZHST_AUTH_TOKEN') || '';
// 请求 return {
requestInterceptors: [ url: url,
// 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理 options: _objectSpread(_objectSpread({}, options), {}, {
[function (url, options) { headers: {
// console.log('options', options); Authorization: Authorization
return { }
url: url, })
options: _objectSpread(_objectSpread({}, options), {}, { };
headers: { }, function (error) {
authorization: 'test' return Promise.reject(error);
// ...(refererSuffix ? { zhst_referer: `${baseUrl}${refererSuffix}` } : {}), }]],
} // 返回
}) responseInterceptors: [
}; // 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
}, function (error) { [function (response) {
return Promise.reject(error); if (response.status !== 200) {
}]], throw Error(JSON.stringify(response.data));
// 返回 }
responseInterceptors: [ var _ref2 = response.data || {},
// 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理 code = _ref2.code;
[function (response) { if (showMsg && code !== 200) {
if (response.status !== 200) { message.error(response.data.message || '请求失败!');
throw Error(JSON.stringify(response.data)); return null;
} }
return response; return response.data;
}, function (error) { }, function (error) {
return Promise.reject(error); return Promise.reject(error);
}]] }]]
}, config);
}; };

View File

@ -1,4 +1,28 @@
interface RequestConfig { export interface ReqConfigProps {
timeout?: number;
baseURL?: string;
errorConfig?: {
errorHandler?: (error: any, opts: any) => void;
errorThrower?: (err: any) => void;
};
authorization: string;
showMsg?: boolean;
} }
export declare const request: RequestConfig; export declare const reqConfig: (config: ReqConfigProps) => {
export {}; timeout: number;
baseURL: string;
errorConfig: {
errorHandler?: ((error: any, opts: any) => void) | undefined;
errorThrower?: ((err: any) => void) | undefined;
};
authorization: string;
showMsg?: boolean | undefined;
requestInterceptors: (((url: any, options: any) => {
url: any;
options: any;
}) | ((error: any) => Promise<never>))[][];
responseInterceptors: ((response: {
status: number;
data: any;
}) => any)[][];
};

View File

@ -19,59 +19,74 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
// src/index.tsx // src/index.tsx
var src_exports = {}; var src_exports = {};
__export(src_exports, { __export(src_exports, {
request: () => request reqConfig: () => reqConfig
}); });
module.exports = __toCommonJS(src_exports); module.exports = __toCommonJS(src_exports);
var request = { var import_antd = require("antd");
timeout: 1e3, var reqConfig = (config) => {
// other axios options you want const {
errorConfig: { authorization,
// @ts-ignore showMsg
errorHandler(error, opts) { } = config || {};
return {
timeout: 1e3,
baseURL: location.origin,
// other axios options you want
errorConfig: {
// @ts-ignore
errorHandler(error, opts) {
console.log("first", error, opts);
},
// @ts-ignore
errorThrower(res) {
console.log("res", res);
}
}, },
// @ts-ignore // 请求
errorThrower(res) { requestInterceptors: [
console.log("res", res); // 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
} [
}, (url, options) => {
// 请求 const Authorization = authorization || localStorage.getItem("ZHST_AUTH_TOKEN") || "";
requestInterceptors: [ return {
// 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理 url,
[ options: {
(url, options) => { ...options,
return { headers: {
url, Authorization
options: { }
...options,
headers: {
authorization: "test"
// ...(refererSuffix ? { zhst_referer: `${baseUrl}${refererSuffix}` } : {}),
} }
} };
}; },
}, (error) => {
(error) => { return Promise.reject(error);
return Promise.reject(error);
}
]
],
// 返回
responseInterceptors: [
// 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
[
(response) => {
if (response.status !== 200) {
throw Error(JSON.stringify(response.data));
} }
return response; ]
}, ],
(error) => { // 返回
return Promise.reject(error); responseInterceptors: [
} // 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
] [
] (response) => {
if (response.status !== 200) {
throw Error(JSON.stringify(response.data));
}
const { code } = response.data || {};
if (showMsg && code !== 200) {
import_antd.message.error(response.data.message || "请求失败!");
return null;
}
return response.data;
},
(error) => {
return Promise.reject(error);
}
]
],
...config
};
}; };
// Annotate the CommonJS export names for ESM import in node: // Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = { 0 && (module.exports = {
request reqConfig
}); });

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/request", "name": "@zhst/request",
"version": "0.8.9", "version": "0.9.0",
"description": "请求库", "description": "请求库",
"keywords": [ "keywords": [
"request", "request",
@ -14,7 +14,7 @@
"lib/**/style/*", "lib/**/style/*",
"*.less" "*.less"
], ],
"main": "lib/index.ts", "main": "lib/index.js",
"module": "es/index.js", "module": "es/index.js",
"typings": "es/index.d.ts", "typings": "es/index.d.ts",
"exports": { "exports": {
@ -37,11 +37,7 @@
"registry": "http://10.0.0.77:4874" "registry": "http://10.0.0.77:4874"
}, },
"dependencies": { "dependencies": {
"@zhst/func": "workspace:^", "@zhst/func": "workspace:^"
"base-64": "^1.0.0",
"umi": "^4.1.2"
}, },
"devDependencies": { "devDependencies": {}
"@types/base-64": "^1.0.2"
}
} }

View File

@ -1,7 +1,4 @@
--- ---
nav:
title: 其它
order: 999
title: 请求库 title: 请求库
toc: content toc: content
--- ---

View File

@ -0,0 +1,10 @@
---
nav:
title: 其它
order: 999
title: 快速上手
order: 1
toc: content
---
## 请求库

View File

@ -1,87 +1,112 @@
interface RequestConfig { import { message } from 'antd'
export interface ReqConfigProps {
timeout?: number
baseURL?: string
errorConfig?: {
errorHandler?: (error: any, opts: any) => void
errorThrower?: (err: any) => void
}
authorization?: string
showMsg?: boolean
} }
export const request: RequestConfig = { export const reqConfig = (config: ReqConfigProps) => {
timeout: 1000, const {
// other axios options you want authorization,
errorConfig: { showMsg
// @ts-ignore } = config || {}
errorHandler(error: any, opts: any) {
// if (opts?.skipErrorHandler) throw error
// try {
// const { res } = ctx;
// const d = await res.text();
// if (res.status === 401 && store.user.isLogin) { return {
// store.user.resetLoginState(); timeout: 1000,
// message.warning('登录过期,请重新登录!'); baseURL: location.origin,
// return; // other axios options you want
// } errorConfig: {
// const isEmptyRes = d === '' || d.replace(/\s/g,"")=== 'tokenisinvalid'; //有些后端接口成功会返回空 做下兼容 // @ts-ignore
// const body = !isEmptyRes ? JSON.parse(d || '{}') : d; errorHandler(error: any, opts: any) {
// const sessionCode = sessionStorage.getItem('zhst_errcode') || '{}' console.log('first', error, opts);
// const ERROR_CODE = JSON.parse(sessionCode); // if (opts?.skipErrorHandler) throw error
// try {
// const { res } = ctx;
// const d = await res.text();
// if (Number(res.status) === 200) { // if (res.status === 401 && store.user.isLogin) {
// ctx.res = body; // store.user.resetLoginState();
// } else { // message.warning('登录过期,请重新登录!');
// // 先判断Grpc-Metadata-Errorx-Message // return;
// let errMsg = ERROR_CODE[body.code]?.value || body.message || '您的网络发生异常,无法连接服务器' // }
// toast && message.error(errMsg || body); // const isEmptyRes = d === '' || d.replace(/\s/g,"")=== 'tokenisinvalid'; //有些后端接口成功会返回空 做下兼容
// ctx.res = { // const body = !isEmptyRes ? JSON.parse(d || '{}') : d;
// code: body.code, // const sessionCode = sessionStorage.getItem('zhst_errcode') || '{}'
// message: errMsg // const ERROR_CODE = JSON.parse(sessionCode);
// };
// }
// } catch (error) { // if (Number(res.status) === 200) {
// if (get(error, 'type') !== 'CustomError') { // ctx.res = body;
// toast && message.error('您的网络发生异常,无法连接服务器'); // } else {
// } // // 先判断Grpc-Metadata-Errorx-Message
// throw error; // let errMsg = ERROR_CODE[body.code]?.value || body.message || '您的网络发生异常,无法连接服务器'
// } // toast && message.error(errMsg || body);
// ctx.res = {
// code: body.code,
// message: errMsg
// };
// }
// } catch (error) {
// if (get(error, 'type') !== 'CustomError') {
// toast && message.error('您的网络发生异常,无法连接服务器');
// }
// throw error;
// }
},
// @ts-ignore
errorThrower(res) {
console.log('res', res);
},
}, },
// @ts-ignore // 请求
errorThrower(res) { requestInterceptors: [
console.log('res', res); // 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
}, [
}, (url: any, options: any) => {
// 请求 const Authorization = authorization || localStorage.getItem('ZHST_AUTH_TOKEN') || ''
requestInterceptors: [
// 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理 return {
[ url,
(url: any, options: any) => { options: {
// console.log('options', options); ...options,
return { headers: {
url, Authorization,
options: { },
...options,
headers: {
authorization: 'test',
// ...(refererSuffix ? { zhst_referer: `${baseUrl}${refererSuffix}` } : {}),
}, },
}, };
}; },
}, (error: any) => {
(error: any) => { return Promise.reject(error);
return Promise.reject(error); },
}, ],
], ],
], // 返回
// 返回 responseInterceptors: [
responseInterceptors: [ // 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理
// 一个二元组,第一个元素是 request 拦截器,第二个元素是错误处理 [
[ (response: { status: number; data: any; }) => {
(response: { status: number; data: any; }) => { if (response.status !== 200) {
if (response.status !== 200) { throw Error(JSON.stringify(response.data));
throw Error(JSON.stringify(response.data)); }
} const { code } = response.data || {}
return response;
}, if (showMsg && code !== 200) {
(error: any) => { message.error(response.data.message || '请求失败!')
return Promise.reject(error); return null
}, }
return response.data;
},
(error: any) => {
return Promise.reject(error);
},
],
], ],
], ...config
}; };
}

View File

@ -1,5 +1,17 @@
# @zhst/slave # @zhst/slave
## 0.5.0
### Minor Changes
- slave 添加一些和 token 相关的方法
## 0.4.1
### Patch Changes
- @zhst/func@0.9.1
## 0.4.0 ## 0.4.0
### Minor Changes ### Minor Changes

View File

@ -1,6 +1,6 @@
{ {
"name": "@zhst/slave", "name": "@zhst/slave",
"version": "0.4.0", "version": "0.5.0",
"description": "微前端子应用方法库", "description": "微前端子应用方法库",
"keywords": [ "keywords": [
"slave", "slave",

View File

@ -9,6 +9,12 @@ export default () => {
} }
return ( return (
<button onClick={handleInit} ></button> <div>
<button onClick={handleInit} ></button>
<button onClick={() => slave.logOut()}>退</button>
<button onClick={() => slave.getToken()}>token</button>
<button onClick={() => slave.setToken('ppt')}>token</button>
<button onClick={() => slave.removeToken()}>token</button>
</div>
) )
} }

View File

@ -30,3 +30,6 @@ title: 快速上手
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| init | 初始化实例 | function | (data: SlaveProps) => void | - | | init | 初始化实例 | function | (data: SlaveProps) => void | - |
| logOut | 退出登录 | function | () => void | - | | logOut | 退出登录 | function | () => void | - |
| getToken | 获取token | function | () => void | - |
| setToken | 设置token | function | (token: string) => void | - |
| removeToken | 移除token | function | () => void | - |

View File

@ -87,7 +87,7 @@ class Slave {
} }
// 检查是否为url并且跑出错误 // 检查是否为url并且跑出错误
checkUrl(url: string, label: string) { public checkUrl(url: string, label: string) {
if (!isUrl(url)) { if (!isUrl(url)) {
throw Error(`请输入正确的 ${label} 链接地址以http(s)://开头!'`) throw Error(`请输入正确的 ${label} 链接地址以http(s)://开头!'`)
} }

File diff suppressed because it is too large Load Diff