NativeHttpClient.js
5.84 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/*
* 原生 HTTP 客户端(uni.request)
* - 默认不鉴权:request()/send() 直接可用,不需要 connect()
* - auth=true 时:connect() 会调用 /login 拿 token/deviceId,并在请求中自动附加
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import { normalizeWsPayload } from './wsMessage.js'
import { DEFAULT_HTTP_OPTIONS } from './constants.js'
const DEFAULT_TYPE = 'private'
class NativeHttpClient {
/**
* @param {object} [options]
* @param {string} [options.baseUrl] HTTP 根地址,默认 config.HTTP_SERVER
* @param {string} [options.sendPath] send 请求路径,默认 /message
* @param {string} [options.method] 默认 POST
* @param {object} [options.header] 额外请求头
* @param {number} [options.timeout]
*/
constructor(options = {}) {
this.baseUrl = (options.baseUrl || config.HTTP_SERVER || '').replace(/\/+$/, '')
this.sendPath = options.sendPath || DEFAULT_HTTP_OPTIONS.sendPath
this.method = (options.method || DEFAULT_HTTP_OPTIONS.method).toUpperCase()
this.header = { 'Content-Type': 'application/json', ...(options.header || {}) }
this.timeout = options.timeout ?? DEFAULT_HTTP_OPTIONS.timeout
this.dataType = options.dataType || DEFAULT_HTTP_OPTIONS.dataType
this.auth = options.auth === true || (options.auth && options.auth.enabled === true)
this.token = ''
this.deviceId = ''
this.onMessage = null
// HTTP 无“连接”概念;仅在启用 auth 时,connect() 用于拉取 token/deviceId
this._tag = options.logTag || DEFAULT_HTTP_OPTIONS.logTag
}
get isConnected() {
// HTTP 默认认为可用;若启用鉴权,则以 token 是否存在作为“已连接/已就绪”
return this.auth ? !!this.token : true
}
async connect() {
if (!this.auth) {
return
}
const loginRes = await loginDevice()
const code = loginRes?.code
if (code != 200 && code != 0) {
throw new Error(`登录失败 code=${code}`)
}
const data = loginRes.data || {}
this.deviceId = data.id
this.token = data.token
if (!this.deviceId || !this.token) {
throw new Error('登录返回缺少 id 或 token')
}
this._log('info', `HTTP 已登录 deviceId=${this.deviceId}`)
}
/**
* 通用 uni.request 封装(相对路径自动拼 baseUrl)
* @param {object} options uni.request 参数,url 可为相对路径
*/
request(options = {}) {
const url = this._resolveUrl(options.url)
if (!url) {
return Promise.reject(new Error('request 缺少 url'))
}
const header = { ...this.header, ...(options.header || {}) }
if (this.auth && this.token && !header.token) {
header.token = this.token
}
return new Promise((resolve, reject) => {
uni.request({
timeout: this.timeout,
dataType: this.dataType,
...options,
url,
header,
success: (res) => resolve(res),
fail: (err) => reject(err)
})
})
}
send(data, type = DEFAULT_TYPE) {
if (this.auth && !this.token) {
this._log('warn', 'HTTP 需要鉴权:请先 connect() 获取 token/deviceId')
return Promise.resolve(false)
}
let body
if (typeof data === 'string') {
try {
body = JSON.parse(data)
} catch {
body = { raw: data }
}
} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
this._log('warn', 'HTTP 模式暂不支持 ArrayBuffer,请使用 JSON')
return Promise.resolve(false)
} else {
body = {
...data,
...(this.auth && this.deviceId ? { device_id: this.deviceId } : {}),
...(data.type != null ? { type: data.type } : this.auth ? { type } : {})
}
}
const url = this._resolveUrl(this.sendPath)
return new Promise((resolve) => {
uni.request({
url,
method: this.method,
header: this.auth && this.token ? { ...this.header, token: this.token } : { ...this.header },
data: body,
timeout: this.timeout,
dataType: this.dataType,
success: (res) => {
const ok = res.statusCode >= 200 && res.statusCode < 300
if (!ok) {
this._log('warn', `send 非 2xx status=${res.statusCode} ${serializeIfObject(res.data)}`)
resolve(false)
return
}
const parsed = normalizeWsPayload(res.data)
this._log('info', `收到 <= ${JSON.stringify(parsed).slice(0, 240)}`)
this.onMessage && this.onMessage(parsed)
resolve(true)
},
fail: (err) => {
this._log('warn', `send 失败: ${serializeIfObject(err)}`)
resolve(false)
}
})
})
}
sendJson(obj) {
return this.send(obj)
}
async close() {
this.token = ''
this.deviceId = ''
this._log('info', '会话已关闭')
}
async waitUntilConnected(timeoutMs = 15000) {
if (this.isConnected) return true
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (this.isConnected) return true
await new Promise((r) => setTimeout(r, 200))
}
return false
}
_resolveUrl(path) {
if (!path) return ''
if (/^https?:\/\//i.test(path)) return path
const p = path.startsWith('/') ? path : `/${path}`
return `${this.baseUrl}${p}`
}
_log(level, msg) {
const text = `[${this._tag}] ${msg}`
const logger = uni.$logger?.local
if (logger?.[level]) {
logger[level](text)
} else if (level === 'error') {
console.error(text)
} else if (level === 'warn') {
console.warn(text)
} else {
console.log(text)
}
}
}
export default NativeHttpClient