@jetlinks-web/core 1.0.8 → 2.0.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/index.ts CHANGED
@@ -1 +1 @@
1
- export * from './src'
1
+ export * from './scr/axios'
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "@jetlinks-web/core",
3
- "version": "1.0.8",
3
+ "version": "2.0.0",
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/router": "^1.0.7",
21
- "@jetlinks-web/utils": "^1.0.5",
22
- "@jetlinks-web/types": "^1.0.1"
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/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, cleanToken } 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
- cleanToken()
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
- }