useProfileTransactions.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import {useEffect, useState} from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import {Client} from 'sentry/api';
  4. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  5. import {t} from 'sentry/locale';
  6. import {Organization, PageFilters, RequestState} from 'sentry/types';
  7. import {ProfileTransaction} from 'sentry/types/profiling/core';
  8. import {defined} from 'sentry/utils';
  9. import useApi from 'sentry/utils/useApi';
  10. import useOrganization from 'sentry/utils/useOrganization';
  11. type ProfileTransactionsResult = {
  12. pageLinks: string | null;
  13. transactions: ProfileTransaction[];
  14. };
  15. interface UseProfileTransactionsOptions {
  16. query: string;
  17. cursor?: string;
  18. limit?: number;
  19. selection?: PageFilters;
  20. }
  21. function useProfileTransactions({
  22. cursor,
  23. limit,
  24. query,
  25. selection,
  26. }: UseProfileTransactionsOptions): RequestState<ProfileTransactionsResult> {
  27. const api = useApi();
  28. const organization = useOrganization();
  29. const [requestState, setRequestState] = useState<
  30. RequestState<ProfileTransactionsResult>
  31. >({
  32. type: 'initial',
  33. });
  34. useEffect(() => {
  35. if (!defined(selection)) {
  36. return undefined;
  37. }
  38. setRequestState({type: 'loading'});
  39. fetchTransactions(api, organization, {cursor, limit, query, selection})
  40. .then(([transactions, , response]) => {
  41. setRequestState({
  42. type: 'resolved',
  43. data: {
  44. transactions,
  45. pageLinks: response?.getResponseHeader('Link') ?? null,
  46. },
  47. });
  48. })
  49. .catch(err => {
  50. setRequestState({
  51. type: 'errored',
  52. error: t('Error: Unable to load transactions'),
  53. });
  54. Sentry.captureException(err);
  55. });
  56. return () => api.clear();
  57. }, [api, organization, cursor, limit, query, selection]);
  58. return requestState;
  59. }
  60. function fetchTransactions(
  61. api: Client,
  62. organization: Organization,
  63. {
  64. cursor,
  65. limit,
  66. query,
  67. selection,
  68. }: {
  69. cursor: string | undefined;
  70. limit: number | undefined;
  71. query: string;
  72. selection: PageFilters;
  73. }
  74. ) {
  75. return api.requestPromise(
  76. `/organizations/${organization.slug}/profiling/transactions/`,
  77. {
  78. method: 'GET',
  79. includeAllArgs: true,
  80. query: {
  81. cursor,
  82. query,
  83. per_page: limit,
  84. project: selection.projects,
  85. environment: selection.environments,
  86. ...normalizeDateTimeParams(selection.datetime),
  87. },
  88. }
  89. );
  90. }
  91. export {useProfileTransactions};