http-util.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. const { AxiosService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const { isNullOrUndefined } = require('naf-core').Util;
  5. const _ = require('lodash');
  6. //
  7. class HttpUtilService extends AxiosService {
  8. constructor(ctx) {
  9. super(ctx, {}, {});
  10. }
  11. // 替换uri中的参数变量
  12. merge(uri, query = {}) {
  13. const keys = Object.keys(query);
  14. const arr = [];
  15. for (const k of keys) {
  16. arr.push(`${k}=${query[k]}`);
  17. }
  18. if (arr.length > 0) {
  19. uri = `${uri}?${arr.join('&')}`;
  20. }
  21. return uri;
  22. }
  23. /**
  24. * curl-get请求
  25. * @param {String} uri 接口地址
  26. * @param {Object} query 地址栏参数
  27. * @param {Object} options 额外参数
  28. */
  29. async cget(uri, query, options) {
  30. return this.toRequest(uri, null, query, options);
  31. }
  32. /**
  33. * curl-post请求
  34. * @param {String} uri 接口地址
  35. * @param {Object} data post的body
  36. * @param {Object} query 地址栏参数
  37. * @param {Object} options 额外参数
  38. */
  39. async cpost(uri, data = {}, query, options) {
  40. return this.toRequest(uri, data, query, options);
  41. }
  42. async toRequest(uri, data, query, options) {
  43. query = _.pickBy(
  44. query,
  45. val => val !== '' && val !== 'undefined' && val !== 'null'
  46. );
  47. if (!uri) console.error('uri不能为空');
  48. if (_.isObject(query) && _.isObject(options)) {
  49. const params = query.params ? query.params : query;
  50. options = { ...options, params };
  51. } else if (_.isObject(query) && !query.params) {
  52. options = { params: query };
  53. } else if (_.isObject(query) && query.params) {
  54. options = query;
  55. }
  56. const headers = { 'content-type': 'application/json' };
  57. console.log(uri);
  58. const url = this.merge(`${uri}`, options.params);
  59. let res = await this.ctx.curl(url, {
  60. method: isNullOrUndefined(data) ? 'get' : 'post',
  61. url,
  62. data,
  63. dataType: 'json',
  64. headers,
  65. ...options,
  66. });
  67. if (res.status === 200) {
  68. res = res.data || {};
  69. const { errcode, errmsg, details } = res;
  70. if (errcode) {
  71. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  72. return { errcode, errmsg };
  73. }
  74. return res.data;
  75. }
  76. const { status } = res;
  77. console.warn(`[${uri}] fail: ${status}-${res.data.message} `);
  78. }
  79. }
  80. module.exports = HttpUtilService;