connectSocketTask.js 1.9 KB
/*
 * 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)
}