cshenfu
2023-06-14 de93aa62c83d6afb9f70cd5a22838375db0a8cbc
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
const {
  UniCloudError
} = require('../../../common/error')
const {
  camel2snakeJson, snake2camelJson
} = require('../../../common/utils')
 
function generateApiResult (apiName, data) {
  if (data.errcode) {
    throw new UniCloudError({
      code: data.errcode || -2,
      message: data.errmsg || `${apiName} fail`
    })
  } else {
    delete data.errcode
    delete data.errmsg
    return {
      ...data,
      errMsg: `${apiName} ok`,
      errCode: 0
    }
  }
}
 
function nomalizeError (apiName, error) {
  throw new UniCloudError({
    code: error.code || -2,
    message: error.message || `${apiName} fail`
  })
}
 
// 微信openapi接口接收蛇形(snake case)参数返回蛇形参数,这里进行转化,如果是formdata里面的参数需要在对应api实现时就转为蛇形
async function callWxOpenApi ({
  name,
  url,
  data,
  options,
  defaultOptions
}) {
  let result = {}
  // 获取二维码的接口wxacode.get和wxacode.getUnlimited不可以传入access_token(可能有其他接口也不可以),否则会返回data format error
  const dataCopy = camel2snakeJson(Object.assign({}, data))
  if (dataCopy && dataCopy.access_token) {
    delete dataCopy.access_token
  }
  try {
    options = Object.assign({}, defaultOptions, options, { data: dataCopy })
    result = await uniCloud.httpclient.request(url, options)
  } catch (e) {
    return nomalizeError(name, e)
  }
 
  // 有几个接口成功返回buffer失败返回json,对这些接口统一成返回buffer,然后分别解析
  let resData = result.data
  const contentType = result.headers['content-type']
  if (
    Buffer.isBuffer(resData) &&
    (contentType.indexOf('text/plain') === 0 ||
      contentType.indexOf('application/json') === 0)
  ) {
    try {
      resData = JSON.parse(resData.toString())
    } catch (e) {
      resData = resData.toString()
    }
  } else if (Buffer.isBuffer(resData)) {
    resData = {
      buffer: resData,
      contentType
    }
  }
  return snake2camelJson(
    generateApiResult(
      name,
      resData || {
        errCode: -2,
        errMsg: 'Request failed'
      }
    )
  )
}
 
function buildUrl (url, data) {
  let query = ''
  if (data && data.accessToken) {
    const divider = url.indexOf('?') > -1 ? '&' : '?'
    query = `${divider}access_token=${data.accessToken}`
  }
  return `${url}${query}`
}
 
module.exports = {
  callWxOpenApi,
  buildUrl
}