dashboardLoaderSrv.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. define([
  2. 'angular',
  3. 'moment',
  4. 'lodash',
  5. 'jquery',
  6. 'kbn',
  7. ],
  8. function (angular, moment, _, $, kbn) {
  9. 'use strict';
  10. var module = angular.module('grafana.services');
  11. module.service('dashboardLoaderSrv', function(backendSrv,
  12. dashboardSrv,
  13. datasourceSrv,
  14. $http, $q, $timeout,
  15. contextSrv, $routeParams,
  16. $rootScope) {
  17. var self = this;
  18. this._dashboardLoadFailed = function(title) {
  19. return {meta: {canStar: false, canDelete: false, canSave: false}, dashboard: {title: title}};
  20. };
  21. this.loadDashboard = function(type, slug) {
  22. if (type === 'script') {
  23. return this._loadScriptedDashboard(slug);
  24. }
  25. if (type === 'snapshot') {
  26. return backendSrv.get('/api/snapshots/' + $routeParams.slug).catch(function() {
  27. return {meta:{isSnapshot: true, canSave: false, canEdit: false}, dashboard: {title: 'Snapshot not found'}};
  28. });
  29. }
  30. return backendSrv.getDashboard($routeParams.type, $routeParams.slug).catch(function() {
  31. return self._dashboardLoadFailed("Not found");
  32. });
  33. };
  34. this._loadScriptedDashboard = function(file) {
  35. var url = 'public/dashboards/'+file.replace(/\.(?!js)/,"/") + '?' + new Date().getTime();
  36. return $http({ url: url, method: "GET" })
  37. .then(this._executeScript).then(function(result) {
  38. return { meta: { fromScript: true, canDelete: false, canSave: false, canStar: false}, dashboard: result.data };
  39. }, function(err) {
  40. console.log('Script dashboard error '+ err);
  41. $rootScope.appEvent('alert-error', ["Script Error", "Please make sure it exists and returns a valid dashboard"]);
  42. return self._dashboardLoadFailed('Scripted dashboard');
  43. });
  44. };
  45. this._executeScript = function(result) {
  46. var services = {
  47. dashboardSrv: dashboardSrv,
  48. datasourceSrv: datasourceSrv,
  49. $q: $q,
  50. };
  51. /*jshint -W054 */
  52. var script_func = new Function('ARGS','kbn','_','moment','window','document','$','jQuery', 'services', result.data);
  53. var script_result = script_func($routeParams, kbn, _ , moment, window, document, $, $, services);
  54. // Handle async dashboard scripts
  55. if (_.isFunction(script_result)) {
  56. var deferred = $q.defer();
  57. script_result(function(dashboard) {
  58. $timeout(function() {
  59. deferred.resolve({ data: dashboard });
  60. });
  61. });
  62. return deferred.promise;
  63. }
  64. return { data: script_result };
  65. };
  66. });
  67. });