Loading

fetchapi封装js调接口方法

js封装异步调接口的方法

  • 使用isomorphic-fetch库:npm install --save isomorphic-fetch es6-promise
    优点:可以同时照顾 node 和 browser 环境。
  • 使用form-datanpm install --save form-data
import 'isomorphic-fetch'
import 'form-data'

function prepend(prefix, name, separator) {
  //封装一个加前缀的方法
  if (prefix) {
    if (separator)
      return prefix + "." + name;

    return prefix + name;
  }
  return name;
}

function isObject(value) {
    var type = typeof value;
    return !!value && (type == 'object' || type == 'function');
}

function flatten(prefix, obj, map) {
  if (obj) {
    if (Array.isArray(obj)) {
      for (let i = 0; i < obj.length; i++) {
        var item = obj[i];
        flatten(prepend(prefix, "[" + i + "]", false), item, map);
      }
    } else if (isObject(obj)) {
      if (obj['__type__'] == 'map') {
        for (let key in obj) {
          if (key != '__type__')
            flatten(prepend(prefix, "[" + key + "]", false), obj[key], map);
        }
      } else if (obj instanceof File) {
        // deal with JS based file load
        map[prefix] = obj;
      } else {
        for (let key in obj) {
          flatten(prepend(prefix, key, true), obj[key], map);
        }
      }
    }
    else {
      map[prefix] = obj;
    }
  }
}

export function toFlattenMap(obj) {
  let map = {};

  flatten(null, obj, map);
  return map;
}

export function composeFetch(service, endpoint, data, headers) {
  let fullUrl = !!service ? service + endpoint : endpoint;

  let method = !!data && !!data.method ? data.method : 'POST';

  if (method == 'POST') {
    let formData = new FormData();
    if (!!data && !!data.commandObject) {
      let flattenMap = toFlattenMap(data.commandObject);
      for (let key in flattenMap) {
        formData.append(key, flattenMap[key]);
      }
    }
    //支持请求头的设置,电商接口的Content-Type与园区不同,因当前库已经在电商用户版使用,故优先为'Content-Type': 'application/json'
    return ({
      fullUrl,
      fetchData: headers
        ? {
          headers,
          //Credentials 标志设置为 true,从而向服务器发送 Cookies
          credentials: 'include', 
          method,
          body: formData
        }
        : {
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          credentials: 'include',
          method,
          body: JSON.stringify(data.commandObject)
        }
    });

  } else {
    let params = [];
    if (!!data && !!data.commandObject) {
      let flattenMap = toFlattenMap(data.commandObject);

      let i = 0;
      for (let key in flattenMap) {
        if (i++ == 0)
          params.push('?');
        else
          params.push('&')

        params.push(encodeURIComponent(key) + '=' + encodeURIComponent(flattenMap[key]));
      }

      if (params.length > 0)
        fullUrl = fullUrl + params.join('');
    }

    return ({
      fullUrl,
      fetchData: {
        credentials: 'include',
        method
      }
    });
  }
}

export function callApi(service, endpoint, data) {
  let fetchInfo = composeFetch(service, endpoint, data);

  return fetch(fetchInfo.fullUrl, fetchInfo.fetchData)
    .then((response) => {
      return response.text().then(text => text)
    })
    .then((response) => {
      // 长整型bug
      const data = JSON.parse(response.replace(/([^\\])":(\d{15,})/g, '$1":"$2"'))
      if (Number(data.errorCode) !== 200) {
        return Promise.reject(data)
      }
      return (data);
    });
}

export function callRaw(service, endpoint, data, headers) {
  let fetchInfo = composeFetch(service, endpoint, data, headers);
  return fetch(fetchInfo.fullUrl, fetchInfo.fetchData);
}

posted @ 2017-07-05 09:57  lewiskycc  阅读(567)  评论(0编辑  收藏  举报