request.js 2.0 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
import {
  isPlainObject
} from 'uni-shared'

import {
  invoke
} from 'uni-core/service/bridge'

import {
  onMethod,
  invokeMethod
} from '../../platform'

const requestTasks = Object.create(null)

function formatResponse (res, args) {
  if (
    typeof res.data === 'string' &&
    res.data.charCodeAt(0) === 65279
  ) {
    res.data = res.data.substr(1)
  }

  res.statusCode = parseInt(res.statusCode, 10)

  if (isPlainObject(res.header)) {
    res.header = Object.keys(res.header).reduce(function (ret, key) {
      const value = res.header[key]
      if (Array.isArray(value)) {
        ret[key] = value.join(',')
      } else if (typeof value === 'string') {
        ret[key] = value
      }
      return ret
    }, {})
  }

  if (args.dataType && args.dataType.toLowerCase() === 'json') {
    try {
      res.data = JSON.parse(res.data)
    } catch (e) {}
  }

  return res
}

onMethod('onRequestTaskStateChange', function ({
  requestTaskId,
  state,
  data,
  statusCode,
  header,
  errMsg
}) {
  const {
    args,
    callbackId
  } = requestTasks[requestTaskId]

  if (!callbackId) {
    return
  }
  delete requestTasks[requestTaskId]
  switch (state) {
    case 'success':
      invoke(callbackId, formatResponse({
        data,
        statusCode,
        header,
        errMsg: 'request:ok'
      }, args))
      break
    case 'fail':
      invoke(callbackId, {
        errMsg: 'request:fail ' + errMsg
      })
      break
  }
})

class RequestTask {
  constructor (id) {
    this.id = id
  }

  abort () {
    invokeMethod('operateRequestTask', {
      requestTaskId: this.id,
      operationType: 'abort'
    })
  }

  offHeadersReceived () {

  }

  onHeadersReceived () {

  }
}

export function request (args, callbackId) {
  const {
    requestTaskId
  } = invokeMethod('createRequestTask', args)

  requestTasks[requestTaskId] = {
    args,
    callbackId
  }

  return new RequestTask(requestTaskId)
}