NativeHttpClient.js 5.84 KB
/*
 * 原生 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