hooks.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { useEffect, useState } from 'react';
  2. import { useDeepCompareEffect } from 'react-use';
  3. import { SelectableValue, toOption } from '@grafana/data';
  4. import { CloudWatchDatasource } from './datasource';
  5. import { Dimensions } from './types';
  6. import { appendTemplateVariables } from './utils/utils';
  7. export const useRegions = (datasource: CloudWatchDatasource): [Array<SelectableValue<string>>, boolean] => {
  8. const [regionsIsLoading, setRegionsIsLoading] = useState<boolean>(false);
  9. const [regions, setRegions] = useState<Array<SelectableValue<string>>>([{ label: 'default', value: 'default' }]);
  10. useEffect(() => {
  11. setRegionsIsLoading(true);
  12. const variableOptionGroup = {
  13. label: 'Template Variables',
  14. options: datasource.getVariables().map(toOption),
  15. };
  16. datasource
  17. .getRegions()
  18. .then((regions: Array<SelectableValue<string>>) => setRegions([...regions, variableOptionGroup]))
  19. .finally(() => setRegionsIsLoading(false));
  20. }, [datasource]);
  21. return [regions, regionsIsLoading];
  22. };
  23. export const useNamespaces = (datasource: CloudWatchDatasource) => {
  24. const [namespaces, setNamespaces] = useState<Array<SelectableValue<string>>>([]);
  25. useEffect(() => {
  26. datasource.getNamespaces().then((namespaces) => {
  27. setNamespaces(appendTemplateVariables(datasource, namespaces));
  28. });
  29. }, [datasource]);
  30. return namespaces;
  31. };
  32. export const useMetrics = (datasource: CloudWatchDatasource, region: string, namespace: string | undefined) => {
  33. const [metrics, setMetrics] = useState<Array<SelectableValue<string>>>([]);
  34. useEffect(() => {
  35. datasource.getMetrics(namespace, region).then((result: Array<SelectableValue<string>>) => {
  36. setMetrics(appendTemplateVariables(datasource, result));
  37. });
  38. }, [datasource, region, namespace]);
  39. return metrics;
  40. };
  41. export const useDimensionKeys = (
  42. datasource: CloudWatchDatasource,
  43. region: string,
  44. namespace: string | undefined,
  45. metricName: string | undefined,
  46. dimensionFilter?: Dimensions
  47. ) => {
  48. const [dimensionKeys, setDimensionKeys] = useState<Array<SelectableValue<string>>>([]);
  49. // doing deep comparison to avoid making new api calls to list metrics unless dimension filter object props changes
  50. useDeepCompareEffect(() => {
  51. datasource
  52. .getDimensionKeys(namespace, region, dimensionFilter, metricName)
  53. .then((result: Array<SelectableValue<string>>) => {
  54. setDimensionKeys(appendTemplateVariables(datasource, result));
  55. });
  56. }, [datasource, region, namespace, metricName, dimensionFilter]);
  57. return dimensionKeys;
  58. };