useFetchThresholdsListData.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import {useMemo} from 'react';
  2. import type {Environment} from 'sentry/types';
  3. import {MonitorType} from 'sentry/types/alerts';
  4. import {type ApiQueryKey, useApiQuery} from 'sentry/utils/queryClient';
  5. import useOrganization from 'sentry/utils/useOrganization';
  6. import type {MetricRule} from 'sentry/views/alerts/rules/metric/types';
  7. import {TOTAL_ERROR_COUNT_STR} from 'sentry/views/releases/utils/constants';
  8. import type {Threshold, ThresholdQuery} from './types';
  9. export type HookProps = {
  10. selectedEnvs?: string[];
  11. selectedProjectIds?: number[];
  12. };
  13. export default function useFetchThresholdsListData({
  14. selectedEnvs = [],
  15. selectedProjectIds = [],
  16. }: HookProps = {}) {
  17. const organization = useOrganization();
  18. const query: ThresholdQuery = {};
  19. const isActivatedAlert = organization.features?.includes('activated-alert-rules');
  20. if (selectedEnvs.length) query.environment = selectedEnvs;
  21. if (selectedProjectIds.length) {
  22. query.project = selectedProjectIds;
  23. } else {
  24. query.project = [-1];
  25. }
  26. let queryKey: ApiQueryKey = [
  27. `/organizations/${organization.slug}/release-thresholds/`,
  28. {
  29. query,
  30. },
  31. ];
  32. if (isActivatedAlert) {
  33. query.monitor_type = MonitorType.ACTIVATED;
  34. queryKey = [
  35. `/organizations/${organization.slug}/alert-rules/`,
  36. {
  37. query,
  38. },
  39. ];
  40. }
  41. const hasReleaseV2Feature =
  42. organization.features?.includes('releases-v2-internal') ||
  43. organization.features?.includes('releases-v2') ||
  44. organization.features?.includes('releases-v2-st');
  45. const {data, ...remainigProps} = useApiQuery<Threshold[] | MetricRule[]>(queryKey, {
  46. staleTime: 0,
  47. enabled: hasReleaseV2Feature || isActivatedAlert,
  48. });
  49. const thresholds: Threshold[] = useMemo(() => {
  50. if (!isActivatedAlert) return data as Threshold[];
  51. if (!data) return [];
  52. return data.map((thresholdOrRule: Threshold | MetricRule) => {
  53. const rule = thresholdOrRule as MetricRule;
  54. return {
  55. date_added: rule.dateCreated,
  56. environment: {
  57. name: rule.environment,
  58. displayName: rule.environment,
  59. } as Environment,
  60. id: rule.id,
  61. project: {id: rule.projects[0], slug: rule.projects[0]},
  62. threshold_type: TOTAL_ERROR_COUNT_STR,
  63. trigger_type: 'over',
  64. value: rule.triggers[0]?.alertThreshold,
  65. window_in_seconds: rule.timeWindow,
  66. } as Threshold;
  67. });
  68. }, [isActivatedAlert, data]);
  69. return {
  70. data: thresholds,
  71. ...remainigProps,
  72. };
  73. }