useSpanMetrics.tsx 1.9 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 {MutableSearch} from 'sentry/utils/tokenizeSearch';
  5. import {useLocation} from 'sentry/utils/useLocation';
  6. import {
  7. MetricsProperty,
  8. MetricsResponse,
  9. SpanMetricsQueryFilters,
  10. } from 'sentry/views/starfish/types';
  11. import {useSpansQuery} from 'sentry/views/starfish/utils/useSpansQuery';
  12. import {EMPTY_OPTION_VALUE} from 'sentry/views/starfish/views/spans/selectors/emptyOption';
  13. export const useSpanMetrics = <T extends MetricsProperty[]>(
  14. filters: SpanMetricsQueryFilters,
  15. fields: T,
  16. referrer: string = 'span-metrics'
  17. ) => {
  18. const location = useLocation();
  19. const eventView = getEventView(filters, fields, location);
  20. const enabled = Object.values(filters).every(value => Boolean(value));
  21. const result = useSpansQuery({
  22. eventView,
  23. initialData: [],
  24. enabled,
  25. referrer,
  26. });
  27. const data = (result?.data?.[0] ?? {}) as Pick<MetricsResponse, T[number]>;
  28. return {
  29. ...result,
  30. data,
  31. isEnabled: enabled,
  32. };
  33. };
  34. function getEventView(
  35. filters: SpanMetricsQueryFilters,
  36. fields: string[] = [],
  37. location: Location
  38. ) {
  39. const query = new MutableSearch('');
  40. Object.entries(filters).forEach(([key, value]) => {
  41. if (!value) {
  42. return;
  43. }
  44. if (value === EMPTY_OPTION_VALUE) {
  45. query.addFilterValue('!has', key);
  46. }
  47. query.addFilterValue(key, value, !ALLOWED_WILDCARD_FIELDS.includes(key));
  48. });
  49. // TODO: This condition should be enforced everywhere
  50. // query.addFilterValue('has', 'span.description');
  51. return EventView.fromNewQueryWithLocation(
  52. {
  53. name: '',
  54. query: query.formatString(),
  55. fields,
  56. dataset: DiscoverDatasets.SPANS_METRICS,
  57. version: 2,
  58. },
  59. location
  60. );
  61. }
  62. const ALLOWED_WILDCARD_FIELDS = ['span.description'];