@jetlinks-web/core 2.0.3 → 2.0.5

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/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './src/axios'
2
+ export * from './src/fetch'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jetlinks-web/core",
3
- "version": "2.0.3",
3
+ "version": "2.0.5",
4
4
  "description": "",
5
5
  "main": "index.ts",
6
6
  "module": "index.ts",
@@ -17,8 +17,8 @@
17
17
  "dependencies": {
18
18
  "axios": "^1.7.4",
19
19
  "@jetlinks-web/types": "^1.0.2",
20
- "@jetlinks-web/utils": "^1.2.2",
21
- "@jetlinks-web/constants": "^1.0.5"
20
+ "@jetlinks-web/constants": "^1.0.7",
21
+ "@jetlinks-web/utils": "^1.2.5"
22
22
  },
23
23
  "publishConfig": {
24
24
  "registry": "https://registry.npmjs.org/",
package/src/axios.ts CHANGED
@@ -12,7 +12,7 @@ import {isFunction, isObject} from 'lodash-es'
12
12
 
13
13
  interface Options {
14
14
 
15
- tokenExpiration: () => void
15
+ tokenExpiration: (err: AxiosError<any>, response: AxiosResponse) => void
16
16
  filter_url?: Array<string>
17
17
  code?: number
18
18
  codeKey?: string
@@ -46,9 +46,10 @@ let _options: Options = {
46
46
  handleError: undefined,
47
47
  requestOptions: (config) => ({}),
48
48
  tokenExpiration: () => {},
49
-
50
49
  }
51
50
 
51
+ const controller = new AbortController();
52
+
52
53
  const handleRequest = (config: InternalAxiosRequestConfig) => {
53
54
  const token = getToken()
54
55
 
@@ -100,7 +101,7 @@ const handleResponse = (response: AxiosResponse) => {
100
101
  }
101
102
 
102
103
  const errorHandler = (err: AxiosError<any>) => {
103
- let description = 'Error'
104
+ let description = err.response?.message || 'Error'
104
105
  let _status: string | number = 0
105
106
  if (err.response) {
106
107
  const {data, status} = err.response
@@ -113,7 +114,7 @@ const errorHandler = (err: AxiosError<any>) => {
113
114
  break;
114
115
  case 401:
115
116
  description = '用户未登录'
116
- _options.tokenExpiration?.()
117
+ _options.tokenExpiration?.(err, err.response)
117
118
  break;
118
119
  default:
119
120
  break;
package/src/fetch.ts ADDED
@@ -0,0 +1,237 @@
1
+ import {getToken} from "@jetlinks-web/utils";
2
+ import {BASE_API, TOKEN_KEY} from "@jetlinks-web/constants";
3
+ import {isFunction, isObject, isString} from "lodash-es";
4
+
5
+ const controller = new AbortController();
6
+
7
+ class NdJson {
8
+ options: any = {
9
+ code: 200,
10
+ codeKey: 'status'
11
+ }
12
+ constructor() {}
13
+
14
+ create(options) {
15
+ this.options = Object.assign(this.options, options)
16
+ }
17
+
18
+ getUrl(url) {
19
+ return BASE_API + url
20
+ }
21
+
22
+ get(url, data = '{}', extra = {}) {
23
+
24
+ return new Promise((resolve, reject) => {
25
+ const _url = this.getUrl(url)
26
+
27
+ fetch(
28
+ _url,
29
+ {
30
+ method: 'GET',
31
+ signal: controller.signal,
32
+ keepalive: true,
33
+ ...extra,
34
+ ...this.handleRequest(_url)
35
+ }
36
+ ).then(resp => {
37
+ console.log('[fetch GET]>', resp)
38
+ let is_reader, cancellationRequest = false;
39
+
40
+ const readable = new ReadableStream({
41
+ start(controller) {
42
+ const reader = resp.body.getReader()
43
+ const decoder = new TextDecoder();
44
+ let data_buf = "";
45
+
46
+ is_reader = !!reader
47
+
48
+ reader.read().then(function processResult(result) {
49
+ if (result.done) {
50
+ if (cancellationRequest) {
51
+ return
52
+ }
53
+ data_buf = data_buf.trim()
54
+
55
+ if (data_buf.length !== 0) {
56
+ try {
57
+ controller.enqueue(JSON.parse(data_buf))
58
+ } catch (e) {
59
+ controller.error(e)
60
+ return
61
+ }
62
+ }
63
+
64
+ controller.close()
65
+ return
66
+ }
67
+
68
+ const data = decoder.decode(result.value, { stream: true })
69
+ data_buf += data
70
+
71
+ let lines = data_buf.split('/')
72
+ for(let i = 0; i < lines.length - 1; ++i) {
73
+ const l = lines[i].trim();
74
+ if (l.length > 0) {
75
+ try {
76
+ controller.enqueue(JSON.parse(l));
77
+ } catch(e) {
78
+ controller.error(e);
79
+ cancellationRequest = true;
80
+ reader.cancel();
81
+ return;
82
+ }
83
+ }
84
+ }
85
+ })
86
+ }
87
+ })
88
+
89
+ return resp.json()
90
+ })
91
+ .then((resp) => {
92
+ console.log(resp)
93
+ })
94
+ .catch(e => {
95
+ reject(e)
96
+ })
97
+ })
98
+ }
99
+
100
+ async post(url, data={}, extra = {}) {
101
+
102
+ return new Promise(async (resolve, reject) => {
103
+ const _url = this.getUrl(url)
104
+
105
+ fetch(
106
+ _url,
107
+ {
108
+ method: 'POST',
109
+ signal: controller.signal,
110
+ keepalive: true,
111
+ body: isObject(data) ? JSON.stringify(data) : data,
112
+ ...extra,
113
+ ...this.handleRequest(_url)
114
+ }
115
+ ).then(async resp => {
116
+ console.log('[fetch 1]>', resp.headers.get('content-type'))
117
+ let is_reader, cancellationRequest = false;
118
+
119
+ // return new ReadableStream({
120
+ // start(controller) {
121
+ // const reader = resp.body.getReader()
122
+ // const decoder = new TextDecoder();
123
+ // let data_buf = "";
124
+ //
125
+ // is_reader = !!reader
126
+ //
127
+ // reader.read().then(function processResult(result) {
128
+ // if (result.done) {
129
+ // if (cancellationRequest) {
130
+ // return
131
+ // }
132
+ // data_buf = data_buf.trim()
133
+ //
134
+ // if (data_buf.length !== 0) {
135
+ // try {
136
+ // controller.enqueue(JSON.parse(data_buf))
137
+ // } catch (e) {
138
+ // controller.error(e)
139
+ // return
140
+ // }
141
+ // }
142
+ //
143
+ // controller.close()
144
+ // return
145
+ // }
146
+ //
147
+ // const data = decoder.decode(result.value, { stream: true })
148
+ // data_buf += data
149
+ // console.log(data)
150
+ // let lines = data_buf.split('/')
151
+ // for(let i = 0; i < lines.length - 1; ++i) {
152
+ // const l = lines[i].trim();
153
+ // if (l.length > 0) {
154
+ // try {
155
+ // console.log(l)
156
+ // controller.enqueue( isString(l) ? JSON.parse(l) : l);
157
+ // } catch(e) {
158
+ // controller.error(e);
159
+ // cancellationRequest = true;
160
+ // reader.cancel();
161
+ // return;
162
+ // }
163
+ // }
164
+ // }
165
+ // })
166
+ // },
167
+ // cancel(reason) {
168
+ // console.log("Cancel registered due to ", reason);
169
+ // cancellationRequest = true;
170
+ // is_reader.cancel();
171
+ // }
172
+ // })
173
+ // let msg = await readable.getReader()
174
+ // console.log(resp, msg)
175
+ return resp.json()
176
+ })
177
+ .then((resp) => {
178
+ // const reader = resp.getReader();
179
+ // reader.read().then(result => {
180
+ // console.log(result)
181
+ // })
182
+ resolve(this.handleResponse(resp))
183
+ })
184
+ .catch(e => {
185
+ reject(e)
186
+ })
187
+ })
188
+ }
189
+ handleRequest(url): RequestInit {
190
+ const config: RequestInit = {
191
+ headers: {
192
+ 'Content-Type': 'application/x-ndjson',
193
+ }
194
+ }
195
+
196
+ const token = getToken()
197
+
198
+ if (!token && this.options.filter_url?.some(_url => _url.includes(url))) {
199
+ this.options.tokenExpiration?.()
200
+ return config
201
+ }
202
+
203
+ if (!config.headers[TOKEN_KEY]) {
204
+ config.headers[TOKEN_KEY] = token
205
+ }
206
+
207
+ if (this.options.requestOptions && isFunction(this.options.requestOptions)) {
208
+ const extraOptions = this.options.requestOptions(config)
209
+ if (extraOptions && isObject(extraOptions)) {
210
+ for (const key in extraOptions) {
211
+ config[key] = extraOptions[key]
212
+ }
213
+ }
214
+ }
215
+
216
+ return config
217
+ }
218
+
219
+ handleResponse(response) {
220
+
221
+ if (this.options.handleResponse && isFunction(this.options.handleResponse)) {
222
+ return this.options.handleResponse(response)
223
+ }
224
+
225
+ const status = response[this.options.codeKey || 'status']
226
+ response.success = status === this.options.code
227
+
228
+ return response
229
+ }
230
+
231
+ cancel() {
232
+
233
+ }
234
+ }
235
+
236
+
237
+ export const ndJson = new NdJson()