fetch.js 11.6 KB
import 'es6-promise';
import fetch from 'isomorphic-fetch';
import getLocalForage from '../storage/localForage';
import { dispatch } from './commonUtils';
import * as types from '../redux/actionTypes';
import uuidv1 from 'uuid/v1';
//请求后端环境
let SERVER_DOMAIN = '/';
// if (window.evn == 'production') {
//     SERVER_DOMAIN = window.PRODUCTION_SERVER_DOMAIN;
// } else if (window.evn == 'development') {
//     SERVER_DOMAIN = window.DEVELOPMENT_SERVER_DOMAIN;
// } else if (window.evn == 'test') {
//     SERVER_DOMAIN = window.TEST_SERVER_DOMAIN;
// }

export const api_version = 'v1';
const checkStatus = (response) => {
    switch (response.status) {
        case 200:
            return response;
        case 409:
            return response;
        case 400:
            return response;
        case 401:
            dispatch({
                type: types.FETCH_FAIL,
                payload: '用户认证授权失败',
                meta: {
                    title: '用户认证授权失败',
                    description: '当前请求没有认证授权,请重新登录'
                }
            });
            return response;
        default:
            return response;
    }
};

const handleErrorStatus = (errorJSon = {}, data) => {
    const { code, errors, message, title, x_request_id } = errorJSon;
    const { __form_name = '' } = data, fields = [];
    switch (code) {
        case 400:
            break;
        case 401:
            dispatch({
                type: types.FETCH_FAIL,
                payload: { message, errors, title, x_request_id }
            });
            break;
        default:
            break;
    }
    console.log(__form_name);
    if (__form_name) {
        dispatch({
            type: '@@redux-form/SET_SUBMIT_FINALLY',
            meta: {
                form: __form_name,
                fields: fields,
                error: true
            }
        });
    }
};

const parseJSON = (response, data) => {
    let backJson;
    try {
        backJson = response.json();
        handleErrorStatus(backJson, data);
    } catch (error) {
        backJson = {};
        dispatch({
            type: types.FETCH_FAIL,
            payload: '解析JSON失败'
        });
    }
    return backJson;
};
const redirectFun = (back) => {
    if (back && back.redirect) {
        window.location.href = back.redirect;
    }
    return back;
};

const getToken = () => {
    return getLocalForage().getItem('tokens').then(function (value) {
        const { access_token = '' } = value || {};
        console.log(value);
        return access_token;
    }).catch(function (err) {
        console.log(err);
        return err;
    });
};

const fetchCatch = (err) => {
    console.log(err);
    dispatch({
        type: '@@redux-form/SET_SUBMIT_FINALLY',
        meta: {
            form: '',
            fields: [],
            error: true
        }
    });
    return err;
};

export const get = function* (url) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'get',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then((response) => {
        return parseJSON(response, unSerializeParams(url));
    }).then(redirectFun).catch(fetchCatch);
};

export const post = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 600,
        body: JSON.stringify(data)
    }; console.log("postpostpostpostpost", SERVER_DOMAIN, url);
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then((response) => {
        return parseJSON(response, data);
    }).catch(fetchCatch);
};

export const postFile = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300,
        body: data
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const put = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'put',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300,
        body: JSON.stringify(data)
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const del = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'delete',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const head = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'head',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300,
        body: JSON.stringify(data)
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const patch = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'patch',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300,
        body: JSON.stringify(data)
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const json = function* (url) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'get',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const postJson = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 600,
        body: JSON.stringify(data)
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const putJson = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'put',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300,
        body: JSON.stringify(data)
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const patchJson = function* (url, data = {}) {
    const token = yield getToken();
    const defaultOpt = {
        method: 'patch',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300,
        body: JSON.stringify(data)
    };
    return yield fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then(parseJSON).catch(fetchCatch);
};

export const serializeParams = (params) => {
    if (params && typeof (params) === "object") {
        const keys = Object.keys(params);
        let stringParams = ['?t=1'];
        keys.map((key, i) => {
            stringParams.push(key + "=" + encodeURIComponent(params[key]));
        });
        return stringParams.join("&");
    } else if (params && typeof (params) === "string") {
        return params;
    } else {
        return '';
    }
};

export const unSerializeParams = (url) => {
    const backParmas = {};
    if (url && typeof (url) === "string" && url.indexOf("?") != -1) {
        let parmas = [];
        if (url.split("?")[1]) {
            parmas = url.split("?")[1].split("&");
        }
        parmas.map((parma, i) => {
            if (parma && parma.indexOf("=" != -1)) {
                const temp = parma.split("=");
                backParmas[temp[0]] = decodeURIComponent(temp[1]);
            }
        });
        return backParmas;
    } else {
        return backParmas;
    }
};


export async function ajaxGet(url) {
    let token = '';
    await getLocalForage().getItem('tokens').then(function (value) {
        const { access_token = '' } = value || {};
        token = access_token;
        return access_token;
    }).catch(function (err) {
        console.log(err);
        return err;
    });
    const defaultOpt = {
        method: 'get',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 300
    };
    return fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then((response) => {
        return parseJSON(response, unSerializeParams(url));
    }).then(redirectFun).catch(fetchCatch);
}

export async function ajaxPost(url, data = {}) {
    let token = '';
    await getLocalForage().getItem('tokens').then(function (value) {
        const { access_token = '' } = value || {};
        token = access_token;
        return access_token;
    }).catch(function (err) {
        console.log(err);
        return err;
    });
    const defaultOpt = {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'Request-ID': uuidv1()
        },
        credentials: 'same-origin',
        timeout: 1000 * 600,
        body: JSON.stringify(data)
    };
    return fetch(`${SERVER_DOMAIN}${url}`, defaultOpt).then(checkStatus).then((response) => {
        return parseJSON(response, data);
    }).catch(fetchCatch);
}