useSpanMetrics.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import {PageFilters} from 'sentry/types';
  2. import EventView from 'sentry/utils/discover/eventView';
  3. import {Sort} from 'sentry/utils/discover/fields';
  4. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  5. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  6. import usePageFilters from 'sentry/utils/usePageFilters';
  7. import {
  8. MetricsProperty,
  9. MetricsResponse,
  10. SpanMetricsQueryFilters,
  11. } from 'sentry/views/starfish/types';
  12. import {useWrappedDiscoverQuery} from 'sentry/views/starfish/utils/useSpansQuery';
  13. interface UseSpanMetricsOptions<Fields> {
  14. cursor?: string;
  15. fields?: Fields;
  16. filters?: SpanMetricsQueryFilters;
  17. limit?: number;
  18. referrer?: string;
  19. sorts?: Sort[];
  20. }
  21. export const useSpanMetrics = <Fields extends MetricsProperty[]>(
  22. options: UseSpanMetricsOptions<Fields> = {}
  23. ) => {
  24. const {fields = [], filters = {}, sorts = [], limit, cursor, referrer} = options;
  25. const pageFilters = usePageFilters();
  26. const eventView = getEventView(filters, fields, sorts, pageFilters.selection);
  27. const enabled = Object.values(filters).every(value => Boolean(value));
  28. const result = useWrappedDiscoverQuery({
  29. eventView,
  30. initialData: [],
  31. limit,
  32. enabled,
  33. referrer,
  34. cursor,
  35. });
  36. // 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
  37. // eslint-disable-next-line @typescript-eslint/ban-types
  38. const data = (result?.data ?? []) as Pick<MetricsResponse, Fields[number]>[] | [];
  39. return {
  40. ...result,
  41. data,
  42. isEnabled: enabled,
  43. };
  44. };
  45. function getEventView(
  46. filters: SpanMetricsQueryFilters = {},
  47. fields: string[] = [],
  48. sorts: Sort[] = [],
  49. pageFilters: PageFilters
  50. ) {
  51. const query = MutableSearch.fromQueryObject(filters);
  52. const eventView = EventView.fromNewQueryWithPageFilters(
  53. {
  54. name: '',
  55. query: query.formatString(),
  56. fields,
  57. dataset: DiscoverDatasets.SPANS_METRICS,
  58. version: 2,
  59. },
  60. pageFilters
  61. );
  62. if (sorts.length > 0) {
  63. eventView.sorts = sorts;
  64. }
  65. return eventView;
  66. }