request.ts 3.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
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
import {
  API_REQUEST,
  defineTaskApi,
  RequestOptions,
  RequestProtocol,
} from '@dcloudio/uni-api'
import { hasOwn } from '@vue/shared'

export const request = defineTaskApi<typeof uni.request>(
  API_REQUEST,
  (
    {
      url,
      data,
      header,
      method,
      dataType,
      responseType,
      withCredentials,
      timeout = __uniConfig.networkTimeout.request,
    },
    { resolve, reject }
  ) => {
    let body = null
    // 根据请求类型处理数据
    const contentType = normalizeContentType(header)
    if (method !== 'GET') {
      if (typeof data === 'string' || data instanceof ArrayBuffer) {
        body = data
      } else {
        if (contentType === 'json') {
          try {
            body = JSON.stringify(data)
          } catch (error) {
            body = data!.toString()
          }
        } else if (contentType === 'urlencoded') {
          const bodyArray = []
          for (const key in data) {
            if (hasOwn(data, key)) {
              bodyArray.push(
                encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
              )
            }
          }
          body = bodyArray.join('&')
        } else {
          body = data!.toString()
        }
      }
    }
    const xhr = new XMLHttpRequest()
    const requestTask = new RequestTask(xhr)
    xhr.open(method!, url)
    for (const key in header) {
      if (hasOwn(header, key)) {
        xhr.setRequestHeader(key, header[key])
      }
    }

    const timer = setTimeout(function () {
      xhr.onload = xhr.onabort = xhr.onerror = null
      requestTask.abort()
      reject('timeout')
    }, timeout)
    xhr.responseType = responseType as 'arraybuffer' | 'text'
    xhr.onload = function () {
      clearTimeout(timer)
      const statusCode = xhr.status
      let res = responseType === 'text' ? xhr.responseText : xhr.response
      if (responseType === 'text' && dataType === 'json') {
        try {
          res = JSON.parse(res)
        } catch (error) {
          // 和微信一致解析失败不抛出错误
          // invoke(callbackId, {
          //   errMsg: 'request:fail json parse error'
          // })
          // return
        }
      }
      resolve({
        data: res,
        statusCode,
        header: parseHeaders(xhr.getAllResponseHeaders()),
        cookies: [],
      })
    }
    xhr.onabort = function () {
      clearTimeout(timer)
      reject('abort')
    }
    xhr.onerror = function () {
      clearTimeout(timer)
      reject()
    }
    xhr.withCredentials = withCredentials!
    xhr.send(body)
    return requestTask
  },
  RequestProtocol,
  RequestOptions
)

function normalizeContentType(header: Record<string, string>) {
  const name = Object.keys(header).find(
    (name) => name.toLowerCase() === 'content-type'
  )
  if (!name) {
    return
  }
  const contentType = header[name]
  if (contentType.indexOf('application/json') === 0) {
    return 'json'
  } else if (contentType.indexOf('application/x-www-form-urlencoded') === 0) {
    return 'urlencoded'
  }
  return 'string'
}

/**
 * 请求任务类
 */
class RequestTask implements UniApp.RequestTask {
  private _xhr?: XMLHttpRequest
  constructor(xhr: XMLHttpRequest) {
    this._xhr = xhr
  }
  abort() {
    if (this._xhr) {
      this._xhr.abort()
      delete this._xhr
    }
  }
  onHeadersReceived(callback: (result: any) => void): void {
    throw new Error('Method not implemented.')
  }
  offHeadersReceived(callback: (result: any) => void): void {
    throw new Error('Method not implemented.')
  }
}

/**
 * 解析响应头
 * @param {string} headers
 * @return {object}
 */
function parseHeaders(headers: string) {
  const headersObject: Record<string, string> = {}
  headers.split('\n').forEach((header) => {
    const find = header.match(/(\S+\s*):\s*(.*)/)
    if (!find || find.length !== 3) {
      return
    }
    headersObject[find[1]] = find[2]
  })
  return headersObject
}