adapter.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { cloneDeep } from 'lodash';
  2. import { dispatch } from '../../../store/store';
  3. import { VariableAdapter } from '../adapters';
  4. import { ALL_VARIABLE_TEXT } from '../constants';
  5. import { optionPickerFactory } from '../pickers';
  6. import { setOptionAsCurrent, setOptionFromUrl } from '../state/actions';
  7. import { QueryVariableModel, VariableRefresh } from '../types';
  8. import { containsVariable, isAllVariable, toKeyedVariableIdentifier } from '../utils';
  9. import { QueryVariableEditor } from './QueryVariableEditor';
  10. import { updateQueryVariableOptions } from './actions';
  11. import { initialQueryVariableModelState, queryVariableReducer } from './reducer';
  12. export const createQueryVariableAdapter = (): VariableAdapter<QueryVariableModel> => {
  13. return {
  14. id: 'query',
  15. description: 'Variable values are fetched from a datasource query',
  16. name: 'Query',
  17. initialState: initialQueryVariableModelState,
  18. reducer: queryVariableReducer,
  19. picker: optionPickerFactory<QueryVariableModel>(),
  20. editor: QueryVariableEditor,
  21. dependsOn: (variable, variableToTest) => {
  22. return containsVariable(variable.query, variable.datasource?.uid, variable.regex, variableToTest.name);
  23. },
  24. setValue: async (variable, option, emitChanges = false) => {
  25. await dispatch(setOptionAsCurrent(toKeyedVariableIdentifier(variable), option, emitChanges));
  26. },
  27. setValueFromUrl: async (variable, urlValue) => {
  28. await dispatch(setOptionFromUrl(toKeyedVariableIdentifier(variable), urlValue));
  29. },
  30. updateOptions: async (variable, searchFilter) => {
  31. await dispatch(updateQueryVariableOptions(toKeyedVariableIdentifier(variable), searchFilter));
  32. },
  33. getSaveModel: (variable) => {
  34. const { index, id, state, global, queryValue, rootStateKey, ...rest } = cloneDeep(variable);
  35. // remove options
  36. if (variable.refresh !== VariableRefresh.never) {
  37. return { ...rest, options: [] };
  38. }
  39. return rest;
  40. },
  41. getValueForUrl: (variable) => {
  42. if (isAllVariable(variable)) {
  43. return ALL_VARIABLE_TEXT;
  44. }
  45. return variable.current.value;
  46. },
  47. };
  48. };