useSpanMetrics.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import type {PageFilters} from 'sentry/types';
  2. import EventView from 'sentry/utils/discover/eventView';
  3. import type {Sort} from 'sentry/utils/discover/fields';
  4. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  5. import type {MutableSearch} from 'sentry/utils/tokenizeSearch';
  6. import usePageFilters from 'sentry/utils/usePageFilters';
  7. import type {MetricsProperty, MetricsResponse} from 'sentry/views/starfish/types';
  8. import {useWrappedDiscoverQuery} from 'sentry/views/starfish/utils/useSpansQuery';
  9. interface UseSpanMetricsOptions<Fields> {
  10. cursor?: string;
  11. enabled?: boolean;
  12. fields?: Fields;
  13. limit?: number;
  14. referrer?: string;
  15. search?: MutableSearch;
  16. sorts?: Sort[];
  17. }
  18. export const useSpanMetrics = <Fields extends MetricsProperty[]>(
  19. options: UseSpanMetricsOptions<Fields> = {}
  20. ) => {
  21. const {fields = [], search = undefined, sorts = [], limit, cursor, referrer} = options;
  22. const pageFilters = usePageFilters();
  23. const eventView = getEventView(search, fields, sorts, pageFilters.selection);
  24. const result = useWrappedDiscoverQuery({
  25. eventView,
  26. initialData: [],
  27. limit,
  28. enabled: options.enabled,
  29. referrer,
  30. cursor,
  31. });
  32. // This type is a little awkward but it explicitly states that the response could be empty. This doesn't enable unchecked access errors, but it at least indicates that it's possible that there's no data
  33. // eslint-disable-next-line @typescript-eslint/ban-types
  34. const data = (result?.data ?? []) as Pick<MetricsResponse, Fields[number]>[] | [];
  35. return {
  36. ...result,
  37. data,
  38. isEnabled: options.enabled,
  39. };
  40. };
  41. function getEventView(
  42. search: MutableSearch | undefined,
  43. fields: string[] = [],
  44. sorts: Sort[] = [],
  45. pageFilters: PageFilters
  46. ) {
  47. const eventView = EventView.fromNewQueryWithPageFilters(
  48. {
  49. name: '',
  50. query: search?.formatString() ?? '',
  51. fields,
  52. dataset: DiscoverDatasets.SPANS_METRICS,
  53. version: 2,
  54. },
  55. pageFilters
  56. );
  57. if (sorts.length > 0) {
  58. eventView.sorts = sorts;
  59. }
  60. return eventView;
  61. }