NativeChannelClient.js 2.57 KB
/*
 * 统一通道客户端:构造时选择 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