请求接口封装

/**
 * REST API 封装
 */
(function (root, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            root.lc = factory();
})(this, function () {
    var root = window;

    function ExportClass() {
        var host_ = 'http://localhost:8080';
        var username_ = '';
        var password_ = '';
        var mac_ = '08:57:00:D7:9C:43';
        var projectVersion_ = '1.0';
        var projectName_ = 'Base';
        var clientPushID = '';
        //计错误码412的次数
        var errorCodeTimes = 0;
        var clientId="";
        if (util.isApp()) {
            try {
                host_ = util.localData.read('url/api');
                username_ = util.runtimeData.read('username');
                password_ = util.runtimeData.read('password');
                mac_ = window.native.query('GetMacAddress');
                projectVersion_ = util.localData.read('meta/version');
                projectName_ = util.localData.read('meta/name');
                clientPushID = util.localData.read('user/UniqueID');
                clientId = util.runtimeData.read('config/clientid');
            } catch (err) {
                console.info(err);
            }
        }

        // 接口请求函数
        // 某些情况下,服务端返回200,并且apicode==1000,但结果仍然是不正确的,
        // 此时需要用cbCustomCheckResponse进行额外检查
        function requestCivil(method, data, cbSuccess, cbError, cbCustomCheckResponse) {
            var httpMethod = 'POST';
            var path = '/civil/api/' + method;
            var clientType = 'web';
            var content = {
                'method' : method,
                'clientType' : clientType,
                'clientMac' : mac_,
                'clientPushId' : clientPushID,
                'project' : projectName_,
                'data' : data
            };
            var contentmd5 = algor.md5(JSON.stringify(content));
            var date = data['x-hs-date'] || dateFormat(util.now());
            var signature = httpMethod + '\n' +
                path + '\n' +
                'x-hs-apiver:' + projectVersion_ + '\n' +
                'x-hs-clientid:' + clientId + '\n' +
                'x-hs-contentmd5:' + contentmd5 + '\n' +
                'x-hs-date:' + date + '\n' +
                'x-hs-username:' + username_ + '\n';
            signature = algor.b64_hmac_sha1(password_, signature);

            var xhr = $.ajax({
                timeout : 20000,
                dataType : 'json',
                type : httpMethod,
                url : host_ + path,
                data : JSON.stringify(content),
                beforeSend : function (request) {
                    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
                    request.setRequestHeader('x-hs-apiver', projectVersion_);
                    request.setRequestHeader('x-hs-clientid', clientId);
                    request.setRequestHeader('x-hs-contentmd5', contentmd5);
                    request.setRequestHeader('x-hs-date', date);
                    request.setRequestHeader('x-hs-username', username_);
                    request.setRequestHeader('x-hs-signature', signature);
                    request.setRequestHeader("Connection", "close");
                },
                complete : function(XMLHttpRequest, status) {
                    if (status == 'timeout') {
                        util.toast("网络异常,请检查网络");
                    }
                },
                success : function (result) {
                    var resp = {};
                    if (result.responseText && result.responseText.length) {
                        try {
                            resp = JSON.parse(result.responseText);
                        } catch (err) {}
                    } else if (typeof result.code === 'number') {
                        resp = result;
                    }

                    if (resp.code === 1000) {
                        var br = true;

                        // 额外检查
                        if (typeof cbCustomCheckResponse === 'function') {
                            br = cbCustomCheckResponse(resp);
                        }

                        var cb = br ? cbSuccess : cbError;

                        if (typeof cb === 'function') {
                            cb(br ? resp.data : result);
                            
                        }
                    } else if(resp.code === 1107) {
                        //关闭录像播放界面
                        setTimeout(function(){$('.playback-win-hd').parents('.u-win').find('.j-win-close').click();},10)
                        //关闭完录像后,将视频全部关闭,再退出。
                        ddsocx.StopAllvideo();
                        $("#j-password-lock").css("display","block");
                        $("#coverAll").css("display","block");
                        localStorage.removeItem('recordCode');
                        localStorage.removeItem('videoCode');
                    } else if(resp.code === 1112){
                        $('#loading').hide();
                        //关闭录像播放界面
                        setTimeout(function(){$('.playback-win-hd').parents('.u-win').find('.j-win-close').click();},10)
                        //关闭完录像后,将视频全部关闭,再退出。
                        ddsocx.StopAllvideo();
                        $("#j-single-login").css("display","block");
                        $("#coverAll").css("display","block");
                        localStorage.removeItem('recordCode');
                        localStorage.removeItem('videoCode');
                    } else {
                        if (typeof cbError === 'function') {
                            cbError(result);
                        }
                    }
                },
                error : function (result) {
                    if (result.status == 401) {
                        //关闭录像播放界面
                        setTimeout(function(){$('.playback-win-hd').parents('.u-win').find('.j-win-close').click();},10)
                        //关闭完录像后,将视频全部关闭,再退出。
                        ddsocx.StopAllvideo();
                        $("#j-modify-password").css("display","block");
                        $("#coverAll").css("display","block");
                        localStorage.removeItem('recordCode');
                        localStorage.removeItem('videoCode');
                    }else if (result.status == 0) {
                        util.toast("网络异常,请检查网络");
                        cbError(result);
                    }else if (result.status === 412) {
                        //客户端所带的x-hs-date时间与服务器时间相差过大, 重新请求
                        if(errorCodeTimes < 3){
                            errorCodeTimes ++;
                            data['x-hs-date'] = xhr.getResponseHeader("x-hs-date");
                            console.info(result.getResponseHeader("x-hs-date"));
                            request(method, data, cbSuccess, cbError, cbCustomCheckResponse);
                        }else{
                            errorCodeTimes = 0;
                            util.toast("本地时间不正确,请检查本地时间");
                            setTimeout(function() {
                                 window.native.query('Logout');
                                 localStorage.removeItem('recordCode');
                                localStorage.removeItem('videoCode');
                            }, 3000);
                        }

                    }else if (result.status === 200) {
                        var resp = {};
                        try {
                            resp = JSON.parse(result.responseText);
                            if (resp.code === 1000) {
                                if (typeof cbSuccess === 'function') {
                                    cbSuccess(resp.data);
                                }
                                return;
                            }else if(resp.code === 1112){
                                $('#loading').hide();
                                $("#j-single-login").css("display","block");
                                $("#coverAll").css("display","block");
                                localStorage.removeItem('recordCode');
                                localStorage.removeItem('videoCode');
                            }
                        } catch (err) {
                            console.info(err);
                        }

                        if (typeof cbError === 'function') {
                            cbError(result);
                        }
                    }else if (result.status === 403) {
                        util.toast("无权限");
                        $('.loading').hide();
                        return;
                    }else{
                        cbError(result);
                    }

                }
            });
        }
        
        
        // ---------------- 外部接口 ----------------

        //function requestDMS(httpMethod, path, strData, cbSuccess, cbError)

        this.getList = function (parm, cbSuccess, cbError) {

            var httpMethod = 'GET';
            var strData = null;

            var dmsUrl  = "/device/"+parm+"/breathing-light";

            requestDMS(httpMethod, dmsUrl, strData, cbSuccess, cbError)
        }    


    }

    return new ExportClass();
});
 

转载于:https://my.oschina.net/niejianbo/blog/873161

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值