normalize.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const {
  2. UniCloudError
  3. } = require('../../../common/error')
  4. const {
  5. camel2snakeJson, snake2camelJson
  6. } = require('../../../common/utils')
  7. function generateApiResult (apiName, data) {
  8. if (data.errcode) {
  9. throw new UniCloudError({
  10. code: data.errcode || -2,
  11. message: data.errmsg || `${apiName} fail`
  12. })
  13. } else {
  14. delete data.errcode
  15. delete data.errmsg
  16. return {
  17. ...data,
  18. errMsg: `${apiName} ok`,
  19. errCode: 0
  20. }
  21. }
  22. }
  23. function nomalizeError (apiName, error) {
  24. throw new UniCloudError({
  25. code: error.code || -2,
  26. message: error.message || `${apiName} fail`
  27. })
  28. }
  29. // 微信openapi接口接收蛇形(snake case)参数返回蛇形参数,这里进行转化,如果是formdata里面的参数需要在对应api实现时就转为蛇形
  30. async function callWxOpenApi ({
  31. name,
  32. url,
  33. data,
  34. options,
  35. defaultOptions
  36. }) {
  37. let result = {}
  38. // 获取二维码的接口wxacode.get和wxacode.getUnlimited不可以传入access_token(可能有其他接口也不可以),否则会返回data format error
  39. const dataCopy = camel2snakeJson(Object.assign({}, data))
  40. if (dataCopy && dataCopy.access_token) {
  41. delete dataCopy.access_token
  42. }
  43. try {
  44. options = Object.assign({}, defaultOptions, options, { data: dataCopy })
  45. result = await uniCloud.httpclient.request(url, options)
  46. } catch (e) {
  47. return nomalizeError(name, e)
  48. }
  49. // 有几个接口成功返回buffer失败返回json,对这些接口统一成返回buffer,然后分别解析
  50. let resData = result.data
  51. const contentType = result.headers['content-type']
  52. if (
  53. Buffer.isBuffer(resData) &&
  54. (contentType.indexOf('text/plain') === 0 ||
  55. contentType.indexOf('application/json') === 0)
  56. ) {
  57. try {
  58. resData = JSON.parse(resData.toString())
  59. } catch (e) {
  60. resData = resData.toString()
  61. }
  62. } else if (Buffer.isBuffer(resData)) {
  63. resData = {
  64. buffer: resData,
  65. contentType
  66. }
  67. }
  68. return snake2camelJson(
  69. generateApiResult(
  70. name,
  71. resData || {
  72. errCode: -2,
  73. errMsg: 'Request failed'
  74. }
  75. )
  76. )
  77. }
  78. function buildUrl (url, data) {
  79. let query = ''
  80. if (data && data.accessToken) {
  81. const divider = url.indexOf('?') > -1 ? '&' : '?'
  82. query = `${divider}access_token=${data.accessToken}`
  83. }
  84. return `${url}${query}`
  85. }
  86. module.exports = {
  87. callWxOpenApi,
  88. buildUrl
  89. }