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