backendSrv.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'config',
  5. ],
  6. function (angular, _, config) {
  7. 'use strict';
  8. var module = angular.module('grafana.services');
  9. module.service('backendSrv', function($http, alertSrv, $timeout) {
  10. var self = this;
  11. this.get = function(url, params) {
  12. return this.request({ method: 'GET', url: url, params: params });
  13. };
  14. this.delete = function(url) {
  15. return this.request({ method: 'DELETE', url: url });
  16. };
  17. this.post = function(url, data) {
  18. return this.request({ method: 'POST', url: url, data: data });
  19. };
  20. this.put = function(url, data) {
  21. return this.request({ method: 'PUT', url: url, data: data });
  22. };
  23. this._handleError = function(err) {
  24. if (err.status === 422) {
  25. alertSrv.set("Validation failed", "", "warning", 4000);
  26. throw err.data;
  27. }
  28. var data = err.data || { message: 'Unexpected error' };
  29. if (_.isString(data)) {
  30. data = { message: data };
  31. }
  32. data.severity = 'error';
  33. if (err.status < 500) {
  34. data.severity = "warning";
  35. }
  36. if (data.message) {
  37. alertSrv.set("Problem!", data.message, data.severity, 10000);
  38. }
  39. throw data;
  40. };
  41. this.request = function(options) {
  42. var httpOptions = {
  43. url: config.appSubUrl + options.url,
  44. method: options.method,
  45. data: options.data,
  46. params: options.params,
  47. };
  48. return $http(httpOptions).then(function(results) {
  49. if (options.method !== 'GET') {
  50. if (results && results.data.message) {
  51. alertSrv.set(results.data.message, '', 'success', 3000);
  52. }
  53. }
  54. return results.data;
  55. }, function(err) {
  56. $timeout(function() {
  57. if (err.isHandled) { return; }
  58. self._handleError(err);
  59. }, 50);
  60. throw err;
  61. });
  62. };
  63. this.search = function(query) {
  64. return this.get('/api/search', query);
  65. };
  66. this.saveDashboard = function(dash) {
  67. return this.post('/api/dashboards/db/', {dashboard: dash});
  68. };
  69. });
  70. });