12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- 'use strict';
- module.exports = {
-
- async http(url, data, method = 'POST') {
- const { ctx } = this;
- let targetUrl;
- if (url.includes('http')) {
- targetUrl = url;
- } else {
- targetUrl = this.app.config.baseUrl + url;
- }
- try {
- const res = await ctx.curl(targetUrl, {
- method,
- data,
- dataType: 'json',
- timing: true,
- headers: ctx.header,
- });
-
- if (res.res.timing.contentDownload > 1000) {
- ctx.logger.info(
- `${method}请求${targetUrl}响应耗时:${res.res.timing.contentDownload}ms`
- );
- }
-
- if (res.data.code !== 1) {
- throw res.data.msg;
- }
- return res.data;
- } catch (error) {
- ctx.logger.warn('请求错误:' + error);
- throw error;
- }
- },
-
- camelCase(val) {
- const arr = val.split('_');
- if (arr.length > 1) {
- if (arr[0] === '') {
- arr.splice(0, 1);
- }
- for (let i = 1; i < arr.length; i++) {
- arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
- }
- val = arr.join('');
- return val;
- }
- return false;
- },
-
- formaterResponse(obj) {
- if (Array.isArray(obj)) {
- obj.forEach(item => {
- return this.formaterResponse(item);
- });
- } else {
- Object.keys(obj).forEach(key => {
- const value = obj[key];
- if (this.camelCase(key)) {
- obj[this.camelCase(key)] = value;
- delete obj[key];
- }
- if (Array.isArray(value)) {
- value.forEach(node => {
- return this.formaterResponse(node);
- });
- }
- if (Object.prototype.toString.call(value) === '[object Object]') {
- return this.formaterResponse(value);
- }
- });
- return obj;
- }
- },
- };
|