useSpanMetrics.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import {Location} from 'history';
  2. import EventView from 'sentry/utils/discover/eventView';
  3. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import {
  6. MetricsProperty,
  7. MetricsResponse,
  8. SpanMetricsField,
  9. } from 'sentry/views/starfish/types';
  10. import {useSpansQuery} from 'sentry/views/starfish/utils/useSpansQuery';
  11. const {SPAN_GROUP} = SpanMetricsField;
  12. export type SpanSummaryQueryFilters = {
  13. 'transaction.method'?: string;
  14. transactionName?: string;
  15. };
  16. export const useSpanMetrics = <T extends MetricsProperty[]>(
  17. group: string,
  18. queryFilters: SpanSummaryQueryFilters,
  19. fields: T,
  20. referrer: string = 'span-metrics'
  21. ) => {
  22. const location = useLocation();
  23. const eventView = group
  24. ? getEventView(group, location, queryFilters, fields)
  25. : undefined;
  26. const enabled =
  27. Boolean(group) && Object.values(queryFilters).every(value => Boolean(value));
  28. // TODO: Add referrer
  29. const result = useSpansQuery({
  30. eventView,
  31. initialData: [],
  32. enabled,
  33. referrer,
  34. });
  35. const data = (result?.data?.[0] ?? {}) as Pick<MetricsResponse, T[number]>;
  36. return {
  37. ...result,
  38. data,
  39. isEnabled: enabled,
  40. };
  41. };
  42. function getEventView(
  43. group: string,
  44. location: Location,
  45. queryFilters?: SpanSummaryQueryFilters,
  46. fields: string[] = []
  47. ) {
  48. return EventView.fromNewQueryWithLocation(
  49. {
  50. name: '',
  51. query: `${SPAN_GROUP}:${group}${
  52. queryFilters?.transactionName
  53. ? ` transaction:"${queryFilters?.transactionName}"`
  54. : ''
  55. }${
  56. queryFilters?.['transaction.method']
  57. ? ` transaction.method:${queryFilters?.['transaction.method']}`
  58. : ''
  59. }`,
  60. fields,
  61. dataset: DiscoverDatasets.SPANS_METRICS,
  62. version: 2,
  63. },
  64. location
  65. );
  66. }