useProjects.tsx 8.1 KB

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