useProjects.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import {useEffect, useRef, useState} from 'react';
  2. import uniqBy from 'lodash/uniqBy';
  3. import {Client} from 'sentry/api';
  4. import OrganizationStore from 'sentry/stores/organizationStore';
  5. import ProjectsStore from 'sentry/stores/projectsStore';
  6. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  7. import {AvatarProject, Project} from 'sentry/types';
  8. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  9. import RequestError from 'sentry/utils/requestError/requestError';
  10. import useApi from 'sentry/utils/useApi';
  11. type ProjectPlaceholder = AvatarProject;
  12. type State = {
  13. /**
  14. * The error that occurred if fetching failed
  15. */
  16. fetchError: null | RequestError;
  17. /**
  18. * This is state for when fetching data from API
  19. */
  20. fetching: boolean;
  21. /**
  22. * Indicates that Project results (from API) are paginated and there are more
  23. * projects that are not in the initial response
  24. */
  25. hasMore: null | boolean;
  26. /**
  27. * Reflects whether or not the initial fetch for the requested projects
  28. * was fulfilled. This accounts for both the store and specifically loaded
  29. * slugs.
  30. */
  31. initiallyLoaded: boolean;
  32. /**
  33. * The last query we searched. Used to validate the cursor
  34. */
  35. lastSearch: null | string;
  36. /**
  37. * Pagination
  38. */
  39. nextCursor?: null | string;
  40. };
  41. type Result = {
  42. /**
  43. * This is an action provided to consumers for them to update the current
  44. * projects result set using a simple search query.
  45. *
  46. * Will always add new options into the store.
  47. */
  48. onSearch: (searchTerm: string) => Promise<void>;
  49. /**
  50. * When loading specific slugs, placeholder objects will be returned
  51. */
  52. placeholders: ProjectPlaceholder[];
  53. /**
  54. * The loaded projects list
  55. */
  56. projects: Project[];
  57. } & Pick<State, 'fetching' | 'hasMore' | 'fetchError' | 'initiallyLoaded'>;
  58. type Options = {
  59. /**
  60. * Number of projects to return when not using `props.slugs`
  61. */
  62. limit?: number;
  63. /**
  64. * Specify an orgId, overriding the organization in the current context
  65. */
  66. orgId?: string;
  67. /**
  68. * List of slugs to look for summaries for, this can be from `props.projects`,
  69. * otherwise fetch from API
  70. */
  71. slugs?: string[];
  72. };
  73. type FetchProjectsOptions = {
  74. cursor?: State['nextCursor'];
  75. lastSearch?: State['lastSearch'];
  76. limit?: Options['limit'];
  77. search?: State['lastSearch'];
  78. slugs?: string[];
  79. };
  80. /**
  81. * Helper function to actually load projects
  82. */
  83. async function fetchProjects(
  84. api: Client,
  85. orgId: string,
  86. {slugs, search, limit, lastSearch, cursor}: FetchProjectsOptions = {}
  87. ) {
  88. const query: {
  89. collapse: string[];
  90. all_projects?: number;
  91. cursor?: typeof cursor;
  92. per_page?: number;
  93. query?: string;
  94. } = {
  95. // Never return latestDeploys project property from api
  96. collapse: ['latestDeploys'],
  97. };
  98. if (slugs !== undefined && slugs.length > 0) {
  99. query.query = slugs.map(slug => `slug:${slug}`).join(' ');
  100. }
  101. if (search) {
  102. query.query = `${query.query ?? ''}${search}`.trim();
  103. }
  104. const prevSearchMatches = (!lastSearch && !search) || lastSearch === search;
  105. if (prevSearchMatches && cursor) {
  106. query.cursor = cursor;
  107. }
  108. if (limit !== undefined) {
  109. query.per_page = limit;
  110. }
  111. let hasMore: null | boolean = false;
  112. let nextCursor: null | string = null;
  113. const [data, , resp] = await api.requestPromise(`/organizations/${orgId}/projects/`, {
  114. includeAllArgs: true,
  115. query,
  116. });
  117. const pageLinks = resp?.getResponseHeader('Link');
  118. if (pageLinks) {
  119. const paginationObject = parseLinkHeader(pageLinks);
  120. hasMore = paginationObject?.next?.results || paginationObject?.previous?.results;
  121. nextCursor = paginationObject?.next?.cursor;
  122. }
  123. return {results: data, hasMore, nextCursor};
  124. }
  125. /**
  126. * Provides projects from the ProjectsStore
  127. *
  128. * This hook also provides a way to select specific project slugs, and search
  129. * (type-ahead) for more projects that may not be in the project store.
  130. *
  131. * NOTE: Currently ALL projects are always loaded, but this hook is designed
  132. * for future-compat in a world where we do _not_ load all projects.
  133. */
  134. function useProjects({limit, slugs, orgId: propOrgId}: Options = {}) {
  135. const api = useApi();
  136. const {organization} = useLegacyStore(OrganizationStore);
  137. const store = useLegacyStore(ProjectsStore);
  138. const orgId = propOrgId ?? organization?.slug;
  139. const storeSlugs = new Set(store.projects.map(t => t.slug));
  140. const slugsToLoad = slugs?.filter(slug => !storeSlugs.has(slug)) ?? [];
  141. const shouldLoadSlugs = slugsToLoad.length > 0;
  142. const [state, setState] = useState<State>({
  143. initiallyLoaded: !store.loading && !shouldLoadSlugs,
  144. fetching: shouldLoadSlugs,
  145. hasMore: null,
  146. lastSearch: null,
  147. nextCursor: null,
  148. fetchError: null,
  149. });
  150. const slugsRef = useRef<Set<string> | null>(null);
  151. // Only initialize slugsRef.current once and modify it when we receive new
  152. // slugs determined through set equality
  153. if (slugs !== undefined) {
  154. if (slugsRef.current === null) {
  155. slugsRef.current = new Set(slugs);
  156. }
  157. if (
  158. slugs.length !== slugsRef.current.size ||
  159. slugs.some(slug => !slugsRef.current?.has(slug))
  160. ) {
  161. slugsRef.current = new Set(slugs);
  162. }
  163. }
  164. async function loadProjectsBySlug() {
  165. if (orgId === undefined) {
  166. // eslint-disable-next-line no-console
  167. console.error('Cannot use useProjects({slugs}) without an organization in context');
  168. return;
  169. }
  170. setState({...state, fetching: true});
  171. try {
  172. const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
  173. slugs: slugsToLoad,
  174. limit,
  175. });
  176. const fetchedProjects = uniqBy([...store.projects, ...results], ({slug}) => slug);
  177. ProjectsStore.loadInitialData(fetchedProjects);
  178. setState({
  179. ...state,
  180. hasMore,
  181. fetching: false,
  182. initiallyLoaded: true,
  183. nextCursor,
  184. });
  185. } catch (err) {
  186. console.error(err); // eslint-disable-line no-console
  187. setState({
  188. ...state,
  189. fetching: false,
  190. initiallyLoaded: !store.loading,
  191. fetchError: err,
  192. });
  193. }
  194. }
  195. async function handleSearch(search: string) {
  196. const {lastSearch} = state;
  197. const cursor = state.nextCursor;
  198. if (search === '') {
  199. return;
  200. }
  201. if (orgId === undefined) {
  202. // eslint-disable-next-line no-console
  203. console.error('Cannot use useProjects.onSearch without an organization in context');
  204. return;
  205. }
  206. setState({...state, fetching: true});
  207. try {
  208. api.clear();
  209. const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
  210. search,
  211. limit,
  212. lastSearch,
  213. cursor,
  214. });
  215. const fetchedProjects = uniqBy([...store.projects, ...results], ({slug}) => slug);
  216. // Only update the store if we have more items
  217. if (fetchedProjects.length > store.projects.length) {
  218. ProjectsStore.loadInitialData(fetchedProjects);
  219. }
  220. setState({
  221. ...state,
  222. hasMore,
  223. fetching: false,
  224. lastSearch: search,
  225. nextCursor,
  226. });
  227. } catch (err) {
  228. console.error(err); // eslint-disable-line no-console
  229. setState({...state, fetching: false, fetchError: err});
  230. }
  231. }
  232. useEffect(() => {
  233. // Load specified team slugs
  234. if (shouldLoadSlugs) {
  235. loadProjectsBySlug();
  236. return;
  237. }
  238. }, [slugsRef.current]);
  239. // Update initiallyLoaded when we finish loading within the projectStore
  240. useEffect(() => {
  241. const storeLoaded = !store.loading;
  242. if (state.initiallyLoaded === storeLoaded) {
  243. return;
  244. }
  245. if (shouldLoadSlugs) {
  246. return;
  247. }
  248. setState({...state, initiallyLoaded: storeLoaded});
  249. }, [store.loading]);
  250. const {initiallyLoaded, fetching, fetchError, hasMore} = state;
  251. const filteredProjects = slugs
  252. ? store.projects.filter(t => slugs.includes(t.slug))
  253. : store.projects;
  254. const placeholders = slugsToLoad.map(slug => ({slug}));
  255. const result: Result = {
  256. projects: filteredProjects,
  257. placeholders,
  258. fetching: fetching || store.loading,
  259. initiallyLoaded,
  260. fetchError,
  261. hasMore,
  262. onSearch: handleSearch,
  263. };
  264. return result;
  265. }
  266. export default useProjects;