NativeChannelClient.js
2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* 统一通道客户端:构造时选择 http / websocket,对外 API 一致
*
* const client = new NativeChannelClient({ transport: 'websocket' })
* const client = new NativeChannelClient({ transport: 'http', sendPath: '/message', auth: true })
*/
import { TransportType } from './constants.js'
import NativeWsClient from './NativeWsClient.js'
import NativeHttpClient from './NativeHttpClient.js'
class NativeChannelClient {
/**
* @param {object} [options]
* @param {'http'|'websocket'} [options.transport='websocket']
* @param {string} [options.baseUrl] HTTP 根地址(http 模式)
* @param {string} [options.sendPath] HTTP send 路径(http 模式)
* @param {string} [options.wsUrl] WebSocket 地址覆盖(websocket 模式,写入 NATIVE_WS_BASE 逻辑由 ws 客户端处理)
* @param {Function} [options.onMessage]
*/
constructor(options = {}) {
const transport = options.transport || TransportType.WEBSOCKET
this.transport = transport
if (transport === TransportType.HTTP) {
this._impl = new NativeHttpClient(options)
} else {
this._impl = new NativeWsClient()
if (options.wsUrl) {
this._impl.wsAddress = options.wsUrl
}
}
if (typeof options.onMessage === 'function') {
this._impl.onMessage = options.onMessage
}
}
get isConnected() {
return this._impl.isConnected
}
get deviceId() {
return this._impl.deviceId
}
get token() {
return this._impl.token
}
get onMessage() {
return this._impl.onMessage
}
set onMessage(handler) {
this._impl.onMessage = handler
}
connect() {
return this._impl.connect()
}
connectDirect(url) {
if (this.transport !== TransportType.WEBSOCKET) {
return Promise.reject(new Error('connectDirect 仅支持 websocket 模式'))
}
return this._impl.connectDirect(url)
}
send(data, type) {
return this._impl.send(data, type)
}
sendJson(obj) {
if (typeof this._impl.sendJson === 'function') {
return this._impl.sendJson(obj)
}
return this._impl.send(obj)
}
close(...args) {
return this._impl.close(...args)
}
waitUntilConnected(timeoutMs) {
return this._impl.waitUntilConnected(timeoutMs)
}
/** 仅 http 模式:底层 uni.request */
request(options) {
if (this.transport !== TransportType.HTTP) {
return Promise.reject(new Error('request 仅支持 http 模式'))
}
return this._impl.request(options)
}
}
export default NativeChannelClient