@flyto/request 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";var e=require("qs"),t=require("axios");exports.createRequestClient=function(r){const n=function(r){let n;const o=()=>{n=setTimeout(()=>{r.toggleWarpLoading?.(!1)},10)},s=t.create({...r.defaultConfig,timeout:6e4});return s.interceptors.request.use(async t=>{if(Object.assign(t,{openLoading:t.openLoading??!0,method:t.method??"POST"}),r.beforeRequest)try{const e=await(r.beforeRequest?.(t));if(!1===e.success)return Promise.reject({message:e.message||"请求被拦截"})}catch(e){return Promise.reject(e)}t.openLoading&&(clearTimeout(n),r.toggleWarpLoading?.(!0,t.tip));const o=t.headers?.["Content-Type"]||"";return"get"===t.method||"GET"===t.method?t.params=t.data:o.includes("application/x-www-form-urlencoded")&&(t.notQsContentType||(t.data=e.stringify(t.data))),t}),s.interceptors.response.use(async e=>{if(o(),r.afterResponse)try{await(r.afterResponse?.(e))}catch(e){console.warn("[afterResponse 执行异常]",e)}if(!e.config.ignoreStandardHandler){const{config:t}=e,{ignoreErrorMsg:n=!1,ignoreSuccessMsg:o=!0}=t,s=e.data,i=s.Message?String(s.Message):"";if(0===s.Code&&s.Success)o||r.notify?.success?.(i||"成功");else if(!n)throw r.notify?.error?.(i||"错误,请联系相关人员!","normal"),s}return e},e=>{o();let t="";return t="string"==typeof e?e:"object"==typeof e?JSON.stringify(e):String(e),r.notify?.error?.(t,"network"),e}),s}(r);return{request:async function(e,t){if(!n)throw new Error("请先注册请求函数");const r="string"==typeof e?{method:"post",...t,url:e}:e,{data:o}=await n(r);return o},axiosIns:n}},exports.defineConfig=function(e){return"function"==typeof e?e():e};
@@ -0,0 +1,64 @@
1
+ import { AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
2
+ import { HttpResponse, StandardRequestConfig } from './types';
3
+ /**
4
+ * 配置项
5
+ */
6
+ interface RequestOptions {
7
+ /** axios的默认配置 */
8
+ defaultConfig: AxiosRequestConfig;
9
+ /**
10
+ * 切换遮罩显隐状态
11
+ * @param status 变更后的状态
12
+ * @param tip 此次请求时,给到遮罩的提示语
13
+ *
14
+ */
15
+ toggleWarpLoading?(status: boolean, onceTip?: string): void;
16
+ /** 提示方法 */
17
+ notify?: {
18
+ /**
19
+ * 成功提示
20
+ * @param msg 提示文本
21
+ */
22
+ success?(msg: string): void;
23
+ /**
24
+ * 错误提示
25
+ * @param msg 提示文本
26
+ * @param type 提示类型 normal: 普通错误,network: 网络错误
27
+ */
28
+ error?(msg: string, type?: 'normal' | 'network'): void;
29
+ };
30
+ /**
31
+ * 在请求拦截器中执行,返回 false 或抛错将终止请求
32
+ */
33
+ beforeRequest?: (config: StandardRequestConfig) => {
34
+ success: boolean;
35
+ message?: string;
36
+ } | Promise<{
37
+ success: boolean;
38
+ message?: string;
39
+ }>;
40
+ /**
41
+ * 在响应成功返回后执行(不管 Code 是否为 0)
42
+ */
43
+ afterResponse?: (response: AxiosResponse & {
44
+ config: StandardRequestConfig;
45
+ }) => void | Promise<void>;
46
+ }
47
+ /**
48
+ * 定义一个标准的Request配置
49
+ * @param config 配置
50
+ * @returns
51
+ */
52
+ export declare function defineConfig(config: RequestOptions | (() => RequestOptions)): RequestOptions;
53
+ /**
54
+ * 创建一个请求客户端
55
+ * @param options 配置项
56
+ */
57
+ export declare function createRequestClient(options: RequestOptions): {
58
+ request: {
59
+ <D = any, T = HttpResponse<D>>(url: string, config?: StandardRequestConfig): Promise<T>;
60
+ <D_1 = any, T_1 = HttpResponse<D_1>>(config: StandardRequestConfig): Promise<T_1>;
61
+ };
62
+ axiosIns: AxiosInstance;
63
+ };
64
+ export * from './types';
@@ -0,0 +1 @@
1
+ import e from"qs";import t from"axios";function o(e){return"function"==typeof e?e():e}function r(o){const r=function(o){let r;const n=()=>{r=setTimeout(()=>{o.toggleWarpLoading?.(!1)},10)},s=t.create({...o.defaultConfig,timeout:6e4});return s.interceptors.request.use(async t=>{if(Object.assign(t,{openLoading:t.openLoading??!0,method:t.method??"POST"}),o.beforeRequest)try{const e=await(o.beforeRequest?.(t));if(!1===e.success)return Promise.reject({message:e.message||"请求被拦截"})}catch(e){return Promise.reject(e)}t.openLoading&&(clearTimeout(r),o.toggleWarpLoading?.(!0,t.tip));const n=t.headers?.["Content-Type"]||"";return"get"===t.method||"GET"===t.method?t.params=t.data:n.includes("application/x-www-form-urlencoded")&&(t.notQsContentType||(t.data=e.stringify(t.data))),t}),s.interceptors.response.use(async e=>{if(n(),o.afterResponse)try{await(o.afterResponse?.(e))}catch(e){console.warn("[afterResponse 执行异常]",e)}if(!e.config.ignoreStandardHandler){const{config:t}=e,{ignoreErrorMsg:r=!1,ignoreSuccessMsg:n=!0}=t,s=e.data,i=s.Message?String(s.Message):"";if(0===s.Code&&s.Success)n||o.notify?.success?.(i||"成功");else if(!r)throw o.notify?.error?.(i||"错误,请联系相关人员!","normal"),s}return e},e=>{n();let t="";return t="string"==typeof e?e:"object"==typeof e?JSON.stringify(e):String(e),o.notify?.error?.(t,"network"),e}),s}(o);return{request:async function(e,t){if(!r)throw new Error("请先注册请求函数");const o="string"==typeof e?{method:"post",...t,url:e}:e,{data:n}=await r(o);return n},axiosIns:r}}export{r as createRequestClient,o as defineConfig};
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("qs"),require("axios")):"function"==typeof define&&define.amd?define(["exports","qs","axios"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["flyto-arco-notify"]={},e.qs,e.axios)}(this,function(e,t,o){"use strict";e.createRequestClient=function(e){const n=function(e){let n;const r=()=>{n=setTimeout(()=>{e.toggleWarpLoading?.(!1)},10)},s=o.create({...e.defaultConfig,timeout:6e4});return s.interceptors.request.use(async o=>{if(Object.assign(o,{openLoading:o.openLoading??!0,method:o.method??"POST"}),e.beforeRequest)try{const t=await(e.beforeRequest?.(o));if(!1===t.success)return Promise.reject({message:t.message||"请求被拦截"})}catch(e){return Promise.reject(e)}o.openLoading&&(clearTimeout(n),e.toggleWarpLoading?.(!0,o.tip));const r=o.headers?.["Content-Type"]||"";return"get"===o.method||"GET"===o.method?o.params=o.data:r.includes("application/x-www-form-urlencoded")&&(o.notQsContentType||(o.data=t.stringify(o.data))),o}),s.interceptors.response.use(async t=>{if(r(),e.afterResponse)try{await(e.afterResponse?.(t))}catch(e){console.warn("[afterResponse 执行异常]",e)}if(!t.config.ignoreStandardHandler){const{config:o}=t,{ignoreErrorMsg:n=!1,ignoreSuccessMsg:r=!0}=o,s=t.data,i=s.Message?String(s.Message):"";if(0===s.Code&&s.Success)r||e.notify?.success?.(i||"成功");else if(!n)throw e.notify?.error?.(i||"错误,请联系相关人员!","normal"),s}return t},t=>{r();let o="";return o="string"==typeof t?t:"object"==typeof t?JSON.stringify(t):String(t),e.notify?.error?.(o,"network"),t}),s}(e);return{request:async function(e,t){if(!n)throw new Error("请先注册请求函数");const o="string"==typeof e?{method:"post",...t,url:e}:e,{data:r}=await n(o);return r},axiosIns:n}},e.defineConfig=function(e){return"function"==typeof e?e():e}});
2
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.js","sources":["../src/index.ts"],"sourcesContent":["import qs from 'qs'\r\nimport axios, {\r\n AxiosInstance,\r\n type AxiosRequestConfig,\r\n type AxiosResponse,\r\n} from 'axios'\r\nimport { HttpResponse, StandardRequestConfig } from './types'\r\n\r\n/** 默认 成功Code值 */\r\nconst SUCCESS_CODE = 0\r\n/** 需要通过qs转换的Content-Type */\r\nconst CONTENT_TYPE_TANSFORM = 'application/x-www-form-urlencoded'\r\n/** 请求超时时间 1分钟 */\r\nconst REQUEST_TIMEOUT = 1000 * 60 * 1\r\n\r\n/**\r\n * 配置项\r\n */\r\ninterface RequestOptions {\r\n /** axios的默认配置 */\r\n defaultConfig: AxiosRequestConfig\r\n /**\r\n * 切换遮罩显隐状态\r\n * @param status 变更后的状态\r\n * @param tip 此次请求时,给到遮罩的提示语\r\n *\r\n */\r\n toggleWarpLoading?(status: boolean, onceTip?: string): void\r\n /** 提示方法 */\r\n notify?: {\r\n /**\r\n * 成功提示\r\n * @param msg 提示文本\r\n */\r\n success?(msg: string): void\r\n /**\r\n * 错误提示\r\n * @param msg 提示文本\r\n * @param type 提示类型 normal: 普通错误,network: 网络错误\r\n */\r\n error?(msg: string, type?: 'normal' | 'network'): void\r\n }\r\n /**\r\n * 在请求拦截器中执行,返回 false 或抛错将终止请求\r\n */\r\n beforeRequest?: (\r\n config: StandardRequestConfig,\r\n ) =>\r\n | { success: boolean; message?: string }\r\n | Promise<{ success: boolean; message?: string }>\r\n /**\r\n * 在响应成功返回后执行(不管 Code 是否为 0)\r\n */\r\n afterResponse?: (\r\n response: AxiosResponse & {\r\n config: StandardRequestConfig\r\n },\r\n ) => void | Promise<void>\r\n}\r\n\r\n/**\r\n * 创建一个已经对拦截器做过逻辑处理的Axios实例\r\n * @param options 配置项\r\n * @returns axios实例\r\n */\r\nfunction createAxiosIns(options: RequestOptions) {\r\n // #region loading遮罩层处理\r\n let tiemerId: NodeJS.Timeout\r\n /**\r\n * 关闭遮罩(会延时50ms)\r\n */\r\n const closeLoading = () => {\r\n // 遮罩延迟50毫秒关闭\r\n // 如果有两个连续的请求,使其动画不中断,体验感较好\r\n tiemerId = setTimeout(() => {\r\n options.toggleWarpLoading?.(false)\r\n }, 10)\r\n }\r\n // #endregion\r\n\r\n const axiosIns = axios.create({\r\n ...options.defaultConfig,\r\n timeout: REQUEST_TIMEOUT,\r\n })\r\n // 在发送请求之前做些什么\r\n axiosIns.interceptors.request.use(async (config: StandardRequestConfig) => {\r\n // 合并默认值\r\n Object.assign(config, {\r\n openLoading: config.openLoading ?? true,\r\n method: config.method ?? 'POST',\r\n })\r\n\r\n // 自定义在请求之前做些什么\r\n if (options.beforeRequest) {\r\n try {\r\n const result = await options.beforeRequest?.(config)\r\n if (result.success === false) {\r\n // 取消请求\r\n return Promise.reject({ message: result.message || '请求被拦截' })\r\n }\r\n } catch (err) {\r\n return Promise.reject(err)\r\n }\r\n }\r\n\r\n // 打开遮罩\r\n if (config.openLoading) {\r\n // 如果下一个请求马上进来了,则清除掉计时器\r\n clearTimeout(tiemerId)\r\n options.toggleWarpLoading?.(true, config.tip)\r\n }\r\n\r\n const contentType: string = config.headers?.['Content-Type'] || ''\r\n if (config.method === 'get' || config.method === 'GET') {\r\n config.params = config.data\r\n // 非默认的content-type,不进行qs的转换\r\n } else if (contentType.includes(CONTENT_TYPE_TANSFORM)) {\r\n // qs转格式\r\n if (!config.notQsContentType) {\r\n config.data = qs.stringify(config.data)\r\n }\r\n }\r\n\r\n return config\r\n })\r\n // 在请求成功后做些什么\r\n axiosIns.interceptors.response.use(\r\n async (\r\n response: AxiosResponse & {\r\n config: StandardRequestConfig\r\n },\r\n ) => {\r\n closeLoading()\r\n\r\n // 自定义在请求之后做些什么\r\n if (options.afterResponse) {\r\n try {\r\n await options.afterResponse?.(response)\r\n } catch (err) {\r\n console.warn('[afterResponse 执行异常]', err)\r\n }\r\n }\r\n\r\n // 使用标准返回结构体(HttpResponse)的通用错误处理\r\n // 非HttpResponse,请自行处理\r\n if (!response.config.ignoreStandardHandler) {\r\n const { config } = response\r\n const { ignoreErrorMsg = false, ignoreSuccessMsg = true } = config\r\n\r\n const data = response.data as HttpResponse\r\n const message = data.Message ? String(data.Message) : ''\r\n\r\n if (data.Code === SUCCESS_CODE && data.Success) {\r\n if (!ignoreSuccessMsg) {\r\n options.notify?.success?.(message || '成功')\r\n }\r\n } else if (!ignoreErrorMsg) {\r\n options.notify?.error?.(message || '错误,请联系相关人员!', 'normal')\r\n throw data\r\n }\r\n }\r\n\r\n return response\r\n },\r\n err => {\r\n // 只要服务器返回的code不是200,都会进入该函数,必须抛出实际错误\r\n closeLoading()\r\n\r\n let errStr = ''\r\n if (typeof err === 'string') {\r\n errStr = err\r\n } else if (typeof err === 'object') {\r\n errStr = JSON.stringify(err)\r\n } else {\r\n errStr = String(err)\r\n }\r\n\r\n options.notify?.error?.(errStr, 'network')\r\n return err\r\n },\r\n )\r\n\r\n return axiosIns\r\n}\r\n\r\n/**\r\n * 定义一个标准的Request配置\r\n * @param config 配置\r\n * @returns\r\n */\r\nexport function defineConfig(config: RequestOptions | (() => RequestOptions)) {\r\n if (typeof config === 'function') {\r\n return config()\r\n }\r\n\r\n return config\r\n}\r\n\r\n/**\r\n * 创建一个请求客户端\r\n * @param options 配置项\r\n */\r\nexport function createRequestClient(options: RequestOptions) {\r\n // axios实例 此实例针对拦截器进行了一些逻辑处理\r\n const axiosIns = createAxiosIns(options)\r\n\r\n /**\r\n * 标准请求方法\r\n * @template D 返回的值中,data的类型(例如HttpResponse中的Data)\r\n * @template T 返回值的类型,默认为HttpResponse\r\n * @param url 请求地址\r\n * @param config 配置项\r\n */\r\n async function request<D = any, T = HttpResponse<D>>(\r\n url: string,\r\n config?: StandardRequestConfig,\r\n ): Promise<T>\r\n /**\r\n * 标准请求方法\r\n * @template D 返回的值中,data的类型(例如HttpResponse中的Data)\r\n * @template T 返回值的类型,默认为HttpResponse\r\n * @param config 配置项\r\n */\r\n async function request<D = any, T = HttpResponse<D>>(\r\n config: StandardRequestConfig,\r\n ): Promise<T>\r\n async function request<D = any, T = HttpResponse<D>>(\r\n urlOrConfig: string | StandardRequestConfig,\r\n config?: StandardRequestConfig,\r\n ): Promise<T> {\r\n if (!axiosIns) {\r\n throw new Error('请先注册请求函数')\r\n }\r\n\r\n const params: StandardRequestConfig =\r\n typeof urlOrConfig === 'string'\r\n ? {\r\n method: 'post',\r\n ...config,\r\n url: urlOrConfig,\r\n }\r\n : urlOrConfig\r\n\r\n const { data }: { data: T } = await axiosIns(params)\r\n\r\n return data\r\n }\r\n\r\n return {\r\n request,\r\n axiosIns,\r\n }\r\n}\r\n\r\nexport * from './types'\r\n"],"names":["options","axiosIns","tiemerId","closeLoading","setTimeout","toggleWarpLoading","axios","create","defaultConfig","timeout","interceptors","request","use","async","config","Object","assign","openLoading","method","beforeRequest","result","success","Promise","reject","message","err","clearTimeout","tip","contentType","headers","params","data","includes","notQsContentType","qs","stringify","response","afterResponse","console","warn","ignoreStandardHandler","ignoreErrorMsg","ignoreSuccessMsg","Message","String","Code","Success","notify","error","errStr","JSON","createAxiosIns","urlOrConfig","Error","url"],"mappings":"8UA0MM,SAA8BA,GAElC,MAAMC,EA3IR,SAAwBD,GAEtB,IAAIE,EAIJ,MAAMC,EAAe,KAGnBD,EAAWE,WAAW,KACpBJ,EAAQK,qBAAoB,IAC3B,KAICJ,EAAWK,EAAMC,OAAO,IACzBP,EAAQQ,cACXC,QArEoB,MAyKtB,OAjGAR,EAASS,aAAaC,QAAQC,IAAIC,MAAOC,IAQvC,GANAC,OAAOC,OAAOF,EAAQ,CACpBG,YAAaH,EAAOG,cAAe,EACnCC,OAAQJ,EAAOI,QAAU,SAIvBlB,EAAQmB,cACV,IACE,MAAMC,QAAepB,EAAQmB,gBAAgBL,IAC7C,IAAuB,IAAnBM,EAAOC,QAET,OAAOC,QAAQC,OAAO,CAAEC,QAASJ,EAAOI,SAAW,SAEtD,CAAC,MAAOC,GACP,OAAOH,QAAQC,OAAOE,EACvB,CAICX,EAAOG,cAETS,aAAaxB,GACbF,EAAQK,qBAAoB,EAAMS,EAAOa,MAG3C,MAAMC,EAAsBd,EAAOe,UAAU,iBAAmB,GAWhE,MAVsB,QAAlBf,EAAOI,QAAsC,QAAlBJ,EAAOI,OACpCJ,EAAOgB,OAAShB,EAAOiB,KAEdH,EAAYI,SAzGG,uCA2GnBlB,EAAOmB,mBACVnB,EAAOiB,KAAOG,EAAGC,UAAUrB,EAAOiB,QAI/BjB,IAGTb,EAASS,aAAa0B,SAASxB,IAC7BC,MACEuB,IAOA,GAHAjC,IAGIH,EAAQqC,cACV,UACQrC,EAAQqC,gBAAgBD,GAC/B,CAAC,MAAOX,GACPa,QAAQC,KAAK,uBAAwBd,EACtC,CAKH,IAAKW,EAAStB,OAAO0B,sBAAuB,CAC1C,MAAM1B,OAAEA,GAAWsB,GACbK,eAAEA,GAAiB,EAAKC,iBAAEA,GAAmB,GAAS5B,EAEtDiB,EAAOK,EAASL,KAChBP,EAAUO,EAAKY,QAAUC,OAAOb,EAAKY,SAAW,GAEtD,GA/Ia,IA+ITZ,EAAKc,MAAyBd,EAAKe,QAChCJ,GACH1C,EAAQ+C,QAAQ1B,UAAUG,GAAW,WAElC,IAAKiB,EAEV,MADAzC,EAAQ+C,QAAQC,QAAQxB,GAAW,cAAe,UAC5CO,CAET,CAED,OAAOK,GAETX,IAEEtB,IAEA,IAAI8C,EAAS,GAUb,OAREA,EADiB,iBAARxB,EACAA,EACe,iBAARA,EACPyB,KAAKf,UAAUV,GAEfmB,OAAOnB,GAGlBzB,EAAQ+C,QAAQC,QAAQC,EAAQ,WACzBxB,IAIJxB,CACT,CAqBmBkD,CAAenD,GA4ChC,MAAO,CACLW,QAvBFE,eACEuC,EACAtC,GAEA,IAAKb,EACH,MAAM,IAAIoD,MAAM,YAGlB,MAAMvB,EACmB,iBAAhBsB,EACH,CACElC,OAAQ,UACLJ,EACHwC,IAAKF,GAEPA,GAEArB,KAAEA,SAA4B9B,EAAS6B,GAE7C,OAAOC,CACR,EAIC9B,WAEJ,iBA9DM,SAAuBa,GAC3B,MAAsB,mBAAXA,EACFA,IAGFA,CACT"}
@@ -0,0 +1,39 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ /**
3
+ * 标准请求方法配置项
4
+ */
5
+ export interface StandardRequestConfig<T = unknown> extends AxiosRequestConfig<T> {
6
+ /**
7
+ * 打开加载全屏遮罩
8
+ */
9
+ openLoading?: boolean;
10
+ /**
11
+ * 遮罩提示语
12
+ */
13
+ tip?: string;
14
+ /**
15
+ * 忽略请求成功提示
16
+ */
17
+ ignoreSuccessMsg?: boolean;
18
+ /**
19
+ *忽略请求错误提示
20
+ */
21
+ ignoreErrorMsg?: boolean;
22
+ /**
23
+ * 是否忽略采用标准响应结构的回调处理
24
+ */
25
+ ignoreStandardHandler?: boolean;
26
+ /**
27
+ * 在ContentType等于application/x-www-form-urlencoded时,不采用qs转换
28
+ */
29
+ notQsContentType?: boolean;
30
+ }
31
+ /**
32
+ * 标准响应体结构
33
+ */
34
+ export interface HttpResponse<T = unknown> {
35
+ Code: number;
36
+ Success: boolean;
37
+ Message: string | number | null | undefined;
38
+ Data: T;
39
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@flyto/request",
3
+ "version": "1.0.0",
4
+ "types": "./dist/index.d.ts",
5
+ "module": "./dist/index.esm.js",
6
+ "main": "./dist/index.cjs.js",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.esm.js",
10
+ "require": "./dist/index.cjs.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": ["dist"],
15
+ "scripts": {
16
+ "build": "rollup -c && tsc -b ./tsconfig.types.json"
17
+ },
18
+ "prepublishOnly": "pnpm build",
19
+ "dependencies": {
20
+ "axios": "^0.24.0",
21
+ "qs": "^6.13.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^22.10.3",
25
+ "@types/qs": "^6.9.17",
26
+ "rollup": "^3.9.1",
27
+ "rollup-plugin-delete": "^3.0.0",
28
+ "rollup-plugin-terser": "^7.0.2",
29
+ "rollup-plugin-ts": "^3.4.5",
30
+ "typescript": "^4.8.4"
31
+ }
32
+ }