service.js 4.64 KB

import { AsyncStorage ,NativeModules} from 'react-native';
import {getConfig} from "../index";
import MD5 from "md5"

const xnService= {
    getDetail: (data) => {
        data.method = "api.open.application.get.byCode";
        return post(data)
    },
};

// appKey需要提供给商城使用,保持export
let config = getConfig();
export const app_key = config.app_key; //dev
export const secret = config.secret; //dev

class ResponseError extends Error {
    constructor(message, code, origin) {
        super(message);
        this.code = code;
        this.origin = origin;
    }
}

export const isArray=(o)=> {
    return Object.prototype.toString.call(o) === '[object Array]';
};

async function getPostParameter (request){
    let post_data = '';
    let param_array = new Object();
    // this.passportId = await getPassportId();
    // this.identityId = await identityId();
    //
    // if (this.passportId != undefined && this.passportId != null && this.passportId > 0) {
    //     param_array.passportId = this.passportId;   //932843560934707200
    //     param_array.session = this.passportId;   //932843560934707200
    // }
    // if (this.identityId != undefined && this.identityId != null && this.identityId > 0) {
    //     param_array.identityId = this.identityId;
    //     param_array.session = this.identityId;
    // }

    param_array.format = 'json';
    param_array.sign_method = 'md5';
    param_array.timestamp = Date.parse(new Date());
    param_array.app_key = app_key;
    param_array.v = '1.0';

    for (let p in request) { // 方法
        if (request[p] != null && request[p] != undefined && typeof (request[p]) != "function") {
            param_array[p] = request[p];
        }
    } {
        let param_sign;
        let arrayKey = [];
        let arrayKeyTemp = [];
        for (let p in param_array) { // 方法
            if (typeof (param_array[p]) != "function") {
                arrayKeyTemp.push(p);
            }
        }
        // 最后显示所有的属性
        arrayKeyTemp.sort();
        let strTemp = secret;
        for (let i = 0; i < arrayKeyTemp.length; i++) {
            if (isArray(param_array[arrayKeyTemp[i]])) {
                strTemp = strTemp + arrayKeyTemp[i] + JSON.stringify(param_array[arrayKeyTemp[i]]);
            } else {
                strTemp = strTemp + arrayKeyTemp[i] + param_array[arrayKeyTemp[i]];
            }
        }
        strTemp = strTemp + secret;
        param_sign = MD5(strTemp).toString().toUpperCase();
        post_data = 'sign=' + param_sign.toUpperCase();
        for (let i = 0; i < arrayKeyTemp.length; i++) {
            if (isArray(param_array[arrayKeyTemp[i]])) {
                post_data = post_data + '&' + arrayKeyTemp[i] + '=' + encodeURIComponent(JSON.stringify(param_array[arrayKeyTemp[i]]));
            } else {
                post_data = post_data + '&' + arrayKeyTemp[i] + '=' + encodeURIComponent(param_array[arrayKeyTemp[i]]);
            }
        }
    }

    return post_data;
}

async function request(url,data, _options) {
    let error = false;
    const options = _options || {};
    options.method = options.method || 'GET';
    options.headers = options.headers || {};

    options.body=await getPostParameter(data);

    let newFetch = async function(){
        return Promise.race([
            fetch(url.toString(),options),
            new Promise((resolve,reject) => {
                setTimeout(()=> {
                    reject(new Error("请求超时,请稍后重试!"))
                },10000)
            }).then((data)=>{

            }).catch((error)=>{
                return {code:'error',message:global.isConnected ? '请求超时,请稍后重试!' : '网络异常,请稍后重试!', desc:global.isConnected ? '请求超时,请稍后重试!' : '网络异常,请稍后重试!'};
            })
        ]);
    };
    //
    const resp = await newFetch();
    let json;
    if(resp.type){
        json = JSON.parse(await resp.text());
    }else{
        json = resp;
    }

    // 如果请求失败
    if (resp.status && resp.status !== 200) {
        if (resp.status === 401) {
            console.log(resp.status);
        }
        throw new ResponseError(json.message, resp.status, json);
    }
    // 服务不可用
    if (json.code != 'error' && json.message) {
        throw new ResponseError(json.message, resp.status, json);
    }
    return json;
}

//post
export function post(data, options) {
    config = getConfig();
    return request(config.apiUrl,data, {
        method: 'POST',
        mode: "cors",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        ...options,
    });
}

export default xnService;