SDKHttpPlus.ts 5.17 KB
import { DEBUG } from "cc/env";
import { GAMEDATA, sdkEnv } from "../../framework/wxsdk/base/SDKConst";
import SDKHttp from "../../framework/wxsdk/http/SDKHttp";
import { WxHelper } from "./WxHelper";
import LogService from "../../framework/wxsdk/service/LogService";
import DataService from "../../framework/wxsdk/service/DataService";

sdkEnv.isDebug = DEBUG;
export default class SDKHttpPlus extends SDKHttp {

    public static async backRequest(url: string, method: string, data?: any, dataType: "json" | "string" = "json") {
        return new Promise<IResult<any>>((resolve, reject) => {
            data = {
                ...data,
                gameid: GAMEDATA.game_id,
            }

            if (data && typeof data === "object") {
                data = 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 + "]";
            // console.error("info", info)
            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 });
                            } else {
                                resolve({ code: +responseText.code, data: responseText.data, msg: responseText.msg });
                            }
                            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: -2 });
                    }
                }
            };

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

            xhr.timeout = 30000;
            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`);
                // }

            }
            console.log("data", data)
            xhr.send(data);
        });
    }

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

        url = baseUrl + url;
        return this.backRequest(url, "GET", data, dataType);
    }

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

        url = baseUrl + url;
        return this.backRequest(url, "POST", data, dataType);
    }
}

SDKHttp.onErrorResponse = async function (data: any) {
    console.log("onErrorResponse", data)
    if (data.code > 0) {
        LogService.I.dot("errCode", { form: data.code + "_" + DataService.I?.Data?.userId })
    } else {
        LogService.I.dot("errCode", { form: data.code })
    }
    if (data.code == 1008) {
        let ret = await WxHelper.showModal({
            title: '登录验证失败,请重新登录',
            content: data.msg,
            showCancel: false,
            confirmText: '重启'
        })
        if (ret) {
            WxHelper.restartMiniProgram();
        }
    }
    if (data.code == 1011000) {
        let ret = await WxHelper.showModal({
            title: '数据被修改',
            content: data.msg,
            showCancel: false,
            confirmText: '重启'
        })
        if (ret) {
            WxHelper.restartMiniProgram();
        }
    }
};