@jetlinks-web/core 2.0.4 → 2.0.6

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.4",
3
+ "version": "2.0.6",
4
4
  "description": "",
5
5
  "main": "index.ts",
6
6
  "module": "index.ts",
package/src/axios.ts CHANGED
@@ -12,12 +12,16 @@ 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
19
19
  timeout?: number
20
20
  handleRequest?: () => void
21
+ /**
22
+ * 用以获取localstorage中的lang
23
+ */
24
+ langKey?: string
21
25
  /**
22
26
  * response处理函数
23
27
  * @param response AxiosResponse实例
@@ -44,13 +48,16 @@ let _options: Options = {
44
48
  handleRequest: undefined,
45
49
  handleResponse: undefined,
46
50
  handleError: undefined,
51
+ langKey: 'lang',
47
52
  requestOptions: (config) => ({}),
48
53
  tokenExpiration: () => {},
49
-
50
54
  }
51
55
 
56
+ const controller = new AbortController();
57
+
52
58
  const handleRequest = (config: InternalAxiosRequestConfig) => {
53
59
  const token = getToken()
60
+ const lang = localStorage.getItem(_options.langKey)
54
61
 
55
62
  // 没有token,并且该接口需要token校验
56
63
  if (!token && !_options.filter_url?.some((url) => config.url?.includes(url))) {
@@ -63,6 +70,10 @@ const handleRequest = (config: InternalAxiosRequestConfig) => {
63
70
  config.headers[TOKEN_KEY] = token
64
71
  }
65
72
 
73
+ if (lang) {
74
+ config.headers[_options.langKey] = lang
75
+ }
76
+
66
77
  if (_options.requestOptions && isFunction(_options.requestOptions)) {
67
78
  const extraOptions = _options.requestOptions(config)
68
79
  if (extraOptions && isObject(extraOptions)) {
@@ -113,7 +124,7 @@ const errorHandler = (err: AxiosError<any>) => {
113
124
  break;
114
125
  case 401:
115
126
  description = '用户未登录'
116
- _options.tokenExpiration?.()
127
+ _options.tokenExpiration?.(err, err.response)
117
128
  break;
118
129
  default:
119
130
  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()