datasource_variable.ts 2.1 KB

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