@jetlinks-web/core 1.0.9 → 2.0.1

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 @@
1
- export * from './src'
1
+ export * from './src/axios'
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "@jetlinks-web/core",
3
- "version": "1.0.9",
3
+ "version": "2.0.1",
4
4
  "description": "",
5
5
  "main": "index.ts",
6
6
  "module": "index.ts",
7
- "keywords": [],
7
+ "keywords": [
8
+ "@jetlinks-web"
9
+ ],
8
10
  "files": [
9
11
  "src",
10
12
  "index.ts"
@@ -13,24 +15,16 @@
13
15
  "author": "",
14
16
  "license": "ISC",
15
17
  "dependencies": {
16
- "lodash-es": "^4.17.21",
17
- "axios": "^1.4.0",
18
- "rxjs": "^7.8.1",
19
- "@jetlinks-web/constants": "^1.0.1",
20
- "@jetlinks-web/types": "^1.0.1",
21
- "@jetlinks-web/router": "^1.0.7",
22
- "@jetlinks-web/utils": "^1.0.5"
23
- },
24
- "devDependencies": {
25
- "@types/lodash-es": "^4.17.7",
26
- "@types/node": "^20.2.5",
27
- "jetlinks-ui-components": "^1.0.34-16"
18
+ "axios": "^1.7.4",
19
+ "@jetlinks-web/constants": "^1.0.2",
20
+ "@jetlinks-web/types": "^1.0.2",
21
+ "@jetlinks-web/utils": "^1.0.8"
28
22
  },
29
23
  "publishConfig": {
30
24
  "registry": "https://registry.npmjs.org/",
31
25
  "access": "public"
32
26
  },
33
27
  "scripts": {
34
- "clean": "pnpm rimraf node_modules && pnpm rimraf dist && pnpm rimraf .turbo"
28
+ "clean": "pnpm rimraf .turbo"
35
29
  }
36
30
  }
package/src/axios.ts ADDED
@@ -0,0 +1,211 @@
1
+ import { TOKEN_KEY, BASE_API } from '@jetlinks-web/constants'
2
+ import { getToken } from '@jetlinks-web/utils'
3
+ import axios from 'axios'
4
+ import type {
5
+ AxiosInstance,
6
+ AxiosResponse,
7
+ AxiosError,
8
+ InternalAxiosRequestConfig,
9
+ } from 'axios'
10
+ import type { AxiosResponseRewrite } from '@jetlinks-web/types'
11
+ import {isFunction, isObject} from 'lodash-es'
12
+
13
+ interface Options {
14
+
15
+ tokenExpiration: () => void
16
+ filter_url?: Array<string>
17
+ code?: number
18
+ codeKey?: string
19
+ timeout?: number
20
+ handleRequest?: () => void
21
+ /**
22
+ * response处理函数
23
+ * @param response AxiosResponse实例
24
+ */
25
+ handleResponse?: (response: AxiosResponse) => void
26
+ /**
27
+ * 错误处理函数
28
+ * @param msg 错误消息
29
+ * @param status 错误code
30
+ * @param error 错误实例
31
+ */
32
+ handleError?: (msg: string, status: string | number, error: AxiosError<any>) => void
33
+ requestOptions?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Record<string, any>
34
+
35
+ }
36
+
37
+ let instance: AxiosInstance
38
+
39
+ let _options: Options = {
40
+ filter_url: [],
41
+ code: 200,
42
+ codeKey: 'status',
43
+ timeout: 1000 * 15,
44
+ handleRequest: undefined,
45
+ handleResponse: undefined,
46
+ handleError: undefined,
47
+ requestOptions: (config) => ({}),
48
+ tokenExpiration: () => {},
49
+
50
+ }
51
+
52
+ const handleRequest = (config: InternalAxiosRequestConfig) => {
53
+ const token = getToken()
54
+
55
+ // 没有token,并且该接口需要token校验
56
+ if (!token && !_options.filter_url?.some((url) => config.url?.includes(url))) {
57
+ // 跳转登录页
58
+ _options.tokenExpiration?.()
59
+ return config
60
+ }
61
+
62
+ config.headers[TOKEN_KEY] = token
63
+
64
+ if (_options.requestOptions && isFunction(_options.requestOptions)) {
65
+ const extraOptions = _options.requestOptions(config)
66
+ if (extraOptions && isObject(extraOptions)) {
67
+ for (const key in extraOptions) {
68
+ config[key] = extraOptions[key]
69
+ }
70
+ }
71
+ }
72
+
73
+
74
+ return config
75
+ }
76
+
77
+ const handleResponse = (response: AxiosResponse) => {
78
+
79
+ if (_options.handleResponse && isFunction(_options.handleResponse)) {
80
+ return _options.handleResponse(response)
81
+ }
82
+
83
+ if (response.data instanceof ArrayBuffer) {
84
+ return response
85
+ }
86
+
87
+ const status = response.data[_options.codeKey || 'status']
88
+
89
+ // 增加业务接口处理成功判断方式,只需要判断返回参数包含:success为true
90
+ if (
91
+ typeof response.data === 'object' &&
92
+ typeof response.data.success === 'undefined'
93
+ ) {
94
+ response.data.success = status === _options.code
95
+ }
96
+
97
+ return response.data
98
+ }
99
+
100
+ const errorHandler = (err: AxiosError<any>) => {
101
+ let description = 'Error'
102
+ let _status: string | number = 0
103
+ if (err.response) {
104
+ const {data, status} = err.response
105
+ _status = status
106
+ switch (status) {
107
+ case 400:
108
+ case 403:
109
+ case 500:
110
+ description = (`${data?.message}`).substring(0, 90)
111
+ break;
112
+ case 401:
113
+ description = '用户未登录'
114
+ _options.tokenExpiration?.()
115
+ break;
116
+ default:
117
+ break;
118
+ }
119
+ } else if (err.response === undefined) {
120
+ description = err.message.includes('timeout') ? '接口响应超时' : err.message
121
+ _status = 'timeout'
122
+ }
123
+
124
+ if (_options.handleError && isFunction(_options.handleError)) {
125
+ _options.handleError(description, _status, err)
126
+ }
127
+
128
+ return Promise.reject(err)
129
+ }
130
+
131
+ export const crateAxios = (options: Options) => {
132
+ if (options) {
133
+ _options = Object.assign(_options, options)
134
+ }
135
+
136
+ instance = axios.create({
137
+ withCredentials: false,
138
+ timeout: _options.timeout,
139
+ baseURL: BASE_API
140
+ })
141
+
142
+ instance.interceptors.request.use(
143
+ handleRequest,
144
+ errorHandler
145
+ )
146
+
147
+ instance.interceptors.response.use(
148
+ handleResponse,
149
+ errorHandler
150
+ )
151
+ }
152
+
153
+ export const post = <T = any>(url: string, data: any = undefined, ext?: any) => {
154
+ return (instance<any, AxiosResponseRewrite<T>>({
155
+ method: 'POST',
156
+ url,
157
+ data,
158
+ ...ext,
159
+ }))
160
+ }
161
+
162
+ export const get = <T = any>(url: string, params: any = undefined, ext?: any) => {
163
+ return instance<any, AxiosResponseRewrite<T>>({
164
+ method: 'GET',
165
+ url,
166
+ params,
167
+ ...ext,
168
+ })
169
+ }
170
+
171
+ export const put = <T = any>(url: string, data: any = undefined, ext?: any) => {
172
+ return instance<any, AxiosResponseRewrite<T>>({
173
+ method: 'PUT',
174
+ url,
175
+ data,
176
+ ...ext,
177
+ })
178
+ }
179
+
180
+ export const patch = <T = any>(url: string, data: any = undefined, ext?: any) => {
181
+ return instance<any, AxiosResponseRewrite<T>>({
182
+ method: 'patch',
183
+ url,
184
+ data,
185
+ ...ext,
186
+ })
187
+ }
188
+
189
+ export const remove = <T = any>(url: string, params: any = undefined, ext?: any) => {
190
+ return instance<any, AxiosResponseRewrite<T>>({
191
+ method: 'DELETE',
192
+ url,
193
+ params,
194
+ ...ext,
195
+ })
196
+ }
197
+
198
+ export const getStream = (url: string, params?: any, ext?: any) => {
199
+ return get(url, params, { responseType: 'arraybuffer', ...ext })
200
+ }
201
+
202
+ export const postStream = (url: string, data: any, ext?: any) => {
203
+ return post(url, data, { responseType: 'arraybuffer', ...ext })
204
+ }
205
+
206
+ export const request = {
207
+ post, get, put, patch, remove, getStream, postStream
208
+ }
209
+
210
+
211
+
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './request'
2
- export * from './websocket'
@@ -1,203 +0,0 @@
1
- import { TOKEN_KEY, BASE_API } from '@jetlinks-web/constants'
2
- import { getToken, removeToken } from '@jetlinks-web/utils'
3
- import axios from 'axios'
4
- import type {
5
- AxiosRequestConfig,
6
- AxiosInstance,
7
- AxiosResponse,
8
- AxiosError,
9
- InternalAxiosRequestConfig,
10
- } from 'axios'
11
- import { notification as Notification } from 'jetlinks-ui-components'
12
- import { isFunction, merge } from 'lodash-es'
13
- import type { AxiosResponseRewrite } from '@jetlinks-web/types'
14
- import { context } from './context'
15
-
16
- export interface ContextOptions {
17
- filterUrl?: string[]
18
- handleRequest?: (
19
- config: InternalAxiosRequestConfig,
20
- ) => InternalAxiosRequestConfig
21
- handleResponse?: (response: AxiosResponse) => AxiosResponse
22
- errorHandler?: (error: AxiosError) => void
23
-
24
- loginInvalid?: () => void
25
- }
26
-
27
- export interface CreateAxiosOptions extends AxiosRequestConfig, ContextOptions {}
28
-
29
- const SUCCESS_CODE = 200 // 成功代码
30
-
31
- export class Axios {
32
- private axiosInstance: AxiosInstance
33
- private readonly options: CreateAxiosOptions
34
-
35
- constructor(options: CreateAxiosOptions) {
36
- this.options = merge(context, options)
37
- this.axiosInstance = axios.create({
38
- withCredentials: false,
39
- timeout: 1000 * 15,
40
- baseURL: BASE_API
41
- })
42
- this.axiosInstance.interceptors.request.use(
43
- this.request.bind(this),
44
- this.errorHandler.bind(this)
45
- )
46
- this.axiosInstance.interceptors.response.use(
47
- this.response.bind(this),
48
- this.errorHandler.bind(this),
49
- )
50
- }
51
-
52
- jumpLogin() {
53
- removeToken()
54
- this.options.loginInvalid?.()
55
- }
56
-
57
- request(config: InternalAxiosRequestConfig) {
58
- const token = getToken()
59
- const filterUrl = this.options.filterUrl // 不需要token校验接口
60
- // 没有token,并且该接口需要token校验
61
- if (!token && !filterUrl?.some((url) => config.url?.includes(url))) {
62
- // 跳转登录页
63
- this.jumpLogin()
64
- return config
65
- }
66
-
67
- config.headers[TOKEN_KEY] = token
68
-
69
- if (this.options.handleRequest && isFunction(this.options.handleRequest)) {
70
- config = this.options.handleRequest(config)
71
- }
72
-
73
- return config
74
- }
75
-
76
- response(response: AxiosResponse) {
77
- if (
78
- this.options.handleResponse &&
79
- isFunction(this.options.handleResponse)
80
- ) { // 自定义处理
81
- return this.options.handleResponse(response)
82
- }
83
-
84
- if (response.data instanceof ArrayBuffer) {
85
- return response
86
- }
87
-
88
- const { status } = response.data
89
-
90
- // 增加业务接口处理成功判断方式,只需要判断返回参数包含:success为true
91
- if (
92
- typeof response.data === 'object' &&
93
- typeof response.data.success === 'undefined'
94
- ) {
95
- response.data.success = status === SUCCESS_CODE
96
- }
97
-
98
- return response.data
99
- }
100
-
101
- errorHandler(err: AxiosError<any>) {
102
- if (this.options.errorHandler && isFunction(this.options.errorHandler)) {
103
- this.options.errorHandler(err)
104
- }
105
-
106
- if (err.response) {
107
- const { data, status } = err.response
108
- switch(status) {
109
- case 400:
110
- case 403:
111
- case 500:
112
- const description = (`${data?.message}`).substring(0, 90)
113
- this.showNotification(description, status)
114
- break;
115
- case 401:
116
- this.showNotification('用户未登录', status)
117
- this.jumpLogin()
118
- break;
119
- default:
120
- break;
121
- }
122
- } else if (err.response === undefined) {
123
- const description = err.message.includes('timeout') ? '接口响应超时' : err.message
124
- this.showNotification(description)
125
- }
126
-
127
- return Promise.reject(err)
128
- }
129
-
130
- post<T = any>(url: string, data: any = undefined, ext?: any) {
131
- return (this.axiosInstance<any, AxiosResponseRewrite<T>>({
132
- method: 'POST',
133
- url,
134
- data,
135
- ...ext,
136
- }))
137
- }
138
-
139
- postParams<T = any>(url: string, data: any = undefined, params = {}, ext?: any) {
140
- return this.axiosInstance<any, AxiosResponseRewrite<T>>({
141
- method: 'POST',
142
- url,
143
- data,
144
- params,
145
- ...ext,
146
- })
147
- }
148
-
149
- get<T = any>(url: string, params: any = undefined, ext?: any) {
150
- return this.axiosInstance<any, AxiosResponseRewrite<T>>({
151
- method: 'GET',
152
- url,
153
- params,
154
- ...ext,
155
- })
156
- }
157
-
158
- put<T = any>(url: string, data: any = undefined, ext?: any) {
159
- return this.axiosInstance<any, AxiosResponseRewrite<T>>({
160
- method: 'PUT',
161
- url,
162
- data,
163
- ...ext,
164
- })
165
- }
166
-
167
- patch<T = any>(url: string, data: any = undefined, ext?: any) {
168
- return this.axiosInstance<any, AxiosResponseRewrite<T>>({
169
- method: 'patch',
170
- url,
171
- data,
172
- ...ext,
173
- })
174
- }
175
-
176
- remove<T = any>(url: string, params: any = undefined, data?: any, ext?: any) {
177
- return this.axiosInstance<any, AxiosResponseRewrite<T>>({
178
- method: 'DELETE',
179
- url,
180
- params,
181
- data,
182
- ...ext,
183
- })
184
- }
185
-
186
- getStream(url: string, params?: any) {
187
- return this.get(url, params, { responseType: 'arraybuffer' })
188
- }
189
-
190
- postStream(url: string, data: any, params: any) {
191
- return this.postParams(url, data, params, { responseType: 'arraybuffer' })
192
- }
193
-
194
- private showNotification(description, key?: string | number, show: boolean = true) {
195
- if (show) {
196
- Notification.error({
197
- key,
198
- description,
199
- message: '',
200
- })
201
- }
202
- }
203
- }
@@ -1,12 +0,0 @@
1
- import { ContextOptions } from './axios'
2
- // 公用上下文
3
- export let context: ContextOptions = {
4
- filterUrl: [],
5
- handleRequest: undefined,
6
- handleResponse: undefined,
7
- errorHandler: undefined
8
- }
9
-
10
- export const initRequest = (func: () => ContextOptions) => {
11
- context = func()
12
- }
@@ -1,9 +0,0 @@
1
- import { Axios } from "./axios";
2
- import type { CreateAxiosOptions } from "./axios";
3
- export { initRequest } from './context'
4
-
5
- export const createAxios = (options?: Partial<CreateAxiosOptions>) => {
6
- return new Axios(options)
7
- }
8
-
9
- export const request = createAxios()
package/src/websocket.ts DELETED
@@ -1,185 +0,0 @@
1
- import { notification } from 'jetlinks-ui-components'
2
- import { Observable } from 'rxjs'
3
-
4
- let webSocketUrl = ''
5
- let ws: WebSocket | null = null // websocket实例
6
- let subs = {} // 订阅
7
- const tempQueue: any[] = [] // 缓存消息队列
8
-
9
- type HeartCheckType = {
10
- timeout: number,
11
- timer: NodeJS.Timeout | null
12
- reset: () => HeartCheckType
13
- start: () => void
14
- }
15
- // 心跳
16
- const heartCheck: HeartCheckType = {
17
- timeout: 2 * 1000,
18
- timer: null,
19
- reset() {
20
- if (this.timer) {
21
- clearInterval(this.timer)
22
- }
23
- return this
24
- },
25
- start() {
26
- this.timer = setInterval(() => {
27
- if (ws) {
28
- ws.send(JSON.stringify({ type: 'ping' }))
29
- }
30
- }, this.timeout)
31
- }
32
- }
33
-
34
- // 重启
35
- const reconnect: {
36
- timeout: number,
37
- timer: NodeJS.Timeout | null
38
- count: number,
39
- lock: boolean,
40
- reload: () => void
41
- countAdd: () => void
42
- getReconnectCount: () => number
43
- } = {
44
- timeout: 5 * 1000, // 重启时长,1-10次,频率为5s, 11-20次, 频率为15s, 20+, 频率为30s
45
- timer: null,
46
- count: 0,
47
- lock: false,
48
- reload() {
49
- this.timer && clearTimeout(this.timer)
50
- const that = this
51
- if (!this.lock) {
52
- const count = this.getReconnectCount()
53
- this.lock = true
54
- this.timer = setTimeout(() => {
55
- createWebSocket()
56
- that.lock = false
57
- that.countAdd()
58
- }, that.timeout * count)
59
- }
60
- },
61
- countAdd() {
62
- this.count += 1
63
- },
64
- getReconnectCount() {
65
- const count = this.count
66
- if (count <=10) {
67
- return 1
68
- } else if (count > 10 && count <= 20) {
69
- return 3
70
- } else {
71
- return 6
72
- }
73
- }
74
- }
75
-
76
- export const initWebSocket = (url: string) => {
77
- webSocketUrl = url
78
- }
79
-
80
- function createWebSocket() {
81
- if (!webSocketUrl) {
82
- console.warn('websocket url 不能为空')
83
- return
84
- }
85
-
86
- if (!ws) {
87
- console.log(webSocketUrl)
88
- ws = new WebSocket(webSocketUrl)
89
-
90
- ws.onopen = () => {
91
- heartCheck.reset().start()
92
- reconnect.count = 0 // 重置重启次数
93
- // 发送已缓存的消息
94
- if (tempQueue.length) {
95
- for (let i = tempQueue.length - 1; i >= 0; i--) {
96
- ws!.send(tempQueue[i])
97
- tempQueue.splice(i, 1)
98
- }
99
- }
100
- }
101
-
102
- ws.onerror = () => {
103
- ws = null
104
- reconnect.reload()
105
-
106
- }
107
-
108
- ws.onmessage = (msg: Record<string, any>) => {
109
- const data = JSON.parse(msg.data)
110
-
111
- if (data.type === 'error') {
112
- notification.error({ key: 'error', message: data.message })
113
- }
114
-
115
- const requestItem = subs[data.requestId]
116
- if (requestItem) {
117
- if (data.type === 'complete') {
118
- requestItem.forEach((item: Record<string, any>) => {
119
- item.complete()
120
- })
121
- } else if (data.type === 'result') {
122
- requestItem.forEach((item: Record<string, any>) => {
123
- item.next(data)
124
- })
125
- }
126
- }
127
-
128
- }
129
-
130
- ws.onclose = () => {
131
- ws = null
132
- reconnect.reload()
133
- }
134
-
135
- }
136
- return ws
137
- }
138
-
139
- export const getWebSocket = (id: string, topic: string, parameter: Record<string, any> = {}) => new Observable(subscriber => {
140
- if (!subs[id]) {
141
- subs[id] = []
142
- }
143
-
144
- subs[id].push({
145
- next(val: Record<string, any>) {
146
- subscriber.next(val)
147
- },
148
- complete() {
149
- subscriber.complete()
150
- }
151
- })
152
-
153
- const msg = JSON.stringify({id, topic, parameter, type: 'sub'})
154
- const thatWs = createWebSocket()
155
- if (thatWs) {
156
- if (thatWs.readyState === WebSocket.OPEN) {
157
- thatWs.send(msg)
158
- } else {
159
- tempQueue.push(msg)
160
- }
161
- }
162
-
163
- return () => {
164
- const unsub = JSON.stringify({ id, type: 'unsub' })
165
- delete subs[id]
166
- thatWs?.send(unsub)
167
- }
168
- })
169
-
170
- /**
171
- * 关闭 websocket
172
- */
173
- const closeWs = () => {
174
- if (ws) {
175
- ws.close()
176
- }
177
- }
178
-
179
- window.onbeforeunload = function () {
180
- closeWs()
181
- }
182
-
183
- export {
184
- createWebSocket
185
- }