datasource_srv.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. define([
  2. 'angular',
  3. 'lodash',
  4. '../core_module',
  5. 'app/core/config',
  6. ],
  7. function (angular, _, coreModule, config) {
  8. 'use strict';
  9. coreModule.default.service('datasourceSrv', function($q, $injector) {
  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. meta: value.meta,
  21. });
  22. }
  23. if (value.meta && value.meta.annotations) {
  24. self.annotationSources.push(value);
  25. }
  26. });
  27. this.metricSources.sort(function(a, b) {
  28. if (a.meta.builtIn || a.name > b.name) {
  29. return 1;
  30. }
  31. if (a.name < b.name) {
  32. return -1;
  33. }
  34. return 0;
  35. });
  36. };
  37. this.get = function(name) {
  38. if (!name) {
  39. return this.get(config.defaultDatasource);
  40. }
  41. if (this.datasources[name]) {
  42. return $q.when(this.datasources[name]);
  43. }
  44. return this.loadDatasource(name);
  45. };
  46. this.loadDatasource = function(name) {
  47. var dsConfig = config.datasources[name];
  48. if (!dsConfig) {
  49. return $q.reject({message: "Datasource named " + name + " was not found"});
  50. }
  51. var deferred = $q.defer();
  52. var pluginDef = dsConfig.meta;
  53. console.log(pluginDef);
  54. System.import(pluginDef.module).then(function(plugin) {
  55. // check if its in cache now
  56. if (self.datasources[name]) {
  57. deferred.resolve(self.datasources[name]);
  58. return;
  59. }
  60. // plugin module needs to export a constructor function named Datasource
  61. if (!plugin.Datasource) {
  62. return;
  63. }
  64. var instance = $injector.instantiate(plugin.Datasource, {instanceSettings: dsConfig});
  65. instance.meta = pluginDef;
  66. instance.name = name;
  67. self.datasources[name] = instance;
  68. deferred.resolve(instance);
  69. }).catch(function(err) {
  70. console.log('Failed to load data source: ' + err);
  71. });
  72. return deferred.promise;
  73. };
  74. this.getAll = function() {
  75. return config.datasources;
  76. };
  77. this.getAnnotationSources = function() {
  78. return this.annotationSources;
  79. };
  80. this.getMetricSources = function() {
  81. return this.metricSources;
  82. };
  83. this.init();
  84. });
  85. });