backend_srv.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. ///<reference path="../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import config from 'app/core/config';
  5. import coreModule from 'app/core/core_module';
  6. export class BackendSrv {
  7. inFlightRequests = {};
  8. HTTP_REQUEST_CANCELLED = -1;
  9. /** @ngInject */
  10. constructor(private $http, private alertSrv, private $rootScope, private $q, private $timeout) {
  11. }
  12. get(url, params?) {
  13. return this.request({ method: 'GET', url: url, params: params });
  14. }
  15. delete(url) {
  16. return this.request({ method: 'DELETE', url: url });
  17. }
  18. post(url, data) {
  19. return this.request({ method: 'POST', url: url, data: data });
  20. };
  21. patch(url, data) {
  22. return this.request({ method: 'PATCH', url: url, data: data });
  23. }
  24. put(url, data) {
  25. return this.request({ method: 'PUT', url: url, data: data });
  26. }
  27. requestErrorHandler(err) {
  28. if (err.isHandled) {
  29. return;
  30. }
  31. var data = err.data || { message: 'Unexpected error' };
  32. if (_.isString(data)) {
  33. data = { message: data };
  34. }
  35. if (err.status === 422) {
  36. this.alertSrv.set("Validation failed", data.message, "warning", 4000);
  37. throw data;
  38. }
  39. data.severity = 'error';
  40. if (err.status < 500) {
  41. data.severity = "warning";
  42. }
  43. if (data.message) {
  44. this.alertSrv.set("Problem!", data.message, data.severity, 10000);
  45. }
  46. throw data;
  47. }
  48. request(options) {
  49. options.retry = options.retry || 0;
  50. var requestIsLocal = options.url.indexOf('/') === 0;
  51. var firstAttempt = options.retry === 0;
  52. if (requestIsLocal && !options.hasSubUrl) {
  53. options.url = config.appSubUrl + options.url;
  54. options.hasSubUrl = true;
  55. }
  56. return this.$http(options).then(results => {
  57. if (options.method !== 'GET') {
  58. if (results && results.data.message) {
  59. if (options.showSuccessAlert !== false) {
  60. this.alertSrv.set(results.data.message, '', 'success', 3000);
  61. }
  62. }
  63. }
  64. return results.data;
  65. }, err => {
  66. // handle unauthorized
  67. if (err.status === 401 && firstAttempt) {
  68. return this.loginPing().then(() => {
  69. options.retry = 1;
  70. return this.request(options);
  71. });
  72. }
  73. this.$timeout(this.requestErrorHandler.bind(this, err), 50);
  74. throw err;
  75. });
  76. };
  77. addCanceler(requestId, canceler) {
  78. if (requestId in this.inFlightRequests) {
  79. this.inFlightRequests[requestId].push(canceler);
  80. } else {
  81. this.inFlightRequests[requestId] = [canceler];
  82. }
  83. }
  84. resolveCancelerIfExists(requestId) {
  85. var cancelers = this.inFlightRequests[requestId];
  86. if (!_.isUndefined(cancelers) && cancelers.length) {
  87. cancelers[0].resolve();
  88. }
  89. }
  90. datasourceRequest(options) {
  91. options.retry = options.retry || 0;
  92. // A requestID is provided by the datasource as a unique identifier for a
  93. // particular query. If the requestID exists, the promise it is keyed to
  94. // is canceled, canceling the previous datasource request if it is still
  95. // in-flight.
  96. var requestId = options.requestId;
  97. if (requestId) {
  98. this.resolveCancelerIfExists(requestId);
  99. // create new canceler
  100. var canceler = this.$q.defer();
  101. options.timeout = canceler.promise;
  102. this.addCanceler(requestId, canceler);
  103. }
  104. var requestIsLocal = options.url.indexOf('/') === 0;
  105. var firstAttempt = options.retry === 0;
  106. if (requestIsLocal && !options.hasSubUrl && options.retry === 0) {
  107. options.url = config.appSubUrl + options.url;
  108. }
  109. if (requestIsLocal && options.headers && options.headers.Authorization) {
  110. options.headers['X-DS-Authorization'] = options.headers.Authorization;
  111. delete options.headers.Authorization;
  112. }
  113. return this.$http(options).catch(err => {
  114. if (err.status === this.HTTP_REQUEST_CANCELLED) {
  115. throw {err, cancelled: true};
  116. }
  117. // handle unauthorized for backend requests
  118. if (requestIsLocal && firstAttempt && err.status === 401) {
  119. return this.loginPing().then(() => {
  120. options.retry = 1;
  121. if (canceler) {
  122. canceler.resolve();
  123. }
  124. return this.datasourceRequest(options);
  125. });
  126. }
  127. //populate error obj on Internal Error
  128. if (_.isString(err.data) && err.status === 500) {
  129. err.data = {
  130. error: err.statusText,
  131. response: err.data,
  132. };
  133. }
  134. // for Prometheus
  135. if (!err.data.message && _.isString(err.data.error)) {
  136. err.data.message = err.data.error;
  137. }
  138. throw err;
  139. }).finally(() => {
  140. // clean up
  141. if (options.requestId) {
  142. this.inFlightRequests[options.requestId].shift();
  143. }
  144. });
  145. };
  146. loginPing() {
  147. return this.request({url: '/api/login/ping', method: 'GET', retry: 1 });
  148. }
  149. search(query) {
  150. return this.get('/api/search', query);
  151. }
  152. getDashboard(type, slug) {
  153. return this.get('/api/dashboards/' + type + '/' + slug);
  154. }
  155. saveDashboard(dash, options) {
  156. options = (options || {});
  157. return this.post('/api/dashboards/db/', {dashboard: dash, overwrite: options.overwrite === true});
  158. }
  159. }
  160. coreModule.service('backendSrv', BackendSrv);