1/**
2 * api Interceptor
3 *
4 * @module app/common/services/apiInterceptor
5 * @exports apiInterceptor
6 * @name apiInterceptor
7
8 * @version 0.0.1
9 */
10
11window.angular && (function (angular) {
12    'use strict';
13
14    angular
15        .module('app.common.services')
16        .service('apiInterceptor', ['$q', '$rootScope', 'dataService', function($q, $rootScope, dataService){
17            return {
18                'request': function(config){
19                    dataService.loading = true;
20                    config.timeout = 20000;
21                    return config;
22                },
23                'response': function(response){
24                    dataService.loading = false;
25
26                    //not interested in template requests
27                    if(!/^https?\:/i.test(response.config.url)){
28                        return response;
29                    }
30
31                    dataService.last_updated = new Date();
32                    if(!response){
33                        dataService.server_unreachable = true;
34                    }else{
35                        dataService.server_unreachable = false;
36                    }
37
38                    if(response && response.status == 'error' &&
39                       dataService.path != '/login'){
40                        $rootScope.$emit('timedout-user', {});
41                    }
42
43                    return response;
44                },
45                'responseError': function(rejection){
46                    if (dataService.ignoreHttpError === false)
47                    {
48                        // If unauthorized, log out
49                        if (rejection.status == 401){
50                            if (dataService.path != '/login'){
51                                $rootScope.$emit('timedout-user', {});
52                            }
53                        } else if (rejection.status == -1){
54                            dataService.server_unreachable = true;
55                        }
56
57                        dataService.loading = false;
58                    }
59                    return $q.reject(rejection);
60                }
61            };
62        }]);
63
64})(window.angular);
65