@jetlinks-web/core 2.2.15 → 2.2.17
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/dist/index.mjs +3 -3
- package/index.ts +6 -6
- package/package.json +4 -4
- package/src/fetch.ts +233 -233
- package/src/locales.ts +7 -7
- package/src/router.ts +7 -7
- package/src/stores.ts +10 -10
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{TOKEN_KEY as
|
|
2
|
-
`);for(let p=0;p<f.length-1;++p){let
|
|
3
|
-
`);for(let p=0;p<f.length-1;++p){let
|
|
1
|
+
import{TOKEN_KEY as S,BASE_API as B,LOCAL_BASE_API as U}from"@jetlinks-web/constants";import{getToken as j,randomString as J}from"@jetlinks-web/utils";import G from"axios";import{isFunction as T,isObject as Y}from"lodash-es";var h,a={filter_url:[],code:200,codeKey:"status",timeout:1e3*15,handleRequest:void 0,handleResponse:void 0,handleError:void 0,langKey:"lang",requestOptions:s=>({}),tokenExpiration:()=>{},handleReconnect:()=>Promise.resolve(),isCreateTokenRefresh:!1},w=[],E=!1,be=window.__MICRO_APP_ENVIRONMENT__,y=new Map,F=s=>{let e=J(32);y.has(e)&&y.get(e)?.abort();let t=new AbortController;s.signal=t.signal,s.__requestKey=e,y.set(e,t)},V=s=>{F(s);let e=j(),t=localStorage.getItem(a.langKey),r=localStorage.getItem(U);if(t&&(s.headers[a.langKey]=t),r&&!s.baseURL){let n=s.url.startsWith("/")?s.url:`/${s.url}`;s.url=r+n}if(!e&&!a.filter_url?.some(n=>s.url?.includes(n)))return a.tokenExpiration?.(),s;if(s.headers[S]||(s.headers[S]=e),a.requestOptions&&T(a.requestOptions)){let n=a.requestOptions(s);if(n&&Y(n))for(let i in n)s[i]=n[i]}return s},z=s=>{if(a.handleResponse&&T(a.handleResponse))return a.handleResponse(s);let e=s.config?.__requestKey;if(e&&y.delete(e),s.data instanceof ArrayBuffer)return s;let t=s.data[a.codeKey||"status"];return typeof s.data=="object"&&typeof s.data.success>"u"&&(s.data.success=t===a.code),s.data},X=async s=>{let e=s.config;if(E)return new Promise((t,r)=>{w.push({resolve:t,reject:r})}).then(t=>(e.headers[S]=t,h(e))).catch(t=>Promise.reject(t));e._retry=!0,E=!0;try{if(await a.handleReconnect?.()){let r=j();return e.headers[S]=r,w.forEach(n=>n.resolve(r)),h(e)}}catch(t){throw w.forEach(r=>r.reject(t)),t}finally{w=[],E=!1}},M=async s=>{let e=s.response?.message||"Error",t=0;if(s.response){let{data:r,status:n}=s.response;switch(t=n,n){case 400:case 403:case 500:e=`${r?.message}`.substring(0,90);break;case 401:if(e=s.response.data.result?.text||"\u7528\u6237\u672A\u767B\u5F55",a.tokenExpiration?.(s),a.isCreateTokenRefresh)return X(s);break;case 404:e=s?.response?.data?.message||`${r?.error} ${r?.path}`;break;default:break}}else s.response===void 0&&(e=s.message.includes("timeout")?"\u63A5\u53E3\u54CD\u5E94\u8D85\u65F6":s.message,t="timeout");return a.handleError&&T(a.handleError)&&a.handleError(e,t,s),Promise.reject(s)},ye=()=>{y.forEach(s=>s.abort()),y.clear()},Re=s=>{s&&(a=Object.assign(a,s)),h=G.create({withCredentials:!1,timeout:a.timeout,baseURL:B}),h.interceptors.request.use(V,M),h.interceptors.response.use(z,M)},W=(s,e={},t)=>h({method:"POST",url:s,data:e,...t}),P=(s,e=void 0,t)=>h({method:"GET",url:s,params:e,...t}),N=(s,e={},t)=>h({method:"PUT",url:s,data:e,...t}),_=(s,e={},t)=>h({method:"patch",url:s,data:e,...t}),q=(s,e=void 0,t)=>h({method:"DELETE",url:s,params:e,...t}),Z=(s,e,t)=>P(s,e,{responseType:"arraybuffer",...t}),ee=(s,e,t)=>W(s,e,{responseType:"arraybuffer",...t}),x={post:W,get:P,put:N,patch:_,remove:q,getStream:Z,postStream:ee},I=class{modulePath;constructor(e){this.modulePath=e}page(e={},t={url:void 0,method:void 0}){let{url:r="/_query",method:n="post",...i}=t;return x[n](`${this.modulePath}${r}`,e,i)}noPage(e={},t={url:void 0,method:void 0}){let{url:r="/_query/no-page",method:n="post",...i}=t;return x[n](`${this.modulePath}${r}`,{paging:!1,...e},i)}detail(e,t,r={url:void 0,method:void 0}){let{url:n=`/${e}/detail`,method:i="get",...d}=r;return x[i](`${this.modulePath}${n}`,t,d)}save(e={},t={url:void 0,method:void 0}){let{url:r="/_create",method:n="post",...i}=t;return x[n](`${this.modulePath}${r}`,e,i)}update(e={},t={url:void 0,method:void 0}){let{url:r="/_update",method:n="patch",...i}=t;return _(`${this.modulePath}${r}`,e,i)}delete(e,t,r={url:void 0,method:void 0}){let{url:n=`/${e}`,method:i="post",...d}=r;return q(`${this.modulePath}${n}`,t,d)}post(...e){let[t,r,n]=e;return W(`${this.modulePath}${t}`,r,n)}get(...e){let[t,r,n]=e;return P(`${this.modulePath}${t}`,r,n)}put(...e){let[t,r,n]=e;return N(`${this.modulePath}${t}`,r,n)}patch(...e){let[t,r,n]=e;return _(`${this.modulePath}${t}`,r,n)}remove(...e){let[t,r,n]=e;return q(`${this.modulePath}${t}`,r,n)}};import{getToken as te}from"@jetlinks-web/utils";import{BASE_API as se,TOKEN_KEY as K}from"@jetlinks-web/constants";import{isFunction as L,isObject as H}from"lodash-es";import{Observable as Q}from"rxjs";var v=class{options={code:200,codeKey:"status"};isRead=!1;controller=null;constructor(){}create(e){this.options=Object.assign(this.options,e)}getUrl(e){return se+e}get(e,t="{}",r={}){let n=this.getUrl(e),i=this,d=this.controller=new AbortController;return new Q(o=>{let u;return fetch(n,{method:"GET",signal:d.signal,keepalive:!0,...r,...this.handleRequest(n)}).then(g=>{u=g.body?.getReader();let k=new TextDecoder,l="";if(!u){o.error(new Error("No readable stream available"));return}let R=()=>{if(!i.isRead){u.cancel(),o.complete();return}u.read().then(({done:b,value:A})=>{if(b){if(l.trim().length>0)try{o.next(JSON.parse(l.trim()))}catch(p){o.error(p)}o.complete();return}let C=k.decode(A,{stream:!0});l+=C;let f=l.split(`
|
|
2
|
+
`);for(let p=0;p<f.length-1;++p){let m=f[p].trim();if(m.length>0)try{o.next(JSON.parse(m.startsWith("data:")?m.slice(5):m))}catch(O){o.error(O),u.cancel();return}}l=f[f.length-1],R()}).catch(b=>o.error(b))};i.isRead=!0,R()}).catch(g=>{o.error(g)}),()=>{i.cancel()}})}post(e,t={},r={}){let n=this.getUrl(e),i=this,d=this.controller=new AbortController;return new Q(o=>{let u;return fetch(n,{method:"POST",signal:d.signal,keepalive:!0,body:H(t)?JSON.stringify(t):t,...r,...this.handleRequest(n)}).then(async g=>{u=g.body?.getReader();let k=new TextDecoder,l="";if(!u){o.error(new Error("No readable stream available"));return}let R=()=>{if(!i.isRead){u.cancel(),o.complete();return}u.read().then(({done:b,value:A})=>{if(b){if(l.trim().length>0)try{o.next(JSON.parse(l.trim()))}catch(p){o.error(p)}o.complete();return}let C=k.decode(A,{stream:!0});l+=C;let f=l.split(`
|
|
3
|
+
`);for(let p=0;p<f.length-1;++p){let m=f[p].trim();if(m.length>0)try{o.next(JSON.parse(m.startsWith("data:")?m.slice(5):m))}catch(O){o.error(O),u.cancel();return}}l=f[f.length-1],R()}).catch(b=>o.error(b))};i.isRead=!0,R()}).catch(g=>{o.error(g)}),()=>{i.cancel()}})}handleRequest(e){let t={headers:{"Content-Type":"application/x-ndjson"}},r=te();if(!r&&this.options.filter_url?.some(n=>n.includes(e)))return this.options.tokenExpiration?.(),t;if(t.headers[K]||(t.headers[K]=r),this.options.requestOptions&&L(this.options.requestOptions)){let n=this.options.requestOptions(t);if(n&&H(n))for(let i in n)t[i]=n[i]}return t}handleResponse(e){return this.options.handleResponse&&L(this.options.handleResponse)?this.options.handleResponse(e):e}cancel(){this.isRead&&(this.isRead=!1),this.controller.abort()}},Ce=new v;import{webSocket as ne}from"rxjs/webSocket";import{Observable as re,Subject as ie,timer as D,EMPTY as oe}from"rxjs";import{retry as ae,catchError as ce}from"rxjs/operators";import{notification as ue}from"ant-design-vue";var c=window.__MICRO_APP_ENVIRONMENT__,$=class{ws=null;subscriptions=new Map;pendingSubscriptions=new Map;heartbeatSubscription=null;reconnectAttempts=0;maxReconnectAttempts=2;isConnected=!1;tempQueue=[];url="";options={};wsClient;constructor(e){this.setOptions(e),this.setupConnectionMonitor(),c&&window.microApp.addGlobalDataListener(t=>{this.wsClient=t.wsClient})}setOptions(e){this.options=e||{}}initWebSocket(e){this.url=e}setupConnectionMonitor(){c||(window.addEventListener("online",()=>{console.log("Network is online, attempting to reconnect..."),this.reconnect()}),window.addEventListener("offline",()=>{console.log("Network is offline, caching subscriptions..."),this.cacheSubscriptions()}),window.addEventListener("beforeunload",()=>{this.disconnect()}))}getReconnectDelay(){return this.reconnectAttempts<=10?5e3:this.reconnectAttempts<=20?15e3:6e4}setupWebSocket(){if(c&&this.wsClient){this.wsClient.setupWebSocket();return}this.ws||!this.url||(this.ws=ne({url:this.url,openObserver:{next:()=>{console.log("WebSocket connected"),this.isConnected=!0,this.reconnectAttempts=0,this.startHeartbeat(),this.restoreSubscriptions(),this.processTempQueue()}},closeObserver:{next:()=>{console.log("WebSocket disconnected"),this.isConnected=!1;let e=this.getReconnectDelay();setTimeout(()=>{this.reconnectAttempts+=1,!(this.reconnectAttempts>this.maxReconnectAttempts)&&(this.cacheSubscriptions(),this.stopHeartbeat(),this.reconnect())},e)}}}),this.ws.pipe(ce(e=>(console.error("WebSocket error:",e),oe)),ae({delay:(e,t)=>{if(this.reconnectAttempts=t,t>this.maxReconnectAttempts)throw new Error("Max reconnection attempts reached");return D(this.getReconnectDelay())}})).subscribe(e=>this.handleMessage(e),e=>console.error("WebSocket error:",e)))}startHeartbeat(){if(c&&this.wsClient){this.wsClient.startHeartbeat();return}this.stopHeartbeat(),this.heartbeatSubscription=D(0,2e3).subscribe(()=>{this.send({type:"ping"})})}stopHeartbeat(){if(c&&this.wsClient){this.wsClient.stopHeartbeat();return}this.heartbeatSubscription&&(this.heartbeatSubscription.unsubscribe(),this.heartbeatSubscription=null)}handleMessage(e){if(c&&this.wsClient){this.wsClient.handleMessage(e);return}if(e.type==="pong")return;if(e.type==="error"){this.options.onError?this.options.onError(e):ue.error({key:"error",message:e.message});return}let t=this.subscriptions.get(e.requestId||"");t&&(e.type==="complete"?(t.complete(),this.subscriptions.delete(e.requestId||"")):e.type==="result"&&t.next(e))}processTempQueue(){if(c&&this.wsClient){this.wsClient.processTempQueue();return}for(;this.tempQueue.length>0;){let e=this.tempQueue.shift();e&&this.send(e)}}cacheSubscriptions(){if(c&&this.wsClient){this.wsClient.cacheSubscriptions();return}this.pendingSubscriptions=new Map(this.subscriptions),this.subscriptions.clear()}restoreSubscriptions(){if(c&&this.wsClient){this.wsClient.restoreSubscriptions();return}this.pendingSubscriptions.forEach((e,t)=>{this.subscriptions.set(t,e)}),this.pendingSubscriptions.clear()}reconnect(){if(c&&this.wsClient){this.wsClient.reconnect();return}!this.isConnected&&navigator.onLine&&(this.ws=null,this.setupWebSocket())}connect(){if(c&&this.wsClient){this.wsClient.connect();return}this.setupWebSocket()}disconnect(){if(c&&this.wsClient){this.wsClient.disconnect();return}this.ws&&(this.ws.complete(),this.ws=null),this.stopHeartbeat(),this.subscriptions.clear(),this.pendingSubscriptions.clear(),this.tempQueue=[]}send(e){if(c&&this.wsClient){this.wsClient.send(e);return}this.ws&&this.isConnected?this.ws.next(e):this.tempQueue.push(e)}getWebSocket(e,t,r={}){if(console.log("getWebSocket",this.wsClient,e),c&&this.wsClient)return this.wsClient.getWebSocket(e,t,r);let n=new ie;this.subscriptions.set(e,n);let i={id:e,topic:t,parameter:r,type:"sub"};return this.send(i),new re(d=>{let o=n.subscribe(d);return()=>{o.unsubscribe(),this.send({id:e,type:"unsub"}),this.subscriptions.delete(e)}})}},Pe=new $;var le,$e=s=>{le=s};var pe={},Ie=(s={})=>{pe=s};var he,Ne=s=>{he=s};export{v as NdJson,I as Request,$ as WebSocketClient,ye as abortAllRequests,Re as crateAxios,P as get,Z as getStream,Ne as installLocales,$e as installRouter,Ie as installStores,he as locales,Ce as ndJson,_ as patch,W as post,ee as postStream,N as put,q as remove,x as request,le as router,pe as stores,Pe as wsClient};
|
package/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export * from './src/axios'
|
|
2
|
-
export * from './src/fetch'
|
|
3
|
-
export * from './src/websocket'
|
|
4
|
-
export * from './src/router'
|
|
5
|
-
export * from './src/stores'
|
|
6
|
-
export * from './src/locales'
|
|
1
|
+
export * from './src/axios'
|
|
2
|
+
export * from './src/fetch'
|
|
3
|
+
export * from './src/websocket'
|
|
4
|
+
export * from './src/router'
|
|
5
|
+
export * from './src/stores'
|
|
6
|
+
export * from './src/locales'
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jetlinks-web/core",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.17",
|
|
4
4
|
"main": "dist/index.mjs",
|
|
5
5
|
"module": "dist/index.mjs",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -28,9 +28,9 @@
|
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"axios": "^1.7.4",
|
|
30
30
|
"rxjs": "^7.8.1",
|
|
31
|
-
"@jetlinks-web/
|
|
32
|
-
"@jetlinks-web/
|
|
33
|
-
"@jetlinks-web/utils": "
|
|
31
|
+
"@jetlinks-web/types": "1.0.2",
|
|
32
|
+
"@jetlinks-web/constants": "1.0.9",
|
|
33
|
+
"@jetlinks-web/utils": "1.2.14"
|
|
34
34
|
},
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"registry": "https://registry.npmjs.org/",
|
package/src/fetch.ts
CHANGED
|
@@ -1,233 +1,233 @@
|
|
|
1
|
-
import {getToken} from "@jetlinks-web/utils";
|
|
2
|
-
import {BASE_API, TOKEN_KEY} from "@jetlinks-web/constants";
|
|
3
|
-
import {isFunction, isObject} from "lodash-es";
|
|
4
|
-
import { Observable, } from 'rxjs'
|
|
5
|
-
|
|
6
|
-
export class NdJson {
|
|
7
|
-
options: any = {
|
|
8
|
-
code: 200,
|
|
9
|
-
codeKey: 'status'
|
|
10
|
-
}
|
|
11
|
-
isRead = false
|
|
12
|
-
controller = null
|
|
13
|
-
constructor() {}
|
|
14
|
-
|
|
15
|
-
create(options) {
|
|
16
|
-
this.options = Object.assign(this.options, options)
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
getUrl(url) {
|
|
20
|
-
return BASE_API + url
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
get(url, data = '{}', extra = {}) {
|
|
24
|
-
const _url = this.getUrl(url)
|
|
25
|
-
const that = this
|
|
26
|
-
const controller = this.controller = new AbortController();
|
|
27
|
-
|
|
28
|
-
return new Observable(observer => {
|
|
29
|
-
let reader
|
|
30
|
-
fetch(
|
|
31
|
-
_url,
|
|
32
|
-
{
|
|
33
|
-
method: 'GET',
|
|
34
|
-
signal: controller.signal,
|
|
35
|
-
keepalive: true,
|
|
36
|
-
...extra,
|
|
37
|
-
...this.handleRequest(_url)
|
|
38
|
-
}
|
|
39
|
-
).then(resp => {
|
|
40
|
-
reader = resp.body?.getReader();
|
|
41
|
-
const decoder = new TextDecoder();
|
|
42
|
-
let data_buf = "";
|
|
43
|
-
|
|
44
|
-
if (!reader) {
|
|
45
|
-
observer.error(new Error('No readable stream available'));
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const read = () => {
|
|
50
|
-
|
|
51
|
-
if (!that.isRead) {
|
|
52
|
-
reader.cancel()
|
|
53
|
-
observer.complete();
|
|
54
|
-
return
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
reader.read().then(({ done, value }) => {
|
|
58
|
-
if (done) {
|
|
59
|
-
if (data_buf.trim().length > 0) {
|
|
60
|
-
try {
|
|
61
|
-
observer.next(JSON.parse(data_buf.trim()));
|
|
62
|
-
} catch (e) {
|
|
63
|
-
observer.error(e);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
observer.complete();
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const data = decoder.decode(value, { stream: true });
|
|
71
|
-
data_buf += data;
|
|
72
|
-
|
|
73
|
-
let lines = data_buf.split('\n');
|
|
74
|
-
for (let i = 0; i < lines.length - 1; ++i) {
|
|
75
|
-
const line = lines[i].trim();
|
|
76
|
-
if (line.length > 0) {
|
|
77
|
-
try {
|
|
78
|
-
observer.next(JSON.parse(line));
|
|
79
|
-
} catch (e) {
|
|
80
|
-
observer.error(e);
|
|
81
|
-
reader.cancel();
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
data_buf = lines[lines.length - 1];
|
|
87
|
-
read();
|
|
88
|
-
}).catch(err => observer.error(err));
|
|
89
|
-
};
|
|
90
|
-
that.isRead = true
|
|
91
|
-
read();
|
|
92
|
-
}).catch(e => {
|
|
93
|
-
observer.error(e)
|
|
94
|
-
})
|
|
95
|
-
|
|
96
|
-
return () => {
|
|
97
|
-
that.cancel()
|
|
98
|
-
}
|
|
99
|
-
})
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
post(url, data: BodyInit | any ={}, extra = {}) {
|
|
103
|
-
const _url = this.getUrl(url)
|
|
104
|
-
const that = this
|
|
105
|
-
const controller = this.controller = new AbortController();
|
|
106
|
-
|
|
107
|
-
return new Observable(observer => {
|
|
108
|
-
let reader
|
|
109
|
-
fetch(
|
|
110
|
-
_url,
|
|
111
|
-
{
|
|
112
|
-
method: 'POST',
|
|
113
|
-
signal: controller.signal,
|
|
114
|
-
keepalive: true,
|
|
115
|
-
body: isObject(data) ? JSON.stringify(data) : data,
|
|
116
|
-
...extra,
|
|
117
|
-
...this.handleRequest(_url)
|
|
118
|
-
}
|
|
119
|
-
).then(async resp => {
|
|
120
|
-
reader = resp.body?.getReader();
|
|
121
|
-
const decoder = new TextDecoder();
|
|
122
|
-
let data_buf = "";
|
|
123
|
-
|
|
124
|
-
if (!reader) {
|
|
125
|
-
observer.error(new Error('No readable stream available'));
|
|
126
|
-
return;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
const read = () => {
|
|
130
|
-
|
|
131
|
-
if (!that.isRead) {
|
|
132
|
-
reader.cancel()
|
|
133
|
-
observer.complete();
|
|
134
|
-
return
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
reader.read().then(({ done, value }) => {
|
|
138
|
-
if (done) {
|
|
139
|
-
if (data_buf.trim().length > 0) {
|
|
140
|
-
try {
|
|
141
|
-
observer.next(JSON.parse(data_buf.trim()));
|
|
142
|
-
} catch (e) {
|
|
143
|
-
observer.error(e);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
observer.complete();
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
const data = decoder.decode(value, { stream: true });
|
|
151
|
-
data_buf += data
|
|
152
|
-
|
|
153
|
-
let lines = data_buf.split('\n');
|
|
154
|
-
for (let i = 0; i < lines.length - 1; ++i) {
|
|
155
|
-
const line = lines[i].trim();
|
|
156
|
-
if (line.length > 0) {
|
|
157
|
-
try {
|
|
158
|
-
observer.next(JSON.parse(line));
|
|
159
|
-
} catch (e) {
|
|
160
|
-
observer.error(e);
|
|
161
|
-
reader.cancel();
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
data_buf = lines[lines.length - 1];
|
|
167
|
-
read();
|
|
168
|
-
}).catch(err => observer.error(err));
|
|
169
|
-
};
|
|
170
|
-
that.isRead = true
|
|
171
|
-
read();
|
|
172
|
-
}).catch(e => {
|
|
173
|
-
observer.error(e)
|
|
174
|
-
})
|
|
175
|
-
|
|
176
|
-
return () => {
|
|
177
|
-
that.cancel()
|
|
178
|
-
}
|
|
179
|
-
})
|
|
180
|
-
}
|
|
181
|
-
handleRequest(url): RequestInit {
|
|
182
|
-
const config: RequestInit = {
|
|
183
|
-
headers: {
|
|
184
|
-
'Content-Type': 'application/x-ndjson',
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const token = getToken()
|
|
189
|
-
|
|
190
|
-
if (!token && this.options.filter_url?.some(_url => _url.includes(url))) {
|
|
191
|
-
this.options.tokenExpiration?.()
|
|
192
|
-
return config
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
if (!config.headers[TOKEN_KEY]) {
|
|
196
|
-
config.headers[TOKEN_KEY] = token
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
if (this.options.requestOptions && isFunction(this.options.requestOptions)) {
|
|
200
|
-
const extraOptions = this.options.requestOptions(config)
|
|
201
|
-
if (extraOptions && isObject(extraOptions)) {
|
|
202
|
-
for (const key in extraOptions) {
|
|
203
|
-
config[key] = extraOptions[key]
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
return config
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
handleResponse(response) {
|
|
212
|
-
|
|
213
|
-
if (this.options.handleResponse && isFunction(this.options.handleResponse)) {
|
|
214
|
-
return this.options.handleResponse(response)
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// const status = response[this.options.codeKey || 'status']
|
|
218
|
-
// response.success = status === this.options.code
|
|
219
|
-
|
|
220
|
-
return response
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
cancel() {
|
|
224
|
-
if (this.isRead) {
|
|
225
|
-
this.isRead = false
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
this.controller.abort()
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
export const ndJson = new NdJson()
|
|
1
|
+
import {getToken} from "@jetlinks-web/utils";
|
|
2
|
+
import {BASE_API, TOKEN_KEY} from "@jetlinks-web/constants";
|
|
3
|
+
import {isFunction, isObject} from "lodash-es";
|
|
4
|
+
import { Observable, } from 'rxjs'
|
|
5
|
+
|
|
6
|
+
export class NdJson {
|
|
7
|
+
options: any = {
|
|
8
|
+
code: 200,
|
|
9
|
+
codeKey: 'status'
|
|
10
|
+
}
|
|
11
|
+
isRead = false
|
|
12
|
+
controller = null
|
|
13
|
+
constructor() {}
|
|
14
|
+
|
|
15
|
+
create(options) {
|
|
16
|
+
this.options = Object.assign(this.options, options)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
getUrl(url) {
|
|
20
|
+
return BASE_API + url
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
get(url, data = '{}', extra = {}) {
|
|
24
|
+
const _url = this.getUrl(url)
|
|
25
|
+
const that = this
|
|
26
|
+
const controller = this.controller = new AbortController();
|
|
27
|
+
|
|
28
|
+
return new Observable(observer => {
|
|
29
|
+
let reader
|
|
30
|
+
fetch(
|
|
31
|
+
_url,
|
|
32
|
+
{
|
|
33
|
+
method: 'GET',
|
|
34
|
+
signal: controller.signal,
|
|
35
|
+
keepalive: true,
|
|
36
|
+
...extra,
|
|
37
|
+
...this.handleRequest(_url)
|
|
38
|
+
}
|
|
39
|
+
).then(resp => {
|
|
40
|
+
reader = resp.body?.getReader();
|
|
41
|
+
const decoder = new TextDecoder();
|
|
42
|
+
let data_buf = "";
|
|
43
|
+
|
|
44
|
+
if (!reader) {
|
|
45
|
+
observer.error(new Error('No readable stream available'));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const read = () => {
|
|
50
|
+
|
|
51
|
+
if (!that.isRead) {
|
|
52
|
+
reader.cancel()
|
|
53
|
+
observer.complete();
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
reader.read().then(({ done, value }) => {
|
|
58
|
+
if (done) {
|
|
59
|
+
if (data_buf.trim().length > 0) {
|
|
60
|
+
try {
|
|
61
|
+
observer.next(JSON.parse(data_buf.trim()));
|
|
62
|
+
} catch (e) {
|
|
63
|
+
observer.error(e);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
observer.complete();
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const data = decoder.decode(value, { stream: true });
|
|
71
|
+
data_buf += data;
|
|
72
|
+
|
|
73
|
+
let lines = data_buf.split('\n');
|
|
74
|
+
for (let i = 0; i < lines.length - 1; ++i) {
|
|
75
|
+
const line = lines[i].trim();
|
|
76
|
+
if (line.length > 0) {
|
|
77
|
+
try {
|
|
78
|
+
observer.next(JSON.parse(line.startsWith('data:') ? line.slice(5) : line));
|
|
79
|
+
} catch (e) {
|
|
80
|
+
observer.error(e);
|
|
81
|
+
reader.cancel();
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
data_buf = lines[lines.length - 1];
|
|
87
|
+
read();
|
|
88
|
+
}).catch(err => observer.error(err));
|
|
89
|
+
};
|
|
90
|
+
that.isRead = true
|
|
91
|
+
read();
|
|
92
|
+
}).catch(e => {
|
|
93
|
+
observer.error(e)
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
return () => {
|
|
97
|
+
that.cancel()
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
post(url, data: BodyInit | any ={}, extra = {}) {
|
|
103
|
+
const _url = this.getUrl(url)
|
|
104
|
+
const that = this
|
|
105
|
+
const controller = this.controller = new AbortController();
|
|
106
|
+
|
|
107
|
+
return new Observable(observer => {
|
|
108
|
+
let reader
|
|
109
|
+
fetch(
|
|
110
|
+
_url,
|
|
111
|
+
{
|
|
112
|
+
method: 'POST',
|
|
113
|
+
signal: controller.signal,
|
|
114
|
+
keepalive: true,
|
|
115
|
+
body: isObject(data) ? JSON.stringify(data) : data,
|
|
116
|
+
...extra,
|
|
117
|
+
...this.handleRequest(_url)
|
|
118
|
+
}
|
|
119
|
+
).then(async resp => {
|
|
120
|
+
reader = resp.body?.getReader();
|
|
121
|
+
const decoder = new TextDecoder();
|
|
122
|
+
let data_buf = "";
|
|
123
|
+
|
|
124
|
+
if (!reader) {
|
|
125
|
+
observer.error(new Error('No readable stream available'));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const read = () => {
|
|
130
|
+
|
|
131
|
+
if (!that.isRead) {
|
|
132
|
+
reader.cancel()
|
|
133
|
+
observer.complete();
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
reader.read().then(({ done, value }) => {
|
|
138
|
+
if (done) {
|
|
139
|
+
if (data_buf.trim().length > 0) {
|
|
140
|
+
try {
|
|
141
|
+
observer.next(JSON.parse(data_buf.trim()));
|
|
142
|
+
} catch (e) {
|
|
143
|
+
observer.error(e);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
observer.complete();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const data = decoder.decode(value, { stream: true });
|
|
151
|
+
data_buf += data;
|
|
152
|
+
|
|
153
|
+
let lines = data_buf.split('\n');
|
|
154
|
+
for (let i = 0; i < lines.length - 1; ++i) {
|
|
155
|
+
const line = lines[i].trim();
|
|
156
|
+
if (line.length > 0) {
|
|
157
|
+
try {
|
|
158
|
+
observer.next(JSON.parse(line.startsWith('data:') ? line.slice(5) : line));
|
|
159
|
+
} catch (e) {
|
|
160
|
+
observer.error(e);
|
|
161
|
+
reader.cancel();
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
data_buf = lines[lines.length - 1];
|
|
167
|
+
read();
|
|
168
|
+
}).catch(err => observer.error(err));
|
|
169
|
+
};
|
|
170
|
+
that.isRead = true
|
|
171
|
+
read();
|
|
172
|
+
}).catch(e => {
|
|
173
|
+
observer.error(e)
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
return () => {
|
|
177
|
+
that.cancel()
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
handleRequest(url): RequestInit {
|
|
182
|
+
const config: RequestInit = {
|
|
183
|
+
headers: {
|
|
184
|
+
'Content-Type': 'application/x-ndjson',
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const token = getToken()
|
|
189
|
+
|
|
190
|
+
if (!token && this.options.filter_url?.some(_url => _url.includes(url))) {
|
|
191
|
+
this.options.tokenExpiration?.()
|
|
192
|
+
return config
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (!config.headers[TOKEN_KEY]) {
|
|
196
|
+
config.headers[TOKEN_KEY] = token
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (this.options.requestOptions && isFunction(this.options.requestOptions)) {
|
|
200
|
+
const extraOptions = this.options.requestOptions(config)
|
|
201
|
+
if (extraOptions && isObject(extraOptions)) {
|
|
202
|
+
for (const key in extraOptions) {
|
|
203
|
+
config[key] = extraOptions[key]
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return config
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
handleResponse(response) {
|
|
212
|
+
|
|
213
|
+
if (this.options.handleResponse && isFunction(this.options.handleResponse)) {
|
|
214
|
+
return this.options.handleResponse(response)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// const status = response[this.options.codeKey || 'status']
|
|
218
|
+
// response.success = status === this.options.code
|
|
219
|
+
|
|
220
|
+
return response
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
cancel() {
|
|
224
|
+
if (this.isRead) {
|
|
225
|
+
this.isRead = false
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
this.controller.abort()
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
export const ndJson = new NdJson()
|
package/src/locales.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
let locales
|
|
2
|
-
|
|
3
|
-
const installLocales = (l) => {
|
|
4
|
-
locales = l
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export { locales, installLocales }
|
|
1
|
+
let locales
|
|
2
|
+
|
|
3
|
+
const installLocales = (l) => {
|
|
4
|
+
locales = l
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export { locales, installLocales }
|
package/src/router.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
let router
|
|
2
|
-
|
|
3
|
-
const installRouter = (r) => {
|
|
4
|
-
router = r
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export { router, installRouter }
|
|
1
|
+
let router
|
|
2
|
+
|
|
3
|
+
const installRouter = (r) => {
|
|
4
|
+
router = r
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export { router, installRouter }
|
package/src/stores.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
let stores = {}
|
|
2
|
-
|
|
3
|
-
const installStores = (_s = {}) => {
|
|
4
|
-
stores = _s
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export {
|
|
8
|
-
stores,
|
|
9
|
-
installStores
|
|
10
|
-
}
|
|
1
|
+
let stores = {}
|
|
2
|
+
|
|
3
|
+
const installStores = (_s = {}) => {
|
|
4
|
+
stores = _s
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
stores,
|
|
9
|
+
installStores
|
|
10
|
+
}
|