@grafana/data#DataSourceSettings TypeScript Examples

The following examples show how to use @grafana/data#DataSourceSettings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataSourceHttpSettings.story.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
settingsMock: DataSourceSettings<any, any> = {
  id: 4,
  orgId: 1,
  name: 'gdev-influxdb',
  type: 'influxdb',
  typeLogoUrl: '',
  access: 'direct',
  url: 'http://localhost:8086',
  password: '',
  user: 'grafana',
  database: 'site',
  basicAuth: false,
  basicAuthUser: '',
  basicAuthPassword: '',
  withCredentials: false,
  isDefault: false,
  jsonData: {
    timeInterval: '15s',
    httpMode: 'GET',
    keepCookies: ['cookie1', 'cookie2'],
  },
  secureJsonData: {
    password: true,
  },
  readOnly: true,
}
Example #2
Source File: CustomHeaderSettings.story.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
simple = () => {
  const dataSourceConfig: DataSourceSettings<any, any> = {
    id: 4,
    orgId: 1,
    name: 'gdev-influxdb',
    type: 'influxdb',
    typeLogoUrl: '',
    access: 'direct',
    url: 'http://localhost:8086',
    password: '',
    user: 'grafana',
    database: 'site',
    basicAuth: false,
    basicAuthUser: '',
    basicAuthPassword: '',
    withCredentials: false,
    isDefault: false,
    jsonData: {
      timeInterval: '15s',
      httpMode: 'GET',
      keepCookies: ['cookie1', 'cookie2'],
      httpHeaderName1: 'X-Custom-Header',
    },
    secureJsonData: {
      password: true,
      httpHeaderValue1: 'X-Custom-Header',
    },
    secureJsonFields: {
      httpHeaderValue1: true,
    },
    readOnly: true,
  };

  return <CustomHeadersSettings dataSourceConfig={dataSourceConfig} onChange={() => {}} />;
}
Example #3
Source File: DataSourceDashboards.test.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
setup = (propOverrides?: object) => {
  const props: Props = {
    navModel: {} as NavModel,
    dashboards: [] as PluginDashboard[],
    dataSource: {} as DataSourceSettings,
    pageId: 1,
    importDashboard: jest.fn(),
    loadDataSource: jest.fn(),
    loadPluginDashboards: jest.fn(),
    removeDashboard: jest.fn(),
    isLoading: false,
  };

  Object.assign(props, propOverrides);

  return shallow(<DataSourceDashboards {...props} />);
}
Example #4
Source File: DataSourcesListPage.test.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
setup = (propOverrides?: object) => {
  const props: Props = {
    dataSources: [] as DataSourceSettings[],
    layoutMode: LayoutModes.Grid,
    loadDataSources: jest.fn(),
    navModel: {
      main: {
        text: 'Configuration',
      },
      node: {
        text: 'Data Sources',
      },
    } as NavModel,
    dataSourcesCount: 0,
    searchQuery: '',
    setDataSourcesSearchQuery,
    setDataSourcesLayoutMode,
    hasFetched: false,
  };

  Object.assign(props, propOverrides);

  return shallow(<DataSourcesListPage {...props} />);
}
Example #5
Source File: dataSourcesMocks.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getMockDataSources = (amount: number) => {
  const dataSources = [];

  for (let i = 0; i <= amount; i++) {
    dataSources.push({
      access: '',
      basicAuth: false,
      database: `database-${i}`,
      id: i,
      isDefault: false,
      jsonData: { authType: 'credentials', defaultRegion: 'eu-west-2' },
      name: `dataSource-${i}`,
      orgId: 1,
      password: '',
      readOnly: false,
      type: 'cloudwatch',
      typeLogoUrl: 'public/app/plugins/datasource/cloudwatch/img/amazon-web-services.png',
      url: '',
      user: '',
    });
  }

  return dataSources as DataSourceSettings[];
}
Example #6
Source File: dataSourcesMocks.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getMockDataSource = (): DataSourceSettings => {
  return {
    access: '',
    basicAuth: false,
    basicAuthUser: '',
    basicAuthPassword: '',
    withCredentials: false,
    database: '',
    id: 13,
    isDefault: false,
    jsonData: { authType: 'credentials', defaultRegion: 'eu-west-2' },
    name: 'gdev-cloudwatch',
    orgId: 1,
    password: '',
    readOnly: false,
    type: 'cloudwatch',
    typeLogoUrl: 'public/app/plugins/datasource/cloudwatch/img/amazon-web-services.png',
    url: '',
    user: '',
  };
}
Example #7
Source File: mocks.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
export function createDatasourceSettings<T>(jsonData: T): DataSourceSettings<T> {
  return {
    id: 0,
    orgId: 0,
    name: 'datasource-test',
    typeLogoUrl: '',
    type: 'datasource',
    access: 'server',
    url: 'http://localhost',
    password: '',
    user: '',
    database: '',
    basicAuth: false,
    basicAuthPassword: '',
    basicAuthUser: '',
    isDefault: false,
    jsonData,
    readOnly: false,
    withCredentials: false,
  };
}
Example #8
Source File: ConfigEditor.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
makeJsonUpdater = <T extends any>(field: keyof LokiOptions) => (
  options: DataSourceSettings<LokiOptions>,
  value: T
): DataSourceSettings<LokiOptions> => {
  return {
    ...options,
    jsonData: {
      ...options.jsonData,
      [field]: value,
    },
  };
}
Example #9
Source File: mocks.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
export function createDefaultConfigOptions(): DataSourceSettings<ElasticsearchOptions> {
  return createDatasourceSettings<ElasticsearchOptions>({
    timeField: '@time',
    esVersion: 70,
    interval: 'Hourly',
    timeInterval: '10s',
    maxConcurrentShardRequests: 300,
    logMessageField: 'test.message',
    logLevelField: 'test.level',
  });
}
Example #10
Source File: ElasticDetails.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
changeHandler = (
  key: keyof DataSourceSettings<ElasticsearchOptions>,
  value: Props['value'],
  onChange: Props['onChange']
) => (event: React.SyntheticEvent<HTMLInputElement | HTMLSelectElement>) => {
  onChange({
    ...value,
    [key]: event.currentTarget.value,
  });
}
Example #11
Source File: reducers.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
initialState: DataSourcesState = {
  dataSources: [],
  plugins: [],
  categories: [],
  dataSource: {} as DataSourceSettings,
  layoutMode: LayoutModes.List,
  searchQuery: '',
  dataSourcesCount: 0,
  dataSourceTypeSearchQuery: '',
  hasFetched: false,
  isLoadingDataSources: false,
  dataSourceMeta: {} as DataSourcePluginMeta,
}
Example #12
Source File: mocks.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function createDefaultConfigOptions(): DataSourceSettings<LokiOptions> {
  return createDatasourceSettings<LokiOptions>({
    maxLines: '531',
  });
}
Example #13
Source File: selectors.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
getDataSource = (state: DataSourcesState, dataSourceId: UrlQueryValue): DataSourceSettings | null => {
  if (state.dataSource.id === parseInt(dataSourceId as string, 10)) {
    return state.dataSource;
  }
  return {} as DataSourceSettings;
}
Example #14
Source File: selectors.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
getDataSources = (state: DataSourcesState) => {
  const regex = new RegExp(state.searchQuery, 'i');

  return state.dataSources.filter((dataSource: DataSourceSettings) => {
    return regex.test(dataSource.name) || regex.test(dataSource.database);
  });
}
Example #15
Source File: reducers.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
dataSourcesLoaded = createAction<DataSourceSettings[]>('dataSources/dataSourcesLoaded')
Example #16
Source File: reducers.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
dataSourceLoaded = createAction<DataSourceSettings>('dataSources/dataSourceLoaded')
Example #17
Source File: navModel.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {
  const pluginMeta = plugin.meta;

  const navModel = {
    img: pluginMeta.info.logos.large,
    id: 'datasource-' + dataSource.id,
    subTitle: `Type: ${pluginMeta.name}`,
    url: '',
    text: dataSource.name,
    breadcrumbs: [{ title: 'Data Sources', url: 'datasources' }],
    children: [
      {
        active: false,
        icon: 'fa fa-fw fa-sliders',
        id: `datasource-settings-${dataSource.id}`,
        text: 'Settings',
        url: `datasources/edit/${dataSource.id}/`,
      },
    ],
  };

  if (plugin.configPages) {
    for (const page of plugin.configPages) {
      navModel.children.push({
        active: false,
        text: page.title,
        icon: page.icon,
        url: `datasources/edit/${dataSource.id}/?page=${page.id}`,
        id: `datasource-page-${page.id}`,
      });
    }
  }

  if (pluginMeta.includes && hasDashboards(pluginMeta.includes)) {
    navModel.children.push({
      active: false,
      icon: 'fa fa-fw fa-th-large',
      id: `datasource-dashboards-${dataSource.id}`,
      text: 'Dashboards',
      url: `datasources/edit/${dataSource.id}/dashboards`,
    });
  }

  if (config.licenseInfo.hasLicense) {
    navModel.children.push({
      active: false,
      icon: 'fa fa-fw fa-lock',
      id: `datasource-permissions-${dataSource.id}`,
      text: 'Permissions',
      url: `datasources/edit/${dataSource.id}/permissions`,
    });
  }

  return navModel;
}
Example #18
Source File: actions.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function updateDataSource(dataSource: DataSourceSettings): ThunkResult<void> {
  return async dispatch => {
    await getBackendSrv().put(`/api/datasources/${dataSource.id}`, dataSource);
    await updateFrontendSettings();
    return dispatch(loadDataSource(dataSource.id));
  };
}
Example #19
Source File: PluginSettings.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
onModelChanged = (dataSource: DataSourceSettings) => {
    this.props.onModelChange(dataSource);
  };
Example #20
Source File: PluginSettings.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
scopeProps: {
    ctrl: { datasourceMeta: DataSourcePluginMeta; current: DataSourceSettings };
    onModelChanged: (dataSource: DataSourceSettings) => void;
  };
Example #21
Source File: DataSourceSettingsPage.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
onModelChange = (dataSource: DataSourceSettings) => {
    this.props.dataSourceLoaded(dataSource);
  };
Example #22
Source File: DataSourceSettingsPage.test.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
describe('Render', () => {
  it('should render component', () => {
    const wrapper = setup();

    expect(wrapper).toMatchSnapshot();
  });

  it('should render loader', () => {
    const wrapper = setup({
      dataSource: {} as DataSourceSettings,
      plugin: pluginMock,
    });

    expect(wrapper).toMatchSnapshot();
  });

  it('should render beta info text', () => {
    const wrapper = setup({
      dataSourceMeta: { ...getMockPlugin(), state: 'beta' },
    });

    expect(wrapper).toMatchSnapshot();
  });

  it('should render alpha info text', () => {
    const wrapper = setup({
      dataSourceMeta: { ...getMockPlugin(), state: 'alpha' },
      plugin: pluginMock,
    });

    expect(wrapper).toMatchSnapshot();
  });

  it('should render is ready only message', () => {
    const wrapper = setup({
      dataSource: { ...getMockDataSource(), readOnly: true },
      plugin: pluginMock,
    });

    expect(wrapper).toMatchSnapshot();
  });
});
Example #23
Source File: DataSourceHttpSettings.tsx    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
DataSourceHttpSettings: React.FC<HttpSettingsProps> = props => {
  const { defaultUrl, dataSourceConfig, onChange, showAccessOptions } = props;
  let urlTooltip;
  const [isAccessHelpVisible, setIsAccessHelpVisible] = useState(false);
  const theme = useTheme();

  const onSettingsChange = useCallback(
    (change: Partial<DataSourceSettings<any, any>>) => {
      onChange({
        ...dataSourceConfig,
        ...change,
      });
    },
    [dataSourceConfig]
  );

  switch (dataSourceConfig.access) {
    case 'direct':
      urlTooltip = (
        <>
          Your access method is <em>Browser</em>, this means the URL needs to be accessible from the browser.
        </>
      );
      break;
    case 'proxy':
      urlTooltip = (
        <>
          Your access method is <em>Server</em>, this means the URL needs to be accessible from the grafana
          backend/server.
        </>
      );
      break;
    default:
      urlTooltip = 'Specify a complete HTTP URL (for example http://your_server:8080)';
  }

  const accessSelect = (
    <Select
      width={20}
      options={ACCESS_OPTIONS}
      value={ACCESS_OPTIONS.filter(o => o.value === dataSourceConfig.access)[0] || DEFAULT_ACCESS_OPTION}
      onChange={selectedValue => onSettingsChange({ access: selectedValue.value })}
    />
  );

  const isValidUrl = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/.test(
    dataSourceConfig.url
  );

  const notValidStyle = css`
    box-shadow: inset 0 0px 5px ${theme.colors.red};
  `;

  const inputStyle = cx({ [`width-20`]: true, [notValidStyle]: !isValidUrl });

  const urlInput = (
    <Input
      className={inputStyle}
      placeholder={defaultUrl}
      value={dataSourceConfig.url}
      onChange={event => onSettingsChange({ url: event.currentTarget.value })}
    />
  );

  return (
    <div className="gf-form-group">
      <>
        <h3 className="page-heading">HTTP</h3>
        <div className="gf-form-group">
          <div className="gf-form">
            <FormField label="URL" labelWidth={11} tooltip={urlTooltip} inputEl={urlInput} />
          </div>

          {showAccessOptions && (
            <>
              <div className="gf-form-inline">
                <div className="gf-form">
                  <FormField label="Access" labelWidth={11} inputWidth={20} inputEl={accessSelect} />
                </div>
                <div className="gf-form">
                  <label
                    className="gf-form-label query-keyword pointer"
                    onClick={() => setIsAccessHelpVisible(isVisible => !isVisible)}
                  >
                    Help&nbsp;
                    <i className={`fa fa-caret-${isAccessHelpVisible ? 'down' : 'right'}`} />
                  </label>
                </div>
              </div>
              {isAccessHelpVisible && <HttpAccessHelp />}
            </>
          )}
          {dataSourceConfig.access === 'proxy' && (
            <div className="gf-form">
              <FormLabel
                width={11}
                tooltip="Grafana Proxy deletes forwarded cookies by default. Specify cookies by name that should be forwarded to the data source."
              >
                Whitelisted Cookies
              </FormLabel>
              <TagsInput
                tags={dataSourceConfig.jsonData.keepCookies}
                onChange={cookies =>
                  onSettingsChange({ jsonData: { ...dataSourceConfig.jsonData, keepCookies: cookies } })
                }
                width={20}
              />
            </div>
          )}
        </div>
      </>

      <>
        <h3 className="page-heading">Auth</h3>
        <div className="gf-form-group">
          <div className="gf-form-inline">
            <Switch
              label="Basic auth"
              labelClass="width-13"
              checked={dataSourceConfig.basicAuth}
              onChange={event => {
                onSettingsChange({ basicAuth: event!.currentTarget.checked });
              }}
            />
            <Switch
              label="With Credentials"
              labelClass="width-13"
              checked={dataSourceConfig.withCredentials}
              onChange={event => {
                onSettingsChange({ withCredentials: event!.currentTarget.checked });
              }}
              tooltip="Whether credentials such as cookies or auth headers should be sent with cross-site requests."
            />
          </div>

          {dataSourceConfig.access === 'proxy' && (
            <HttpProxySettings
              dataSourceConfig={dataSourceConfig}
              onChange={jsonData => onSettingsChange({ jsonData })}
            />
          )}
        </div>
        {dataSourceConfig.basicAuth && (
          <>
            <h6>Basic Auth Details</h6>
            <div className="gf-form-group">
              <BasicAuthSettings {...props} />
            </div>
          </>
        )}

        {(dataSourceConfig.jsonData.tlsAuth || dataSourceConfig.jsonData.tlsAuthWithCACert) && (
          <TLSAuthSettings dataSourceConfig={dataSourceConfig} onChange={onChange} />
        )}

        <CustomHeadersSettings dataSourceConfig={dataSourceConfig} onChange={onChange} />
      </>
    </div>
  );
}