helper.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. /* 这里统一放一些工具函数 */
  3. module.exports = {
  4. // http请求
  5. async http(url, data, method = 'POST') {
  6. const { ctx } = this;
  7. let targetUrl;
  8. if (url.includes('http')) {
  9. targetUrl = url;
  10. } else {
  11. targetUrl = this.app.config.baseUrl + url;
  12. }
  13. try {
  14. const res = await ctx.curl(targetUrl, {
  15. method,
  16. data,
  17. dataType: 'json',
  18. timing: true,
  19. headers: ctx.header,
  20. });
  21. /* timing :{
  22. queuing:分配 socket 耗时
  23. dnslookup:DNS 查询耗时
  24. connected:socket 三次握手连接成功耗时
  25. requestSent:请求数据完整发送完毕耗时
  26. waiting:收到第一个字节的响应数据耗时
  27. contentDownload:全部响应数据接收完毕耗时
  28. }
  29. */
  30. if (res.res.timing.contentDownload > 1000) {
  31. ctx.logger.info(
  32. `${method}请求${targetUrl}响应耗时:${res.res.timing.contentDownload}ms`
  33. );
  34. }
  35. // 这里可以根据后台返回状态码判断请求成功或失败
  36. if (res.data.code !== 1) {
  37. throw res.data.msg;
  38. }
  39. return res.data;
  40. } catch (error) {
  41. ctx.logger.warn('请求错误:' + error);
  42. throw error;
  43. }
  44. },
  45. // 下划转驼峰
  46. camelCase(val) {
  47. const arr = val.split('_');
  48. if (arr.length > 1) {
  49. if (arr[0] === '') {
  50. arr.splice(0, 1);
  51. }
  52. for (let i = 1; i < arr.length; i++) {
  53. arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
  54. }
  55. val = arr.join('');
  56. return val;
  57. }
  58. return false;
  59. },
  60. // 响应数据下划转驼峰
  61. formaterResponse(obj) {
  62. if (Array.isArray(obj)) {
  63. obj.forEach(item => {
  64. return this.formaterResponse(item);
  65. });
  66. } else {
  67. Object.keys(obj).forEach(key => {
  68. const value = obj[key];
  69. if (this.camelCase(key)) {
  70. obj[this.camelCase(key)] = value;
  71. delete obj[key];
  72. }
  73. if (Array.isArray(value)) {
  74. value.forEach(node => {
  75. return this.formaterResponse(node);
  76. });
  77. }
  78. if (Object.prototype.toString.call(value) === '[object Object]') {
  79. return this.formaterResponse(value);
  80. }
  81. });
  82. return obj;
  83. }
  84. },
  85. };