http-util.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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(query, val => val !== '' && val !== 'undefined' && val !== 'null');
  44. if (!uri) console.error('uri不能为空');
  45. if (_.isObject(query) && _.isObject(options)) {
  46. const params = query.params ? query.params : query;
  47. options = { ...options, params };
  48. } else if (_.isObject(query) && !query.params) {
  49. options = { params: query };
  50. } else if (_.isObject(query) && query.params) {
  51. options = query;
  52. }
  53. const headers = { 'content-type': 'application/json' };
  54. console.log(uri);
  55. const url = this.merge(`${uri}`, options.params);
  56. let res = await this.ctx.curl(url, {
  57. method: isNullOrUndefined(data) ? 'get' : 'post',
  58. url,
  59. data,
  60. dataType: 'json',
  61. headers,
  62. ...options,
  63. });
  64. if (res.status === 200) {
  65. res = res.data || {};
  66. const { errcode, errmsg, details } = res;
  67. if (errcode) {
  68. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  69. return { errcode, errmsg };
  70. }
  71. return res.data;
  72. }
  73. const { status } = res;
  74. console.warn(`[${uri}] fail: ${status}-${res.data.message} `);
  75. }
  76. }
  77. module.exports = HttpUtilService;