reducer.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { createSlice, PayloadAction } from '@reduxjs/toolkit';
  2. import { DataSourceInstanceSettings } from '@grafana/data';
  3. import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE } from '../constants';
  4. import { getInstanceState } from '../state/selectors';
  5. import { initialVariablesState, VariablePayload, VariablesState } from '../state/types';
  6. import { DataSourceVariableModel, initialVariableModelState, VariableOption, VariableRefresh } from '../types';
  7. export const initialDataSourceVariableModelState: DataSourceVariableModel = {
  8. ...initialVariableModelState,
  9. type: 'datasource',
  10. current: {} as VariableOption,
  11. regex: '',
  12. options: [],
  13. query: '',
  14. multi: false,
  15. includeAll: false,
  16. refresh: VariableRefresh.onDashboardLoad,
  17. };
  18. export const dataSourceVariableSlice = createSlice({
  19. name: 'templating/datasource',
  20. initialState: initialVariablesState,
  21. reducers: {
  22. createDataSourceOptions: (
  23. state: VariablesState,
  24. action: PayloadAction<VariablePayload<{ sources: DataSourceInstanceSettings[]; regex: RegExp | undefined }>>
  25. ) => {
  26. const { sources, regex } = action.payload.data;
  27. const options: VariableOption[] = [];
  28. const instanceState = getInstanceState<DataSourceVariableModel>(state, action.payload.id);
  29. for (let i = 0; i < sources.length; i++) {
  30. const source = sources[i];
  31. // must match on type
  32. if (source.meta.id !== instanceState.query) {
  33. continue;
  34. }
  35. if (isValid(source, regex)) {
  36. options.push({ text: source.name, value: source.name, selected: false });
  37. }
  38. if (isDefault(source, regex)) {
  39. options.push({ text: 'default', value: 'default', selected: false });
  40. }
  41. }
  42. if (options.length === 0) {
  43. options.push({ text: 'No data sources found', value: '', selected: false });
  44. }
  45. if (instanceState.includeAll) {
  46. options.unshift({ text: ALL_VARIABLE_TEXT, value: ALL_VARIABLE_VALUE, selected: false });
  47. }
  48. instanceState.options = options;
  49. },
  50. },
  51. });
  52. function isValid(source: DataSourceInstanceSettings, regex?: RegExp) {
  53. if (!regex) {
  54. return true;
  55. }
  56. return regex.exec(source.name);
  57. }
  58. function isDefault(source: DataSourceInstanceSettings, regex?: RegExp) {
  59. if (!source.isDefault) {
  60. return false;
  61. }
  62. if (!regex) {
  63. return true;
  64. }
  65. return regex.exec('default');
  66. }
  67. export const dataSourceVariableReducer = dataSourceVariableSlice.reducer;
  68. export const { createDataSourceOptions } = dataSourceVariableSlice.actions;