webservice.js 8.48 KB
Newer Older
eddie.woo's avatar
eddie.woo committed
1 2 3
/// <reference path="../../app.js" />

// apiInterceptor is responsible to handle the aspect of each request and response.
eddie.woo's avatar
eddie.woo committed
4 5
webservices.factory('apiInterceptor', ['$q', 'loginContext', '$log', '$window', '$injector','$cookies',
    function ($q, loginContext, $log, $window, $injector,$cookies) {
eddie.woo's avatar
eddie.woo committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
        'use strict';

        $log.debug('apiInterceptor.ctor()...');

        var apiToken = loginContext.apiToken;
        var tokenType = loginContext.tokenType;
        var webApiHostUrl = loginContext.apiHost + constant.webapi.prefix;
        //for vat api
        var vatWebApiHostUrl = loginContext.vatApiHost + constant.webapi.prefix;

        var redirectToLogOut = loginContext.redirectToLogOutFunction;

        return {
            //token save to services for further usage
            tokenType: tokenType,
eddie.woo's avatar
eddie.woo committed
21 22 23
            apiToken: function () {
                return apiToken;
            },
eddie.woo's avatar
eddie.woo committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
            webApiHostUrl: webApiHostUrl,
            //for vat api
            vatWebApiHostUrl: vatWebApiHostUrl,

            // On request success
            request: function (config) {

                // Check if this request is a web api call, we should only update url and header for each web api request.
                // Because angular will use the $http service as well internally, such as ng-include to request a html file from server.
                // Set this config to send request to a different web server will break the functions of angularJS.
                if (config.isWebApiRequest) {
                    config.headers = config.headers || {};
                    config.headers.Authorization = tokenType + ' ' + apiToken;
                    if (config.apiType == 'vat') {
                        config.url = vatWebApiHostUrl + config.url;
                    }
                    else {
                        config.url = webApiHostUrl + config.url;
                    }
                    config.withCredentials = true;

45
                    //废弃 token有效期会自动判断
eddie.woo's avatar
eddie.woo committed
46 47
                    // before each api call, try to ensure user account has not been expired
                    // otherwise, force user to login again
48 49 50 51 52 53
                    // var $http = $injector.get('$http');
                    // $http.get(loginContext.serverUrl + '/Account/CheckLoginStatus?_=' + (new Date).valueOf(), { isBusyRequest: false }).success(function (data) {
                    //     if (data === false) {
                    //         redirectToLogOut();
                    //     }
                    // });
eddie.woo's avatar
eddie.woo committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
                }

                return config;
            },
            // On request failure
            requestError: function (rejection) {
                $log.error(rejection); // Contains the data about the error on the request.

                // Return the promise rejection.
                return $q.reject(rejection);
            },
            // On response success
            response: function (response) {
                if (response.status === 401) {
                    redirectToLogOut();
69
                }else if (response.status === 403) {
gary's avatar
gary committed
70 71 72 73 74
                    swal({
                        title: "警告",
                        text: "很抱歉,您没有访问该接口的权限!",
                        type: "warning"
                    });
75
                    return;
gary's avatar
gary committed
76
                }
eddie.woo's avatar
eddie.woo committed
77 78 79 80 81
                var tmpToken = response.headers('refreshToken');
                if (!!tmpToken) {
                    apiToken = tmpToken;
                    $log.info('refresh token: ' + apiToken);
                }
eddie.woo's avatar
eddie.woo committed
82 83 84 85 86 87 88 89
                return response || $q.when(response);
            },
            // On response failture
            responseError: function (rejection) {
                $log.error(rejection); // Contains the data about the error.

                if (rejection.status === 401) {
                    redirectToLogOut();
90
                }else if (rejection.status === 403) {
gary's avatar
gary committed
91 92 93 94 95
                    swal({
                        title: "警告",
                        text: "很抱歉,您没有访问该接口的权限!",
                        type: "warning"
                    });
96
                    return;
gary's avatar
gary committed
97
                }
eddie.woo's avatar
eddie.woo committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

                // Return the promise rejection.
                return $q.reject(rejection);
            }
        };
    }])
.factory('requestNotificationInterceptor', ['$q', '$injector', '$log', function ($q, $injector, $log) {
    'use strict';

    $log.debug('busyRequestNotificationInterceptor.ctor()...');

    var busyRequestNotificationHub;
    var busyRequestUrl = null;
    var requestOntheWay = 0;

    function onRequestStarted(config) {
        if (config.isWebApiRequest && config.isBusyRequest) {
            //$log.debug('busyRequestNotificationInterceptor: Start busy request ' + config.url);
            //busyRequestNotificationHub = busyRequestNotificationHub || $injector.get('busyRequestNotificationHub');
            //busyRequestNotificationHub.requestStarted();
            //busyRequestUrl = config.url;
        }

        if (config && typeof (config.ignoreLoadingBar) !== 'undefined' && !config.ignoreLoadingBar) {
            requestOntheWay++;
        }

        if (requestOntheWay > 0) {
            $('#busy-indicator-container').show();
        }
    }

    function onRequestEnded(config) {
        if (busyRequestUrl && config.url === busyRequestUrl) {
            //$log.debug('busyRequestNotificationInterceptor: Finish busy request ' + config.url);
            //busyRequestNotificationHub = busyRequestNotificationHub || $injector.get('busyRequestNotificationHub');
            //busyRequestNotificationHub.requestEnded();
            //busyRequestUrl = null;
        }

        if (config && typeof (config.ignoreLoadingBar) !== 'undefined' && !config.ignoreLoadingBar) {
            requestOntheWay--;
        }

        if (requestOntheWay <= 0) {
            $('#busy-indicator-container').hide();
        }
    }

    return {
        // On request success
        request: function (config) {
            onRequestStarted(config);
            return config;
        },
        // On request failure
        requestError: function (rejection) {
            onRequestEnded(rejection.config);
            return $q.reject(rejection);
        },
        // On response success
        response: function (response) {
            onRequestEnded(response.config);
            return response || $q.when(response);
        },
        // On response failture
        responseError: function (rejection) {
            onRequestEnded(rejection.config);
            return $q.reject(rejection);
        }
    }
}]);

webservices.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('apiInterceptor');
    $httpProvider.interceptors.push('requestNotificationInterceptor');
}]);

// All web api request should use this service to create its config for request.
webservices.factory('apiConfig', ['$log', 'vatSessionService',
    function ($log, vatSessionService) {

        $log.debug('apiConfig.ctor()...');

        return {
            create: function (config) {
                var cfg = {
                    apiType: 'admin',
                    ignoreLoadingBar: false
                };
                if (config) {
                    cfg = _.extend(cfg, config);
                }

                cfg.isWebApiRequest = true;
193
                if (config && config.dbName) {
194
                    cfg.headers = { 'from': config.project.id  };
eddie.woo's avatar
eddie.woo committed
195 196
                }
                else {
197
                    if (vatSessionService.project && vatSessionService.project.id) {
198
                        cfg.headers = { 'from': vatSessionService.project.id  };
eddie.woo's avatar
eddie.woo committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
                    }
                }
                return cfg;
            },
            createVat: function (config) {
                var cfg = {
                    apiType: 'vat',
                    ignoreLoadingBar: false
                };
                if (config) {
                    cfg = _.extend(cfg, config);
                }

                cfg.isWebApiRequest = true;
                if (config && config.dbName) {
frank.xa.zhang's avatar
frank.xa.zhang committed
214
                    cfg.headers = { 'from': config.dbName + '@cn.pwc.com' };
eddie.woo's avatar
eddie.woo committed
215 216
                }
                else {
217
                    cfg.headers = { 'from': vatSessionService.project.id };
eddie.woo's avatar
eddie.woo committed
218 219 220 221 222 223 224
                }
                //$httpProvider.defaults.headers.common['from'] = vatSessionService.project.dbName + '@cn.pwc.com';
                //cfg.headers.from = vatSessionService.project.dbName+'@cn.pwc.com';
                return cfg;
            }
        };
    }]);