actions.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { chain } from 'lodash';
  2. import { stringToJsRegex } from '@grafana/data';
  3. import { getTemplateSrv } from '@grafana/runtime';
  4. import { ThunkResult } from '../../../types';
  5. import { getDatasourceSrv } from '../../plugins/datasource_srv';
  6. import { changeVariableEditorExtended } from '../editor/reducer';
  7. import { validateVariableSelectionState } from '../state/actions';
  8. import { toKeyedAction } from '../state/keyedVariablesReducer';
  9. import { getVariable } from '../state/selectors';
  10. import { KeyedVariableIdentifier } from '../state/types';
  11. import { DataSourceVariableModel } from '../types';
  12. import { toVariablePayload } from '../utils';
  13. import { createDataSourceOptions } from './reducer';
  14. export interface DataSourceVariableActionDependencies {
  15. getDatasourceSrv: typeof getDatasourceSrv;
  16. }
  17. export const updateDataSourceVariableOptions =
  18. (
  19. identifier: KeyedVariableIdentifier,
  20. dependencies: DataSourceVariableActionDependencies = { getDatasourceSrv: getDatasourceSrv }
  21. ): ThunkResult<void> =>
  22. async (dispatch, getState) => {
  23. const { rootStateKey } = identifier;
  24. const sources = dependencies.getDatasourceSrv().getList({ metrics: true, variables: false });
  25. const variableInState = getVariable<DataSourceVariableModel>(identifier, getState());
  26. let regex;
  27. if (variableInState.regex) {
  28. regex = getTemplateSrv().replace(variableInState.regex, undefined, 'regex');
  29. regex = stringToJsRegex(regex);
  30. }
  31. dispatch(toKeyedAction(rootStateKey, createDataSourceOptions(toVariablePayload(identifier, { sources, regex }))));
  32. await dispatch(validateVariableSelectionState(identifier));
  33. };
  34. export const initDataSourceVariableEditor =
  35. (
  36. key: string,
  37. dependencies: DataSourceVariableActionDependencies = { getDatasourceSrv: getDatasourceSrv }
  38. ): ThunkResult<void> =>
  39. (dispatch) => {
  40. const dataSources = dependencies.getDatasourceSrv().getList({ metrics: true, variables: true });
  41. const dataSourceTypes = chain(dataSources)
  42. .uniqBy('meta.id')
  43. .map((ds: any) => {
  44. return { text: ds.meta.name, value: ds.meta.id };
  45. })
  46. .value();
  47. dataSourceTypes.unshift({ text: '', value: '' });
  48. dispatch(toKeyedAction(key, changeVariableEditorExtended({ dataSourceTypes })));
  49. };