SDKHttp.ts 5.03 KB
import { GAMEDATA, sdkEnv } from "../base/SDKConst";
import SignUtils from "../utils/SignUtils";

export default class SDKHttp {
    public static onErrorResponse: (data: any) => void;

    public static async httpRequest(url: string, method: string, data?: any, dataType: "json" | "string" = "json") {
        return new Promise<IResult<any>>((resolve, reject) => {
            data = {
                ...data,
                ver: GAMEDATA.version,
                gameid: GAMEDATA.game_id,
                sign_type: 'md5',
                time_stamp: (Math.floor(Date.now() / 1000)) + ''
            }
            //生成sign
            data = {
                ...data,
                sign: SignUtils.I.createSign(data)
            }
            if (data && typeof data === "object") {
                data = JSON.stringify(data);
            }
            console.error("sign"+ url+JSON.stringify(data))
            data = data || "";
            if (method == "GET" && data != "") {
                data = JSON.parse(data);
                let str = ''
                for (let key in data) {
                    str = str + `${key}` + '=' + `${data[key]}&`
                }
                url += "?" + str;
                data = "";
            }
            let info = "[url:" + url + ", data:" + data + "]";
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status >= 200 && xhr.status < 400) {
                        let responseText: any = xhr.responseText;
                        cc.log("responseText"+ responseText)
                        try {
                            responseText = JSON.parse(responseText);
                            // cc.log("responseText22", responseText)
                            if (url.indexOf('.json') > -1) {
                                resolve({ code: 0, data: responseText, msg: responseText.msg, servertime: responseText.servertime });
                            } else {
                                resolve({ code: +responseText.code, data: responseText.data, msg: responseText.msg, servertime: responseText.servertime });
                            }
                            return
                        } catch (ex) {
                            // console.error("httpRequest[parseError]:responseText=" + xhr.responseText);
                            resolve({ msg: "JSON parse error:" + ex.message, code: -1 });
                            return;
                        }
                    } else {
                        // console.error(xhr.status, '网络请求失败!');
                        resolve({ code: -5 });
                    }
                }
            };

            xhr.ontimeout = function (info): void {
                // cc.error("info1", info)
                resolve({ msg: `请求超时!`, code: -2 });
            }
            xhr.onerror = function (info): void {
                // cc.error("info2", info)
                resolve({ msg: `请求失败!`, code: -3 });
            }
            xhr.onabort = function (info): void {
                // cc.error("info3", info)
                resolve({ msg: `请求失败!`, code: -4 });
            }

            xhr.open(method, url, true);

            if (method == "POST") {
                xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")//application/x-www-form-urlencoded
                // if (cc.sys.os === 'Android') {
                //     cc.error("http__uid", AppSdkData.I.uid);
                //     xhr.setRequestHeader('Uuid', `${AppSdkData.I.uid}`);
                // } else {
                //     xhr.setRequestHeader('Uuid', `909`);
                // }

            }
            xhr.timeout = 3000;
            // console.log(data)
            xhr.send(data);
        });
    }

    public static withMock(url: string) {
        return sdkEnv.isDebug && window["MOCK"] && window["MOCK"][url];
    }
    public static mockData(url: string): Promise<IResult<any>> {
        let responseText = window["MOCK"][url]
        return Promise.resolve({ code: +responseText.code, data: responseText.data, msg: responseText.msg });
    }

    public static async httpGet(baseUrl: string, url: string, data?: any, dataType: "json" | "string" = "json") {
        if (this.withMock(url)) {
            return this.mockData(url);
        }

        url = baseUrl + url;
        let res = await this.httpRequest(url, "GET", data, dataType);
        if (this.onErrorResponse && !res.code) {
            //
            this.onErrorResponse(res);
        }
        return res;
    }

    public static async httpPost(baseUrl: string, url: string, data?: any, dataType: "json" | "string" = "json") {
        if (this.withMock(url)) {
            return this.mockData(url);
        }

        url = baseUrl + url;
        let res = await this.httpRequest(url, "POST", data, dataType);
        if (this.onErrorResponse && res.code) {
            //
            this.onErrorResponse(res);
        }
        return res
    }
}