blob: ce47b670789c10f7afc20ae32dcfdb1114e6d9c4 [file] [log] [blame]
Iftekharul Islam99d199f2017-03-24 15:28:25 -05001/**
2 * api Interceptor
3 *
4 * @module app/common/services/apiInterceptor
5 * @exports apiInterceptor
6 * @name apiInterceptor
7
Iftekharul Islam99d199f2017-03-24 15:28:25 -05008 */
9
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070010window.angular && (function(angular) {
11 'use strict';
Iftekharul Islam99d199f2017-03-24 15:28:25 -050012
Andrew Geisslerd27bb132018-05-24 11:07:27 -070013 angular.module('app.common.services').service('apiInterceptor', [
14 '$q', '$rootScope', 'dataService',
15 function($q, $rootScope, dataService) {
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070016 return {
17 'request': function(config) {
18 dataService.loading = true;
19 // If caller has not defined a timeout, set to default of 20s
20 if (config.timeout == null) {
21 config.timeout = 20000;
22 }
23 return config;
24 },
25 'response': function(response) {
26 dataService.loading = false;
Iftekharul Islam99d199f2017-03-24 15:28:25 -050027
Andrew Geisslerd27bb132018-05-24 11:07:27 -070028 // not interested in template requests
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070029 if (!/^https?\:/i.test(response.config.url)) {
30 return response;
31 }
Iftekharul Islamcd789502017-04-19 14:37:55 -050032
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070033 dataService.last_updated = new Date();
34 if (!response) {
35 dataService.server_unreachable = true;
Andrew Geisslerd27bb132018-05-24 11:07:27 -070036 } else {
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070037 dataService.server_unreachable = false;
38 }
Iftekharul Islam99d199f2017-03-24 15:28:25 -050039
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070040 if (response && response.status == 'error' &&
Andrew Geisslerd27bb132018-05-24 11:07:27 -070041 dataService.path != '/login') {
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070042 $rootScope.$emit('timedout-user', {});
43 }
Iftekharul Islam99d199f2017-03-24 15:28:25 -050044
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070045 return response;
46 },
47 'responseError': function(rejection) {
48 if (dataService.ignoreHttpError === false) {
49 // If unauthorized, log out
50 if (rejection.status == 401) {
51 if (dataService.path != '/login') {
52 $rootScope.$emit('timedout-user', {});
53 }
Andrew Geisslerd27bb132018-05-24 11:07:27 -070054 } else if (rejection.status == -1) {
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070055 dataService.server_unreachable = true;
56 }
Ed Tanousbbcf6702017-10-06 13:53:06 -070057
Andrew Geisslerba5e3f32018-05-24 10:58:00 -070058 dataService.loading = false;
59 }
60 return $q.reject(rejection);
61 }
62 };
Andrew Geisslerd27bb132018-05-24 11:07:27 -070063 }
64 ]);
Ed Tanousbbcf6702017-10-06 13:53:06 -070065})(window.angular);