datasourceSrv.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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('datasourceSrv', function($q, $injector, $rootScope) {
  10. var self = this;
  11. this.init = function() {
  12. this.datasources = {};
  13. this.metricSources = [];
  14. this.annotationSources = [];
  15. _.each(config.datasources, function(value, key) {
  16. if (value.meta && value.meta.metrics) {
  17. self.metricSources.push({
  18. value: key === config.defaultDatasource ? null : key,
  19. name: key
  20. });
  21. }
  22. if (value.meta && value.meta.annotations) {
  23. self.annotationSources.push(value);
  24. }
  25. });
  26. };
  27. this.get = function(name) {
  28. if (!name) {
  29. return this.get(config.defaultDatasource);
  30. }
  31. if (this.datasources[name]) {
  32. return $q.when(this.datasources[name]);
  33. }
  34. return this.loadDatasource(name);
  35. };
  36. this.loadDatasource = function(name) {
  37. var dsConfig = config.datasources[name];
  38. if (!dsConfig) {
  39. return $q.reject({message: "Datasource named " + name + " was not found"});
  40. }
  41. var deferred = $q.defer();
  42. var pluginDef = dsConfig.meta;
  43. $rootScope.require([pluginDef.module], function() {
  44. var AngularService = $injector.get(pluginDef.serviceName);
  45. var instance = new AngularService(dsConfig, pluginDef);
  46. instance.meta = pluginDef;
  47. instance.name = name;
  48. self.datasources[name] = instance;
  49. deferred.resolve(instance);
  50. });
  51. return deferred.promise;
  52. };
  53. this.getAll = function() {
  54. return config.datasources;
  55. };
  56. this.getAnnotationSources = function() {
  57. return this.annotationSources;
  58. };
  59. this.getMetricSources = function() {
  60. return this.metricSources;
  61. };
  62. this.init();
  63. });
  64. });