@seayoo-web/request 0.6.1 → 0.7.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.
package/README.md CHANGED
@@ -11,11 +11,11 @@
11
11
 
12
12
  ## 特性
13
13
 
14
- 1. 默认基于 fetch,请求和响应均 基于 json 或 text(不支持其他格式)
14
+ 1. 默认基于 fetch,请求和响应解析均 基于 json 或 text(不支持其他格式)
15
15
  2. 支持重试配置 maxRetry / retryResolve / retryInterval
16
16
  3. 支持响应结果处理策略 responseRule 和通用提示配置
17
17
  4. 支持类型守卫 typeGuard
18
- 5. 支持多实例,多端(浏览器,nodejs,并可以扩展小程序)
18
+ 5. 支持多实例,多端(浏览器,nodejs,微信小程序)
19
19
  7. get 请求函数支持并发缓存(默认缓存 500ms)
20
20
  8. 函数永不抛错,返回固定解析结构 { ok, data, status, headers, code, message }
21
21
  9. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
@@ -64,22 +64,28 @@ setGlobalConfig({
64
64
  })
65
65
  ```
66
66
 
67
- ## 全局函数和自创建实例
67
+ ## 全局函数和自定义实例
68
68
 
69
69
  ```js
70
70
  // 以下为浏览器环境全局默认导出的工具函数
71
71
  import { get, post, put, patch, del, head } from "@seayoo-web/request"
72
-
73
72
  // 以下是 nodejs 环境全局默认导出的工具函数
74
73
  import { get, post, put, patch, del, head } from "@seayoo-web/request/node"
74
+ // 以下是 微信小程序 环境全局默认导出的工具函数
75
+ // 注意,微信不支持 patch 方法
76
+ import { get, post, put, del, head } from "@seayoo-web/request/wx"
75
77
 
76
78
  // 浏览器环境自定义创建实例
77
79
  import { NetRequest } from "@seayoo-web/request"
78
- const { get, post, put, patch, del, setConfig } = NetRequest()
80
+ const { get, post, put, patch, del, head, setConfig } = NetRequest()
79
81
 
80
82
  // nodejs环境自定义创建实例
81
83
  import { NetRequest } from "@seayoo-web/request/node"
82
- const { get, post, put, patch, del, setConfig } = NetRequest()
84
+ const { get, post, put, patch, del, head, setConfig } = NetRequest()
85
+
86
+ // 微信小程序自定义创建实例
87
+ import { NetRequest } from "@seayoo-web/request/wx"
88
+ const { get, post, put, del, head, setConfig } = NetRequest()
83
89
  ```
84
90
 
85
91
  ## 全局配置参数
@@ -336,7 +342,7 @@ type TypeGuard<T> = {
336
342
  type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
337
343
  ```
338
344
 
339
- ## 包装函数
345
+ ## Request函数
340
346
 
341
347
  ### get\<T\>(url: string, typeGard?: TypeGuardParam\<T\> | null, options?: IRequestOptions)
342
348
 
@@ -344,7 +350,7 @@ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
344
350
  - **typeGuard**: 可选类型守卫,如果设置为 null,则返回的内容为 unkonwn,否则就是经过类型守卫检查后的类型化数据,推荐传递类型守卫
345
351
  - **options**: 可选请求配置参数
346
352
 
347
- > 注意,get 请求强制设置 500ms 缓存,即对同一个请求(url+params)在 500ms 内不再重复发起请求,而是直接返回上一次的结果
353
+ > 注意,get 请求默认设置 500ms 缓存,即对同一个请求(url+params)在 500ms 内不再重复发起请求,而是直接返回上一次的结果
348
354
 
349
355
  ### post(url: string, data: RequstBody, typeGard?: TypeGuardParam\<T\> | null, options?: IRequestOptions)
350
356
 
@@ -1,9 +1,9 @@
1
1
  import type { TypeGuardFn } from "@seayoo-web/utils";
2
2
  /**
3
- * 以 script 方式加载远程资源,url 需要是一个完整的url地址,资源通过回调函数接收,强制进行类型校验
3
+ * 以 script 方式加载远程资源,资源通过回调函数接收,强制进行类型校验
4
4
  */
5
5
  export declare function jsonp<T>(url: string, typeGuard: TypeGuardFn<T>, params?: Record<string, string | number | boolean>): Promise<T | null>;
6
6
  /**
7
- * 以 script 方式加载远程资源,url 需要是一个完整的url地址,资源通过全局变量接收,强制进行类型校验
7
+ * 以 script 方式加载远程资源,资源通过全局变量接收,强制进行类型校验
8
8
  */
9
9
  export declare function jsonx<T>(url: string, typeGuard: TypeGuardFn<T>, params?: Record<string, string | number | boolean>): Promise<T | null>;
@@ -0,0 +1,5 @@
1
+ import type { NetRequestAgent } from "./type";
2
+ /**
3
+ * 基于 wx.request 的网络请求包装函数,该方法必定 resolve,限制在微信小程序环境中使用
4
+ */
5
+ export declare const wxRequest: NetRequestAgent;
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- var e=require("@seayoo-web/utils"),t=require("node:http"),r=require("node:https");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/s(t),o=/*#__PURE__*/s(r),a=function t(r,s,n,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:n.get("maxRetry")),h=null!=(u=null==o?void 0:o.retryResolve)?u:n.get("retryResolve"),d=n.get("logHandler")||e.noop;d({type:"prepear",url:s,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var f=Date.now();return Promise.resolve(r(s,n,o)).then(function(a){var i,u=a.status,g=Date.now()-f,m="[cost "+g+"]["+u+"] "+(u<0?a.body:"");if(d({type:"finished",url:s,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+m:"retry "+c+"/"+l+" finish "+m,response:a,cost:g}),!l||"network"===h&&u>0||"status"===h&&u>=200&&u<400||c>=l)return a;var v=null!=(i=null==o?void 0:o.retryInterval)?i:n.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof v?v(c+1):v))).then(function(){return Promise.resolve(t(r,s,n,o,c+1))})})}catch(e){return Promise.reject(e)}};function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},i.apply(this,arguments)}var u="message";function c(t,r){if(void 0===r&&(r=u),!e.isJsonLike(t))return"";var s,n=e.parseJSON(t);return n&&e.isStringRecord(n)&&r in n?(s=n[r])?"string"==typeof s?s:JSON.stringify(s):"":t}function l(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function h(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function d(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var f=function(t,r,s){try{var a=function(e,t,r){var s=Object.assign({method:"GET"},r),n=s.body instanceof FormData,o=n?"POST":s.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=Object.assign(n?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:d(s.body),params:c,headers:a,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}(t,r,s);if(!e.isFullURL(t))return Promise.resolve({url:t,method:a.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var i=/^https:\/\//i.test(t)?o.default:n.default,u=new URL(t),c=a.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===a.method;return Promise.resolve(new Promise(function(e){var r=i.request(u,{headers:a.headers,method:a.method,timeout:a.timeout>0?a.timeout:void 0},function(r){var s=[];l||r.on("data",function(e){return s.push(e)}),r.on("end",function(){var n=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:t,method:a.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:n,body:l?"":Buffer.concat(s).toString("utf-8")})})});r.on("error",function(r){e({url:t,method:a.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),a.body&&r.write(a.body),r.end()}))}catch(e){return Promise.reject(e)}},g=function(t,r,s){try{return Promise.resolve(a(f,t,r,s)).then(function(n){return function(t,r,s,n){if(t.status<0)return h({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},t.method+" "+r+" "+t.statusText,t.method,r,s,n);var o;(t.status<200||t.status>=400)&&(null==(o=s.get("errorHandler"))||o(t.status,t.method,r));var a,d,f,g,m,v=i({},(a=t.status,d=t.statusText,f=t.body,g=s.get("responseRule"),m=(null==n?void 0:n.responseRule)||g,a>=200&&a<400?function(t,r,s,n){var o=t||{resolve:"body"},a={ok:!0,code:s,message:"",data:null};if(202===r||204===r||!n)return a;if("body"===o.resolve)return a.data=e.isJsonLike(n)?e.parseJSON(n):n,a;var i=e.parseJSON(n);if(!i||!e.isStringRecord(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var c=o.statusField||"code",l=o.statusOKValue||"0",h=o.dataField||"data",d=o.messageField||u,f=o.ignoreMessage||"";if(!(c in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+c,a;var g=i[c]+"";return a.ok=g===l,a.code=g,a.message=d in i?i[d]+"":"",a.data=h in i?i[h]:null,f&&a.message&&(Array.isArray(f)&&f.includes(a.message)||"string"==typeof f&&a.message===f)&&(a.message=""),a}(m.ok||g.ok,a,d,f):function(e,t,r){var s=e||{resolve:"json",messageField:u},n={ok:!1,code:t,message:r,data:null};switch(s.resolve){case"auto":n.message=l(r)||c(r,s.messageField)||r;break;case"body":n.message=l(r)||r;break;case"json":n.message=c(r,s.messageField)}return n}(m.failed||g.failed,d,f)),{status:t.status,headers:Object.fromEntries(Object.entries(t.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return h(v,v.ok?v.message:t.method+" "+r+" ["+v.code+"] "+(v.message||t.statusText),t.method,r,s,n)}(n,t,r,s)})}catch(e){return Promise.reject(e)}},m=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),v=/*#__PURE__*/function(){function t(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var r=t.prototype;return r.set=function(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!e.isFullURL(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)},r.get=function(e){return this.config[e]},r.getFullUrl=function(t){return t.startsWith("/")?e.getFullURL(t):e.getFullURL(t,this.config.baseURL)},r.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},t}(),y=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new v(t),this.agent=e,this.cache=new m(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this)}var r=t.prototype;return r.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},r.guard=function(t,r,s){try{return Promise.resolve(function(t,r,s,n){if(r.ok&&!e.isEmpty(r.data)&&null!==n){var o=e.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),s.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,s))}catch(e){return Promise.reject(e)}},r.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},r.getConfig=function(e){return this.config.get(e)},r.head=function(e,t){try{var r=this,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function p(e){return new y(g,e)}var b=p(),j=b.setConfig,P=b.head,x=b.get,O=b.post,R=b.del,T=b.put,w=b.patch;exports.NetRequest=p,exports.del=R,exports.get=x,exports.head=P,exports.patch=w,exports.post=O,exports.put=T,exports.setGlobalConfig=j;
1
+ var e=require("node:http"),t=require("node:https"),r=require("@seayoo-web/utils");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/s(e),o=/*#__PURE__*/s(t),a=function e(t,s,n,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:n.get("maxRetry")),h=null!=(u=null==o?void 0:o.retryResolve)?u:n.get("retryResolve"),d=n.get("logHandler")||r.noop;d({type:"prepear",url:s,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var f=Date.now();return Promise.resolve(t(s,n,o)).then(function(a){var i,u=a.status,g=Date.now()-f,m="[cost "+g+"]["+u+"] "+(u<0?a.body:"");if(d({type:"finished",url:s,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+m:"retry "+c+"/"+l+" finish "+m,response:a,cost:g}),!l||"network"===h&&u>0||"status"===h&&u>=200&&u<400||c>=l)return a;var v=null!=(i=null==o?void 0:o.retryInterval)?i:n.get("retryInterval");return Promise.resolve(r.sleep(Math.max(100,"function"==typeof v?v(c+1):v))).then(function(){return Promise.resolve(e(t,s,n,o,c+1))})})}catch(e){return Promise.reject(e)}};function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},i.apply(this,arguments)}var u="message";function c(e,t){if(void 0===t&&(t=u),!r.isJsonLike(e))return"";var s,n=r.parseJSON(e);return n&&r.isStringRecord(n)&&t in n?(s=n[t])?"string"==typeof s?s:JSON.stringify(s):"":e}function l(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function h(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function d(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var f=function(e,t,s){try{return Promise.resolve(a(g,e,t,s)).then(function(n){return function(e,t,s,n){if(e.status<0)return h({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,s,n);var o;(e.status<200||e.status>=400)&&(null==(o=s.get("errorHandler"))||o(e.status,e.method,t));var a,d,f,g,m,v=i({},(a=e.status,d=e.statusText,f=e.body,g=s.get("responseRule"),m=(null==n?void 0:n.responseRule)||g,a>=200&&a<400?function(e,t,s,n){var o=e||{resolve:"body"},a={ok:!0,code:s,message:"",data:null};if(202===t||204===t||!n)return a;if("body"===o.resolve)return a.data=r.isJsonLike(n)?r.parseJSON(n):n,a;var i=r.parseJSON(n);if(!i||!r.isStringRecord(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var c=o.statusField||"code",l=o.statusOKValue||"0",h=o.dataField||"data",d=o.messageField||u,f=o.ignoreMessage||"";if(!(c in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+c,a;var g=i[c]+"";return a.ok=g===l,a.code=g,a.message=d in i?i[d]+"":"",a.data=h in i?i[h]:null,f&&a.message&&(Array.isArray(f)&&f.includes(a.message)||"string"==typeof f&&a.message===f)&&(a.message=""),a}(m.ok||g.ok,a,d,f):function(e,t,r){var s=e||{resolve:"json",messageField:u},n={ok:!1,code:t,message:r,data:null};switch(s.resolve){case"auto":n.message=l(r)||c(r,s.messageField)||r;break;case"body":n.message=l(r)||r;break;case"json":n.message=c(r,s.messageField)}return n}(m.failed||g.failed,d,f)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return h(v,v.ok?v.message:e.method+" "+t+" ["+v.code+"] "+(v.message||e.statusText),e.method,t,s,n)}(n,e,t,s)})}catch(e){return Promise.reject(e)}},g=function(e,t,s){try{var a=function(e,t,r){var s=Object.assign({method:"GET"},r),n=s.body instanceof FormData,o=n?"POST":s.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=Object.assign(n?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:d(s.body),params:c,headers:a,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}(e,t,s);if(!r.isFullURL(e))return Promise.resolve({url:e,method:a.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var i=/^https:\/\//i.test(e)?o.default:n.default,u=new URL(e),c=a.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===a.method;return Promise.resolve(new Promise(function(t){var r=i.request(u,{headers:a.headers,method:a.method,timeout:a.timeout>0?a.timeout:void 0},function(r){var s=[];l||r.on("data",function(e){return s.push(e)}),r.on("end",function(){var n=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));t({url:e,method:a.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:n,body:l?"":Buffer.concat(s).toString("utf-8")})})});r.on("error",function(r){t({url:e,method:a.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),a.body&&r.write(a.body),r.end()}))}catch(e){return Promise.reject(e)}},m=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),v=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!r.isFullURL(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?r.getFullURL(e):r.getFullURL(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),y=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new v(t),this.agent=e,this.cache=new m(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,s){try{return Promise.resolve(function(e,t,s,n){if(t.ok&&!r.isEmpty(t.data)&&null!==n){var o=r.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(t.data))return t;console.error("response type check faild",e,t.data),s.showMessage(!0,e+" "+o.message)}return t.data=null,t}(e,t,this.config,s))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function p(e){return new y(f,e)}var b=p(),j=b.setConfig,P=b.head,x=b.get,O=b.post,R=b.del,T=b.put,w=b.patch;exports.NetRequest=p,exports.del=R,exports.get=x,exports.head=P,exports.patch=w,exports.post=O,exports.put=T,exports.setGlobalConfig=j;
package/dist/node.mjs CHANGED
@@ -1 +1 @@
1
- import{noop as e,sleep as t,isJsonLike as r,parseJSON as n,isStringRecord as s,isFullURL as o,isEmpty as a,getTypeGuard as i,getFullURL as u}from"@seayoo-web/utils";import c from"node:http";import l from"node:https";var h=function r(n,s,o,a,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||e;f({type:"prepear",url:s,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:a});var m=Date.now();return Promise.resolve(n(s,o,a)).then(function(e){var i,u=e.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?e.body:"");if(f({type:"finished",url:s,method:e.method,retry:l,maxRetry:h,message:0===l?"finish "+g:"retry "+l+"/"+h+" finish "+g,response:e,cost:c}),!h||"network"===d&&u>0||"status"===d&&u>=200&&u<400||l>=h)return e;var v=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(t(Math.max(100,"function"==typeof v?v(l+1):v))).then(function(){return Promise.resolve(r(n,s,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d.apply(this,arguments)}var f="message";function m(e,t){if(void 0===t&&(t=f),!r(e))return"";var o,a=n(e);return a&&s(a)&&t in a?(o=a[t])?"string"==typeof o?o:JSON.stringify(o):"":e}function g(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function v(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function y(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var p=function(e,t,r){try{var n=function(e,t,r){var n=Object.assign({method:"GET"},r),s=n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=n.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:y(n.body),params:c,headers:a,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}(e,t,r);if(!o(e))return Promise.resolve({url:e,method:n.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var s=/^https:\/\//i.test(e)?l:c,a=new URL(e),i=n.params;i instanceof Object&&Object.keys(i).forEach(function(e){return a.searchParams.set(e,i[e])});var u="HEAD"===n.method;return Promise.resolve(new Promise(function(t){var r=s.request(a,{headers:n.headers,method:n.method,timeout:n.timeout>0?n.timeout:void 0},function(r){var s=[];u||r.on("data",function(e){return s.push(e)}),r.on("end",function(){var o=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));t({url:e,method:n.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:o,body:u?"":Buffer.concat(s).toString("utf-8")})})});r.on("error",function(r){t({url:e,method:n.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),n.body&&r.write(n.body),r.end()}))}catch(e){return Promise.reject(e)}},b=function(e,t,o){try{return Promise.resolve(h(p,e,t,o)).then(function(a){return function(e,t,o,a){if(e.status<0)return v({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);var i;(e.status<200||e.status>=400)&&(null==(i=o.get("errorHandler"))||i(e.status,e.method,t));var u,c,l,h,y,p=d({},(u=e.status,c=e.statusText,l=e.body,h=o.get("responseRule"),y=(null==a?void 0:a.responseRule)||h,u>=200&&u<400?function(e,t,o,a){var i=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!a)return u;if("body"===i.resolve)return u.data=r(a)?n(a):a,u;var c=n(a);if(!c||!s(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField||"code",h=i.statusOKValue||"0",d=i.dataField||"data",m=i.messageField||f,g=i.ignoreMessage||"";if(!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=c[l]+"";return u.ok=v===h,u.code=v,u.message=m in c?c[m]+"":"",u.data=d in c?c[d]:null,g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(y.ok||h.ok,u,c,l):function(e,t,r){var n=e||{resolve:"json",messageField:f},s={ok:!1,code:t,message:r,data:null};switch(n.resolve){case"auto":s.message=g(r)||m(r,n.messageField)||r;break;case"body":s.message=g(r)||r;break;case"json":s.message=m(r,n.messageField)}return s}(y.failed||h.failed,c,l)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return v(p,p.ok?p.message:e.method+" "+t+" ["+p.code+"] "+(p.message||e.statusText),e.method,t,o,a)}(a,e,t,o)})}catch(e){return Promise.reject(e)}},j=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),P=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!o(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?u(e):u(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(t),this.agent=e,this.cache=new j(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!a(t.data)&&null!==n){var s=i(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,t}(e,t,this.config,r))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function w(e){return new T(b,e)}var O=w(),x=O.setConfig,R=O.head,k=O.get,E=O.post,L=O.del,U=O.put,F=O.patch;export{w as NetRequest,L as del,k as get,R as head,F as patch,E as post,U as put,x as setGlobalConfig};
1
+ import e from"node:http";import t from"node:https";import{noop as r,sleep as n,isJsonLike as s,parseJSON as o,isStringRecord as a,isFullURL as i,isEmpty as u,getTypeGuard as c,getFullURL as l}from"@seayoo-web/utils";var h=function e(t,s,o,a,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||r;f({type:"prepear",url:s,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:a});var m=Date.now();return Promise.resolve(t(s,o,a)).then(function(r){var i,u=r.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?r.body:"");if(f({type:"finished",url:s,method:r.method,retry:l,maxRetry:h,message:0===l?"finish "+g:"retry "+l+"/"+h+" finish "+g,response:r,cost:c}),!h||"network"===d&&u>0||"status"===d&&u>=200&&u<400||l>=h)return r;var v=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(n(Math.max(100,"function"==typeof v?v(l+1):v))).then(function(){return Promise.resolve(e(t,s,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d.apply(this,arguments)}var f="message";function m(e,t){if(void 0===t&&(t=f),!s(e))return"";var r,n=o(e);return n&&a(n)&&t in n?(r=n[t])?"string"==typeof r?r:JSON.stringify(r):"":e}function g(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function v(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function y(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var p=function(e,t,r){try{return Promise.resolve(h(b,e,t,r)).then(function(n){return function(e,t,r,n){if(e.status<0)return v({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,r,n);var i;(e.status<200||e.status>=400)&&(null==(i=r.get("errorHandler"))||i(e.status,e.method,t));var u,c,l,h,y,p=d({},(u=e.status,c=e.statusText,l=e.body,h=r.get("responseRule"),y=(null==n?void 0:n.responseRule)||h,u>=200&&u<400?function(e,t,r,n){var i=e||{resolve:"body"},u={ok:!0,code:r,message:"",data:null};if(202===t||204===t||!n)return u;if("body"===i.resolve)return u.data=s(n)?o(n):n,u;var c=o(n);if(!c||!a(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField||"code",h=i.statusOKValue||"0",d=i.dataField||"data",m=i.messageField||f,g=i.ignoreMessage||"";if(!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=c[l]+"";return u.ok=v===h,u.code=v,u.message=m in c?c[m]+"":"",u.data=d in c?c[d]:null,g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(y.ok||h.ok,u,c,l):function(e,t,r){var n=e||{resolve:"json",messageField:f},s={ok:!1,code:t,message:r,data:null};switch(n.resolve){case"auto":s.message=g(r)||m(r,n.messageField)||r;break;case"body":s.message=g(r)||r;break;case"json":s.message=m(r,n.messageField)}return s}(y.failed||h.failed,c,l)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return v(p,p.ok?p.message:e.method+" "+t+" ["+p.code+"] "+(p.message||e.statusText),e.method,t,r,n)}(n,e,t,r)})}catch(e){return Promise.reject(e)}},b=function(r,n,s){try{var o=function(e,t,r){var n=Object.assign({method:"GET"},r),s=n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=n.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:y(n.body),params:c,headers:a,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}(r,n,s);if(!i(r))return Promise.resolve({url:r,method:o.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var a=/^https:\/\//i.test(r)?t:e,u=new URL(r),c=o.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===o.method;return Promise.resolve(new Promise(function(e){var t=a.request(u,{headers:o.headers,method:o.method,timeout:o.timeout>0?o.timeout:void 0},function(t){var n=[];l||t.on("data",function(e){return n.push(e)}),t.on("end",function(){var s=Object.fromEntries(Object.entries(t.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:r,method:o.method,status:t.statusCode||-3,statusText:t.statusMessage||"Unknown",headers:s,body:l?"":Buffer.concat(n).toString("utf-8")})})});t.on("error",function(t){e({url:r,method:o.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),o.body&&t.write(o.body),t.end()}))}catch(e){return Promise.reject(e)}},j=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),P=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!i(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?l(e):l(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(t),this.agent=e,this.cache=new j(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!u(t.data)&&null!==n){var s=c(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,t}(e,t,this.config,r))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function w(e){return new T(p,e)}var O=w(),x=O.setConfig,R=O.head,k=O.get,E=O.post,L=O.del,U=O.put,F=O.patch;export{w as NetRequest,L as del,k as get,R as head,F as patch,E as post,U as put,x as setGlobalConfig};
package/dist/wx.cjs ADDED
@@ -0,0 +1 @@
1
+ var e=require("@seayoo-web/utils");function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},t.apply(this,arguments)}var r=function t(r,s,n,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:n.get("maxRetry")),h=null!=(u=null==o?void 0:o.retryResolve)?u:n.get("retryResolve"),d=n.get("logHandler")||e.noop;d({type:"prepear",url:s,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var g=Date.now();return Promise.resolve(r(s,n,o)).then(function(a){var i,u=a.status,f=Date.now()-g,m="[cost "+f+"]["+u+"] "+(u<0?a.body:"");if(d({type:"finished",url:s,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+m:"retry "+c+"/"+l+" finish "+m,response:a,cost:f}),!l||"network"===h&&u>0||"status"===h&&u>=200&&u<400||c>=l)return a;var v=null!=(i=null==o?void 0:o.retryInterval)?i:n.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof v?v(c+1):v))).then(function(){return Promise.resolve(t(r,s,n,o,c+1))})})}catch(e){return Promise.reject(e)}},s="message";function n(t,r){if(void 0===r&&(r=s),!e.isJsonLike(t))return"";var n,o=e.parseJSON(t);return o&&e.isStringRecord(o)&&r in o?(n=o[r])?"string"==typeof n?n:JSON.stringify(n):"":t}function o(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function a(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function i(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var u=function(i,u,l){try{return Promise.resolve(r(c,i,u,l)).then(function(r){return function(r,i,u,c){if(r.status<0)return a({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+i+" "+r.statusText,r.method,i,u,c);var l;(r.status<200||r.status>=400)&&(null==(l=u.get("errorHandler"))||l(r.status,r.method,i));var h,d,g,f,m,v=t({},(h=r.status,d=r.statusText,g=r.body,f=u.get("responseRule"),m=(null==c?void 0:c.responseRule)||f,h>=200&&h<400?function(t,r,n,o){var a=t||{resolve:"body"},i={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!o)return i;if("body"===a.resolve)return i.data=e.isJsonLike(o)?e.parseJSON(o):o,i;var u=e.parseJSON(o);if(!u||!e.isStringRecord(u))return i.ok=!1,i.code="ResponseFormatError",i.message="响应内容无法格式化为 Object",i;var c=a.statusField||"code",l=a.statusOKValue||"0",h=a.dataField||"data",d=a.messageField||s,g=a.ignoreMessage||"";if(!(c in u))return i.ok=!1,i.code="ResponseFieldMissing",i.message="响应内容找不到状态字段 "+c,i;var f=u[c]+"";return i.ok=f===l,i.code=f,i.message=d in u?u[d]+"":"",i.data=h in u?u[h]:null,g&&i.message&&(Array.isArray(g)&&g.includes(i.message)||"string"==typeof g&&i.message===g)&&(i.message=""),i}(m.ok||f.ok,h,d,g):function(e,t,r){var a=e||{resolve:"json",messageField:s},i={ok:!1,code:t,message:r,data:null};switch(a.resolve){case"auto":i.message=o(r)||n(r,a.messageField)||r;break;case"body":i.message=o(r)||r;break;case"json":i.message=n(r,a.messageField)}return i}(m.failed||f.failed,d,g)),{status:r.status,headers:Object.fromEntries(Object.entries(r.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return a(v,v.ok?v.message:r.method+" "+i+" ["+v.code+"] "+(v.message||r.statusText),r.method,i,u,c)}(r,i,u,l)})}catch(e){return Promise.reject(e)}},c=function(r,s,n){try{var o=function(e,t,r){var s=Object.assign({method:"GET"},r),n=s.body instanceof FormData,o=n?"POST":s.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=Object.assign(n?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=t.get("headerHandler");u&&u(a,o,e);var c=s.params||{},l={};return Object.keys(c).forEach(function(e){var t;void 0!==c[e]&&(l[e]="string"==typeof(t=c[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:i(s.body),params:l,headers:a,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}(r,s,n),a="PATCH"===o.method?"POST":o.method,u=e.addParamsToString(s.getFullUrl(r),o.params);return globalThis.wx?Promise.resolve(new Promise(function(e){wx.request({url:u,data:o.body,header:o.headers,method:a,dataType:"string",responseType:"text",fail:function(){e({url:u,method:a,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(r){var s;e({url:u,method:a,status:r.statusCode,statusText:r.statusCode+"",headers:t({},r.header),body:(s=r.data,"string"==typeof s?s:s instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(s):JSON.stringify(s))})}})})):Promise.resolve({url:u,method:a,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"})}catch(e){return Promise.reject(e)}},l=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),h=/*#__PURE__*/function(){function t(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var r=t.prototype;return r.set=function(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!e.isFullURL(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)},r.get=function(e){return this.config[e]},r.getFullUrl=function(t){return t.startsWith("/")?e.getFullURL(t):e.getFullURL(t,this.config.baseURL)},r.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},t}(),d=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new h(t),this.agent=e,this.cache=new l(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this)}var r=t.prototype;return r.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},r.guard=function(t,r,s){try{return Promise.resolve(function(t,r,s,n){if(r.ok&&!e.isEmpty(r.data)&&null!==n){var o=e.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),s.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,s))}catch(e){return Promise.reject(e)}},r.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},r.getConfig=function(e){return this.config.get(e)},r.head=function(e,t){try{var r=this,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function g(e){return new d(u,e)}var f=g(),m=f.setConfig,v=f.head,y=f.get,p=f.post,b=f.del,T=f.put;exports.NetRequest=g,exports.del=b,exports.get=y,exports.head=v,exports.post=p,exports.put=T,exports.setGlobalConfig=m;
package/dist/wx.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { NetRequestHandler } from "./inc/main";
2
+ import type { IGlobalConfig } from "./inc/type";
3
+ export type { IGlobalConfig } from "./inc/type";
4
+ /**
5
+ * 创建新的实例空间,配置和缓存跟全局默认实例是隔离的
6
+ */
7
+ export declare function NetRequest(config?: IGlobalConfig): NetRequestHandler;
8
+ /**
9
+ * 设置全局默认的 Request Config
10
+ */
11
+ export declare const setGlobalConfig: (config: IGlobalConfig) => void;
12
+ /**
13
+ * 发送一个 HEAD 请求
14
+ */
15
+ export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithType<null>;
16
+ /**
17
+ * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景,可选 typeGuard 用于检查数据类型
18
+ */
19
+ export declare const get: {
20
+ (url: string): import("./inc/type").ResponseWithoutType;
21
+ (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
22
+ <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
23
+ };
24
+ /**
25
+ * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
26
+ */
27
+ export declare const post: {
28
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
29
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
30
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
31
+ };
32
+ /**
33
+ * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
34
+ */
35
+ export declare const del: {
36
+ (url: string): import("./inc/type").ResponseWithoutType;
37
+ (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
38
+ <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
39
+ };
40
+ /**
41
+ * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
42
+ */
43
+ export declare const put: {
44
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
45
+ (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
46
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
47
+ };
package/dist/wx.mjs ADDED
@@ -0,0 +1 @@
1
+ import{noop as e,sleep as t,isJsonLike as r,parseJSON as s,isStringRecord as n,addParamsToString as o,isEmpty as a,getTypeGuard as i,isFullURL as u,getFullURL as c}from"@seayoo-web/utils";function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},l.apply(this,arguments)}var h=function r(s,n,o,a,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||e;f({type:"prepear",url:n,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:a});var g=Date.now();return Promise.resolve(s(n,o,a)).then(function(e){var i,u=e.status,c=Date.now()-g,m="[cost "+c+"]["+u+"] "+(u<0?e.body:"");if(f({type:"finished",url:n,method:e.method,retry:l,maxRetry:h,message:0===l?"finish "+m:"retry "+l+"/"+h+" finish "+m,response:e,cost:c}),!h||"network"===d&&u>0||"status"===d&&u>=200&&u<400||l>=h)return e;var v=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(t(Math.max(100,"function"==typeof v?v(l+1):v))).then(function(){return Promise.resolve(r(s,n,o,a,l+1))})})}catch(e){return Promise.reject(e)}},d="message";function f(e,t){if(void 0===t&&(t=d),!r(e))return"";var o,a=s(e);return a&&n(a)&&t in a?(o=a[t])?"string"==typeof o?o:JSON.stringify(o):"":e}function g(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function m(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function v(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var y=function(e,t,o){try{return Promise.resolve(h(p,e,t,o)).then(function(a){return function(e,t,o,a){if(e.status<0)return m({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);var i;(e.status<200||e.status>=400)&&(null==(i=o.get("errorHandler"))||i(e.status,e.method,t));var u,c,h,v,y,p=l({},(u=e.status,c=e.statusText,h=e.body,v=o.get("responseRule"),y=(null==a?void 0:a.responseRule)||v,u>=200&&u<400?function(e,t,o,a){var i=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!a)return u;if("body"===i.resolve)return u.data=r(a)?s(a):a,u;var c=s(a);if(!c||!n(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField||"code",h=i.statusOKValue||"0",f=i.dataField||"data",g=i.messageField||d,m=i.ignoreMessage||"";if(!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=c[l]+"";return u.ok=v===h,u.code=v,u.message=g in c?c[g]+"":"",u.data=f in c?c[f]:null,m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(y.ok||v.ok,u,c,h):function(e,t,r){var s=e||{resolve:"json",messageField:d},n={ok:!1,code:t,message:r,data:null};switch(s.resolve){case"auto":n.message=g(r)||f(r,s.messageField)||r;break;case"body":n.message=g(r)||r;break;case"json":n.message=f(r,s.messageField)}return n}(y.failed||v.failed,c,h)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return m(p,p.ok?p.message:e.method+" "+t+" ["+p.code+"] "+(p.message||e.statusText),e.method,t,o,a)}(a,e,t,o)})}catch(e){return Promise.reject(e)}},p=function(e,t,r){try{var s=function(e,t,r){var s=Object.assign({method:"GET"},r),n=s.body instanceof FormData,o=n?"POST":s.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=Object.assign(n?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),i=t.get("headerHandler");i&&i(a,o,e);var u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),{method:o,body:v(s.body),params:c,headers:a,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}(e,t,r),n="PATCH"===s.method?"POST":s.method,a=o(t.getFullUrl(e),s.params);return globalThis.wx?Promise.resolve(new Promise(function(e){wx.request({url:a,data:s.body,header:s.headers,method:n,dataType:"string",responseType:"text",fail:function(){e({url:a,method:n,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(t){var r;e({url:a,method:n,status:t.statusCode,statusText:t.statusCode+"",headers:l({},t.header),body:(r=t.data,"string"==typeof r?r:r instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(r):JSON.stringify(r))})}})})):Promise.resolve({url:a,method:n,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"})}catch(e){return Promise.reject(e)}},b=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),P=/*#__PURE__*/function(){function e(e){this.config={baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}},e&&this.set(e)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!u(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?c(e):c(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(t),this.agent=e,this.cache=new b(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,s){if(t.ok&&!a(t.data)&&null!==s){var n=i(s,"响应数据未能正确识别");if(n.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+n.message)}return t.data=null,t}(e,t,this.config,r))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function j(e){return new T(y,e)}var x=j(),w=x.setConfig,O=x.head,k=x.get,R=x.post,E=x.del,L=x.put;export{j as NetRequest,E as del,k as get,O as head,R as post,L as put,w as setGlobalConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -17,6 +17,11 @@
17
17
  "types": "./dist/node.d.ts",
18
18
  "default": "./dist/node.mjs",
19
19
  "require": "./dist/node.cjs"
20
+ },
21
+ "./wx": {
22
+ "types": "./dist/wx.d.ts",
23
+ "default": "./dist/wx.mjs",
24
+ "require": "./dist/wx.cjs"
20
25
  }
21
26
  },
22
27
  "publishConfig": {
@@ -1,5 +0,0 @@
1
- import type { NetRequestCoreFn } from "./type";
2
- /**
3
- * 基于 node 自带的 http 包的网络请求包装函数,其中 url 必须是完整 url 地址
4
- */
5
- export declare const coreNodeRequest: NetRequestCoreFn;