datasource_variable.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import kbn from 'app/core/utils/kbn';
  2. import { Variable, containsVariable, assignModelProperties, variableTypes } from './variable';
  3. export class DatasourceVariable implements Variable {
  4. regex: any;
  5. query: string;
  6. options: any;
  7. current: any;
  8. refresh: any;
  9. defaults = {
  10. type: 'datasource',
  11. name: '',
  12. hide: 0,
  13. label: '',
  14. current: {},
  15. regex: '',
  16. options: [],
  17. query: '',
  18. refresh: 1,
  19. };
  20. /** @ngInject **/
  21. constructor(private model, private datasourceSrv, private variableSrv, private templateSrv) {
  22. assignModelProperties(this, model, this.defaults);
  23. this.refresh = 1;
  24. }
  25. getSaveModel() {
  26. assignModelProperties(this.model, this, this.defaults);
  27. // don't persist options
  28. this.model.options = [];
  29. return this.model;
  30. }
  31. setValue(option) {
  32. return this.variableSrv.setOptionAsCurrent(this, option);
  33. }
  34. updateOptions() {
  35. var options = [];
  36. var sources = this.datasourceSrv.getMetricSources({ skipVariables: true });
  37. var regex;
  38. if (this.regex) {
  39. regex = this.templateSrv.replace(this.regex, null, 'regex');
  40. regex = kbn.stringToJsRegex(regex);
  41. }
  42. for (var i = 0; i < sources.length; i++) {
  43. var source = sources[i];
  44. // must match on type
  45. if (source.meta.id !== this.query) {
  46. continue;
  47. }
  48. if (regex && !regex.exec(source.name)) {
  49. continue;
  50. }
  51. options.push({ text: source.name, value: source.name });
  52. }
  53. if (options.length === 0) {
  54. options.push({ text: 'No data sources found', value: '' });
  55. }
  56. this.options = options;
  57. return this.variableSrv.validateVariableSelectionState(this);
  58. }
  59. dependsOn(variable) {
  60. if (this.regex) {
  61. return containsVariable(this.regex, variable.name);
  62. }
  63. return false;
  64. }
  65. setValueFromUrl(urlValue) {
  66. return this.variableSrv.setOptionFromUrl(this, urlValue);
  67. }
  68. getValueForUrl() {
  69. return this.current.value;
  70. }
  71. }
  72. variableTypes['datasource'] = {
  73. name: 'Datasource',
  74. ctor: DatasourceVariable,
  75. description: 'Enabled you to dynamically switch the datasource for multiple panels',
  76. };