connectSocketTask.js
1.9 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
/*
* uni.connectSocket 官方说明:
* https://uniapp.dcloud.net.cn/api/request/websocket.html
*
* - 至少传入 success / fail / complete 之一 → 同步返回 SocketTask
* - 不传上述回调 → 返回封装后的 Promise<SocketTask>
*
* 统一使用 SocketTask(onOpen / onMessage / send / close),
* 不使用已废弃的全局 uni.onSocketOpen / uni.sendSocketMessage 等。
*/
export function isSocketTask(task) {
return task != null && typeof task.onOpen === 'function'
}
/**
* 文档推荐写法:传入 complete,同步拿到 SocketTask
* @param {{ url: string, header?: object, protocols?: string[], fail?: Function }} options
* @returns {object} SocketTask
*/
export function createSocketTask(options) {
const { url, header, protocols, fail } = options
if (!url) {
throw new Error('connectSocket 缺少 url')
}
const socketTask = uni.connectSocket({
url,
header: header || {},
protocols: protocols || [],
fail,
complete: () => {}
})
if (!isSocketTask(socketTask)) {
throw new Error('connectSocket 未返回 SocketTask,需传入 success / fail / complete 之一')
}
return socketTask
}
/**
* 兼容 Promise 封装:不传 success/fail/complete 时 await
* @param {{ url: string, header?: object, protocols?: string[] }} options
* @returns {Promise<object>} SocketTask
*/
export async function connectSocketTask(options) {
const { url, header, protocols } = options
if (!url) {
throw new Error('connectSocket 缺少 url')
}
const result = uni.connectSocket({
url,
header: header || {},
protocols: protocols || []
})
if (isSocketTask(result)) {
return result
}
if (result != null && typeof result.then === 'function') {
const task = await result
if (!isSocketTask(task)) {
throw new Error('connectSocket Promise 未解析为 SocketTask')
}
return task
}
return createSocketTask(options)
}