'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var fetch = require('isomorphic-fetch');
// import cookie from 'js-cookie';

var errorMessages = function errorMessages(res) {
    return res.status + ' ' + res.statusText;
};

function check401(res) {
    if (res.status === 401) {
        // location.href = '/login';
        console.log('401');
    }
    return res;
}

function check404(res) {
    if (res.status === 404) {
        // location.href='/404';
        return Promise.reject(errorMessages(res));
    }
    return res;
}

function jsonParse(res) {
    return res.json().then(function (json) {
        return _extends({}, res, { json: json });
    }).catch(function (err) {
        return _extends({}, res, { json: { status: 0, message: '数据加载错误!' } });
    });
}

function errorMessageParse(res) {
    var _res$json = res.json;
    var status = _res$json.status;
    var msg = _res$json.msg;
    var message = _res$json.message;
    var result = _res$json.result;

    if (status != 1) {
        return Promise.reject(msg || message);
    }
    return result;
}

function xFetch(url, options) {
    var opts = _extends({}, options);

    if (opts.method != 'GET') {
        opts.headers = _extends({}, opts.headers, {
            'content-type': 'application/x-www-form-urlencoded'
        });
    }

    return fetch(url, opts).then(check401).then(check404).then(jsonParse).then(errorMessageParse);
}

exports.default = xFetch;

//# sourceMappingURL=xFetch.js.map