genericDiscoverQuery.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import {Component, useContext} from 'react';
  2. import {useQuery} from '@tanstack/react-query';
  3. import {Location} from 'history';
  4. import {EventQuery} from 'sentry/actionCreators/events';
  5. import {Client, ResponseMeta} from 'sentry/api';
  6. import {t} from 'sentry/locale';
  7. import EventView, {
  8. ImmutableEventView,
  9. isAPIPayloadSimilar,
  10. LocationQuery,
  11. } from 'sentry/utils/discover/eventView';
  12. import {QueryBatching} from 'sentry/utils/performance/contexts/genericQueryBatcher';
  13. import {PerformanceEventViewContext} from 'sentry/utils/performance/contexts/performanceEventViewContext';
  14. import {OrganizationContext} from 'sentry/views/organizationContext';
  15. import useApi from '../useApi';
  16. export class QueryError {
  17. message: string;
  18. private originalError: any; // For debugging in case parseError picks a value that doesn't make sense.
  19. constructor(errorMessage: string, originalError?: any) {
  20. this.message = errorMessage;
  21. this.originalError = originalError;
  22. }
  23. getOriginalError() {
  24. return this.originalError;
  25. }
  26. }
  27. export type GenericChildrenProps<T> = {
  28. /**
  29. * Error, if not null.
  30. */
  31. error: null | QueryError;
  32. /**
  33. * Loading state of this query.
  34. */
  35. isLoading: boolean;
  36. /**
  37. * Pagelinks, if applicable. Can be provided to the Pagination component.
  38. */
  39. pageLinks: null | string;
  40. /**
  41. * Data / result.
  42. */
  43. tableData: T | null;
  44. };
  45. type OptionalContextProps = {
  46. eventView?: EventView | ImmutableEventView;
  47. orgSlug?: string;
  48. };
  49. type BaseDiscoverQueryProps = {
  50. /**
  51. * Used as the default source for cursor values.
  52. */
  53. location: Location;
  54. /**
  55. * Explicit cursor value if you aren't using `location.query.cursor` because there are
  56. * multiple paginated results on the page.
  57. */
  58. cursor?: string;
  59. /**
  60. * Appends a raw string to query to be able to sidestep the tokenizer.
  61. * @deprecated
  62. */
  63. forceAppendRawQueryString?: string;
  64. /**
  65. * Record limit to get.
  66. */
  67. limit?: number;
  68. /**
  69. * Include this whenever pagination won't be used. Limit can still be used when this is
  70. * passed, but cursor will be ignored.
  71. */
  72. noPagination?: boolean;
  73. /**
  74. * A container for query batching data and functions.
  75. */
  76. queryBatching?: QueryBatching;
  77. /**
  78. * Extra query parameters to be added.
  79. */
  80. queryExtras?: Record<string, string>;
  81. /**
  82. * Sets referrer parameter in the API Payload. Set of allowed referrers are defined
  83. * on the OrganizationEventsV2Endpoint view.
  84. */
  85. referrer?: string;
  86. /**
  87. * A callback to set an error so that the error can be rendered in parent components
  88. */
  89. setError?: (errObject: QueryError | undefined) => void;
  90. };
  91. export type DiscoverQueryPropsWithContext = BaseDiscoverQueryProps & OptionalContextProps;
  92. export type DiscoverQueryProps = BaseDiscoverQueryProps & {
  93. eventView: EventView | ImmutableEventView;
  94. orgSlug: string;
  95. };
  96. type InnerRequestProps<P> = DiscoverQueryProps & P;
  97. type OuterRequestProps<P> = DiscoverQueryPropsWithContext & P;
  98. export type ReactProps<T> = {
  99. children?: (props: GenericChildrenProps<T>) => React.ReactNode;
  100. };
  101. type ComponentProps<T, P> = {
  102. /**
  103. * Route to the endpoint
  104. */
  105. route: string;
  106. /**
  107. * A hook to modify data into the correct output after data has been received
  108. */
  109. afterFetch?: (data: any, props?: Props<T, P>) => T;
  110. /**
  111. * A hook before fetch that can be used to do things like clearing the api
  112. */
  113. beforeFetch?: (api: Client) => void;
  114. /**
  115. * A hook for parent orchestrators to pass down data based on query results, unlike afterFetch it is not meant for specializations as it will not modify data.
  116. */
  117. didFetch?: (data: T) => void;
  118. /**
  119. * Allows components to modify the payload before it is set.
  120. */
  121. getRequestPayload?: (props: Props<T, P>) => any;
  122. /**
  123. * An external hook to parse errors in case there are differences for a specific api.
  124. */
  125. parseError?: (error: any) => QueryError | null;
  126. /**
  127. * An external hook in addition to the event view check to check if data should be refetched
  128. */
  129. shouldRefetchData?: (prevProps: Props<T, P>, props: Props<T, P>) => boolean;
  130. };
  131. type Props<T, P> = InnerRequestProps<P> & ReactProps<T> & ComponentProps<T, P>;
  132. type OuterProps<T, P> = OuterRequestProps<P> & ReactProps<T> & ComponentProps<T, P>;
  133. type State<T> = {
  134. api: Client;
  135. tableFetchID: symbol | undefined;
  136. } & GenericChildrenProps<T>;
  137. /**
  138. * Generic component for discover queries
  139. */
  140. class _GenericDiscoverQuery<T, P> extends Component<Props<T, P>, State<T>> {
  141. state: State<T> = {
  142. isLoading: true,
  143. tableFetchID: undefined,
  144. error: null,
  145. tableData: null,
  146. pageLinks: null,
  147. api: new Client(),
  148. };
  149. componentDidMount() {
  150. this.fetchData();
  151. }
  152. componentDidUpdate(prevProps: Props<T, P>) {
  153. // Reload data if the payload changes
  154. const refetchCondition = this._shouldRefetchData(prevProps);
  155. // or if we've moved from an invalid view state to a valid one,
  156. const eventViewValidation =
  157. prevProps.eventView.isValid() === false && this.props.eventView.isValid();
  158. const shouldRefetchExternal = this.props.shouldRefetchData
  159. ? this.props.shouldRefetchData(prevProps, this.props)
  160. : false;
  161. if (refetchCondition || eventViewValidation || shouldRefetchExternal) {
  162. this.fetchData();
  163. }
  164. }
  165. _shouldRefetchData = (prevProps: Props<T, P>): boolean => {
  166. const thisAPIPayload = getPayload(this.props);
  167. const otherAPIPayload = getPayload(prevProps);
  168. return (
  169. !isAPIPayloadSimilar(thisAPIPayload, otherAPIPayload) ||
  170. prevProps.limit !== this.props.limit ||
  171. prevProps.route !== this.props.route ||
  172. prevProps.cursor !== this.props.cursor
  173. );
  174. };
  175. /**
  176. * The error type isn't consistent across APIs. We see detail as just string some times, other times as an object.
  177. */
  178. _parseError = (error: any): QueryError | null => {
  179. if (this.props.parseError) {
  180. return this.props.parseError(error);
  181. }
  182. if (!error) {
  183. return null;
  184. }
  185. const detail = error.responseJSON?.detail;
  186. if (typeof detail === 'string') {
  187. return new QueryError(detail, error);
  188. }
  189. const message = detail?.message;
  190. if (typeof message === 'string') {
  191. return new QueryError(message, error);
  192. }
  193. const unknownError = new QueryError(t('An unknown error occurred.'), error);
  194. return unknownError;
  195. };
  196. fetchData = async () => {
  197. const {
  198. queryBatching,
  199. beforeFetch,
  200. afterFetch,
  201. didFetch,
  202. eventView,
  203. orgSlug,
  204. route,
  205. setError,
  206. } = this.props;
  207. const {api} = this.state;
  208. if (!eventView.isValid()) {
  209. return;
  210. }
  211. const url = `/organizations/${orgSlug}/${route}/`;
  212. const tableFetchID = Symbol(`tableFetchID`);
  213. const apiPayload: Partial<EventQuery & LocationQuery> = getPayload(this.props);
  214. this.setState({isLoading: true, tableFetchID});
  215. setError?.(undefined);
  216. beforeFetch?.(api);
  217. // clear any inflight requests since they are now stale
  218. api.clear();
  219. try {
  220. const [data, , resp] = await doDiscoverQuery<T>(
  221. api,
  222. url,
  223. apiPayload,
  224. queryBatching
  225. );
  226. if (this.state.tableFetchID !== tableFetchID) {
  227. // invariant: a different request was initiated after this request
  228. return;
  229. }
  230. const tableData = afterFetch ? afterFetch(data, this.props) : data;
  231. didFetch?.(tableData);
  232. this.setState(prevState => ({
  233. isLoading: false,
  234. tableFetchID: undefined,
  235. error: null,
  236. pageLinks: resp?.getResponseHeader('Link') ?? prevState.pageLinks,
  237. tableData,
  238. }));
  239. } catch (err) {
  240. const error = this._parseError(err);
  241. this.setState({
  242. isLoading: false,
  243. tableFetchID: undefined,
  244. error,
  245. tableData: null,
  246. });
  247. if (setError) {
  248. setError(error ?? undefined);
  249. }
  250. }
  251. };
  252. render() {
  253. const {isLoading, error, tableData, pageLinks} = this.state;
  254. const childrenProps: GenericChildrenProps<T> = {
  255. isLoading,
  256. error,
  257. tableData,
  258. pageLinks,
  259. };
  260. const children: ReactProps<T>['children'] = this.props.children; // Explicitly setting type due to issues with generics and React's children
  261. return children?.(childrenProps);
  262. }
  263. }
  264. // Shim to allow us to use generic discover query or any specialization with or without passing org slug or eventview, which are now contexts.
  265. // This will help keep tests working and we can remove extra uses of context-provided props and update tests as we go.
  266. export function GenericDiscoverQuery<T, P>(props: OuterProps<T, P>) {
  267. const organizationSlug = useContext(OrganizationContext)?.slug;
  268. const performanceEventView = useContext(PerformanceEventViewContext)?.eventView;
  269. const orgSlug = props.orgSlug ?? organizationSlug;
  270. const eventView = props.eventView ?? performanceEventView;
  271. if (orgSlug === undefined || eventView === undefined) {
  272. throw new Error('GenericDiscoverQuery requires both an orgSlug and eventView');
  273. }
  274. const _props: Props<T, P> = {
  275. ...props,
  276. orgSlug,
  277. eventView,
  278. };
  279. return <_GenericDiscoverQuery<T, P> {..._props} />;
  280. }
  281. export type DiscoverQueryRequestParams = Partial<EventQuery & LocationQuery>;
  282. export function doDiscoverQuery<T>(
  283. api: Client,
  284. url: string,
  285. params: DiscoverQueryRequestParams,
  286. queryBatching?: QueryBatching
  287. ): Promise<[T, string | undefined, ResponseMeta<T> | undefined]> {
  288. if (queryBatching?.batchRequest) {
  289. return queryBatching.batchRequest(api, url, {
  290. query: params,
  291. includeAllArgs: true,
  292. });
  293. }
  294. return api.requestPromise(url, {
  295. method: 'GET',
  296. includeAllArgs: true,
  297. query: {
  298. // marking params as any so as to not cause typescript errors
  299. ...(params as any),
  300. },
  301. });
  302. }
  303. function getPayload<T, P>(props: Props<T, P>) {
  304. const {
  305. cursor,
  306. limit,
  307. noPagination,
  308. referrer,
  309. getRequestPayload,
  310. eventView,
  311. location,
  312. forceAppendRawQueryString,
  313. } = props;
  314. const payload = getRequestPayload
  315. ? getRequestPayload(props)
  316. : eventView.getEventsAPIPayload(location, forceAppendRawQueryString);
  317. if (cursor) {
  318. payload.cursor = cursor;
  319. }
  320. if (limit) {
  321. payload.per_page = limit;
  322. }
  323. if (noPagination) {
  324. payload.noPagination = noPagination;
  325. }
  326. if (referrer) {
  327. payload.referrer = referrer;
  328. }
  329. Object.assign(payload, props.queryExtras ?? {});
  330. return payload;
  331. }
  332. export function useGenericDiscoverQuery<T, P>(props: Props<T, P>) {
  333. const api = useApi();
  334. const {orgSlug, route} = props;
  335. const url = `/organizations/${orgSlug}/${route}/`;
  336. const apiPayload = getPayload<T, P>(props);
  337. return useQuery<T, QueryError>([route, apiPayload], async () => {
  338. const [resp] = await doDiscoverQuery<T>(api, url, apiPayload, props.queryBatching);
  339. return resp;
  340. });
  341. }
  342. export default GenericDiscoverQuery;