useTeams.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import {useEffect, useMemo, useRef, useState} from 'react';
  2. import uniqBy from 'lodash/uniqBy';
  3. import {fetchUserTeams} from 'sentry/actionCreators/teams';
  4. import TeamActions from 'sentry/actions/teamActions';
  5. import {Client} from 'sentry/api';
  6. import OrganizationStore from 'sentry/stores/organizationStore';
  7. import TeamStore from 'sentry/stores/teamStore';
  8. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  9. import {Team} from 'sentry/types';
  10. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  11. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  12. import RequestError from 'sentry/utils/requestError/requestError';
  13. import useApi from 'sentry/utils/useApi';
  14. type State = {
  15. /**
  16. * The error that occurred if fetching failed
  17. */
  18. fetchError: null | RequestError;
  19. /**
  20. * This is state for when fetching data from API
  21. */
  22. fetching: boolean;
  23. /**
  24. * Indicates that Team results (from API) are paginated and there are more
  25. * Teams that are not in the initial response.
  26. */
  27. hasMore: null | boolean;
  28. /**
  29. * Reflects whether or not the initial fetch for the requested teams was
  30. * fulfilled
  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 request more teams
  45. * to be loaded. Additional teams will be fetched and loaded into the store.
  46. */
  47. loadMore: (searchTerm?: string) => Promise<void>;
  48. /**
  49. * This is an action provided to consumers for them to update the current
  50. * teams result set using a simple search query.
  51. *
  52. * Will always add new options into the store.
  53. */
  54. onSearch: (searchTerm: string) => Promise<void>;
  55. /**
  56. * The loaded teams list
  57. */
  58. teams: Team[];
  59. } & Pick<State, 'fetching' | 'hasMore' | 'fetchError' | 'initiallyLoaded'>;
  60. type Options = {
  61. /**
  62. * When provided, fetches specified teams by id if necessary and only provides those teams.
  63. */
  64. ids?: string[];
  65. /**
  66. * Number of teams to return when not using `props.slugs`
  67. */
  68. limit?: number;
  69. /**
  70. * When true, fetches user's teams if necessary and only provides user's
  71. * teams (isMember = true).
  72. */
  73. provideUserTeams?: boolean;
  74. /**
  75. * When provided, fetches specified teams by slug if necessary and only provides those teams.
  76. */
  77. slugs?: string[];
  78. };
  79. type FetchTeamOptions = {
  80. cursor?: State['nextCursor'];
  81. ids?: string[];
  82. lastSearch?: State['lastSearch'];
  83. limit?: Options['limit'];
  84. search?: State['lastSearch'];
  85. slugs?: string[];
  86. };
  87. /**
  88. * Helper function to actually load teams
  89. */
  90. async function fetchTeams(
  91. api: Client,
  92. orgId: string,
  93. {slugs, ids, search, limit, lastSearch, cursor}: FetchTeamOptions = {}
  94. ) {
  95. const query: {
  96. cursor?: typeof cursor;
  97. per_page?: number;
  98. query?: string;
  99. } = {};
  100. if (slugs !== undefined && slugs.length > 0) {
  101. query.query = slugs.map(slug => `slug:${slug}`).join(' ');
  102. }
  103. if (ids !== undefined && ids.length > 0) {
  104. query.query = ids.map(id => `id:${id}`).join(' ');
  105. }
  106. if (search) {
  107. query.query = `${query.query ?? ''} ${search}`.trim();
  108. }
  109. const isSameSearch = lastSearch === search || (!lastSearch && !search);
  110. if (isSameSearch && cursor) {
  111. query.cursor = cursor;
  112. }
  113. if (limit !== undefined) {
  114. query.per_page = limit;
  115. }
  116. let hasMore: null | boolean = false;
  117. let nextCursor: null | string = null;
  118. const [data, , resp] = await api.requestPromise(`/organizations/${orgId}/teams/`, {
  119. includeAllArgs: true,
  120. query,
  121. });
  122. const pageLinks = resp?.getResponseHeader('Link');
  123. if (pageLinks) {
  124. const paginationObject = parseLinkHeader(pageLinks);
  125. hasMore = paginationObject?.next?.results;
  126. nextCursor = paginationObject?.next?.cursor;
  127. }
  128. return {results: data, hasMore, nextCursor};
  129. }
  130. // TODO: Paging for items which have already exist in the store is not
  131. // correctly implemented.
  132. /**
  133. * Provides teams from the TeamStore
  134. *
  135. * This hook also provides a way to select specific slugs to ensure they are
  136. * loaded, as well as search (type-ahead) for more slugs that may not be in the
  137. * TeamsStore.
  138. *
  139. * NOTE: It is NOT guaranteed that all teams for an organization will be
  140. * loaded, so you should use this hook with the intention of providing specific
  141. * slugs, or loading more through search.
  142. *
  143. */
  144. function useTeams({limit, slugs, ids, provideUserTeams}: Options = {}) {
  145. const api = useApi();
  146. const {organization} = useLegacyStore(OrganizationStore);
  147. const store = useLegacyStore(TeamStore);
  148. const orgId = organization?.slug;
  149. const storeSlugs = new Set(store.teams.map(t => t.slug));
  150. const slugsToLoad = slugs?.filter(slug => !storeSlugs.has(slug)) ?? [];
  151. const storeIds = new Set(store.teams.map(t => t.id));
  152. const idsToLoad = ids?.filter(id => !storeIds.has(id)) ?? [];
  153. const shouldLoadSlugs = slugsToLoad.length > 0;
  154. const shouldLoadIds = idsToLoad.length > 0;
  155. const shouldLoadTeams = provideUserTeams && !store.loadedUserTeams;
  156. // If we don't need to make a request either for slugs or user teams, set
  157. // initiallyLoaded to true
  158. const initiallyLoaded = !shouldLoadSlugs && !shouldLoadTeams && !shouldLoadIds;
  159. const [state, setState] = useState<State>({
  160. initiallyLoaded,
  161. fetching: false,
  162. hasMore: store.hasMore,
  163. lastSearch: null,
  164. nextCursor: store.cursor,
  165. fetchError: null,
  166. });
  167. const slugOrIdRef = useRef<Set<string> | null>(null);
  168. // Only initialize slugOrIdRef.current once and modify it when we receive new
  169. // slugs or ids determined through set equality
  170. if (slugs !== undefined || ids !== undefined) {
  171. const slugsOrIds = (slugs || ids) ?? [];
  172. if (slugOrIdRef.current === null) {
  173. slugOrIdRef.current = new Set(slugsOrIds);
  174. }
  175. if (
  176. slugsOrIds.length !== slugOrIdRef.current.size ||
  177. slugsOrIds.some(slugOrId => !slugOrIdRef.current?.has(slugOrId))
  178. ) {
  179. slugOrIdRef.current = new Set(slugsOrIds);
  180. }
  181. }
  182. async function loadUserTeams() {
  183. if (orgId === undefined) {
  184. return;
  185. }
  186. setState({...state, fetching: true});
  187. try {
  188. await fetchUserTeams(api, {orgId});
  189. setState({...state, fetching: false, initiallyLoaded: true});
  190. } catch (err) {
  191. console.error(err); // eslint-disable-line no-console
  192. setState({...state, fetching: false, initiallyLoaded: true, fetchError: err});
  193. }
  194. }
  195. async function loadTeamsBySlugOrId() {
  196. if (orgId === undefined) {
  197. return;
  198. }
  199. setState({...state, fetching: true});
  200. try {
  201. const {results, hasMore, nextCursor} = await fetchTeams(api, orgId, {
  202. slugs: slugsToLoad,
  203. ids: idsToLoad,
  204. limit,
  205. });
  206. // Unique by `id` to avoid duplicates due to renames and state store data
  207. const fetchedTeams = uniqBy([...results, ...store.teams], ({id}) => id);
  208. TeamActions.loadTeams(fetchedTeams);
  209. setState({
  210. ...state,
  211. hasMore,
  212. fetching: false,
  213. initiallyLoaded: true,
  214. nextCursor,
  215. });
  216. } catch (err) {
  217. console.error(err); // eslint-disable-line no-console
  218. setState({...state, fetching: false, initiallyLoaded: true, fetchError: err});
  219. }
  220. }
  221. function handleSearch(search: string) {
  222. if (search !== '') {
  223. return handleFetchAdditionalTeams(search);
  224. }
  225. // Reset pagination state to match store if doing an empty search
  226. if (state.hasMore !== store.hasMore || state.nextCursor !== store.cursor) {
  227. setState({
  228. ...state,
  229. lastSearch: search,
  230. hasMore: store.hasMore,
  231. nextCursor: store.cursor,
  232. });
  233. }
  234. return Promise.resolve();
  235. }
  236. async function handleFetchAdditionalTeams(search?: string) {
  237. const {lastSearch} = state;
  238. // Use the store cursor if there is no search keyword provided
  239. const cursor = search ? state.nextCursor : store.cursor;
  240. if (orgId === undefined) {
  241. // eslint-disable-next-line no-console
  242. console.error('Cannot fetch teams without an organization in context');
  243. return;
  244. }
  245. setState({...state, fetching: true});
  246. try {
  247. api.clear();
  248. const {results, hasMore, nextCursor} = await fetchTeams(api, orgId, {
  249. search,
  250. limit,
  251. lastSearch,
  252. cursor,
  253. });
  254. const fetchedTeams = uniqBy([...store.teams, ...results], ({slug}) => slug);
  255. if (search) {
  256. // Only update the store if we have more items
  257. if (fetchedTeams.length > store.teams.length) {
  258. TeamActions.loadTeams(fetchedTeams);
  259. }
  260. } else {
  261. // If we fetched a page of teams without a search query, add cursor data to the store
  262. TeamActions.loadTeams(fetchedTeams, hasMore, nextCursor);
  263. }
  264. setState({
  265. ...state,
  266. hasMore: hasMore && store.hasMore,
  267. fetching: false,
  268. lastSearch: search ?? null,
  269. nextCursor,
  270. });
  271. } catch (err) {
  272. console.error(err); // eslint-disable-line no-console
  273. setState({...state, fetching: false, fetchError: err});
  274. }
  275. }
  276. useEffect(() => {
  277. // Load specified team slugs
  278. if (shouldLoadSlugs || shouldLoadIds) {
  279. loadTeamsBySlugOrId();
  280. return;
  281. }
  282. // Load user teams
  283. if (shouldLoadTeams) {
  284. loadUserTeams();
  285. }
  286. }, [slugOrIdRef.current, provideUserTeams]);
  287. const isSuperuser = isActiveSuperuser();
  288. const filteredTeams = useMemo(() => {
  289. return slugs
  290. ? store.teams.filter(t => slugs.includes(t.slug))
  291. : ids
  292. ? store.teams.filter(t => ids.includes(t.id))
  293. : provideUserTeams && !isSuperuser
  294. ? store.teams.filter(t => t.isMember)
  295. : store.teams;
  296. }, [store.teams, ids, slugs, provideUserTeams, isSuperuser]);
  297. const result: Result = {
  298. teams: filteredTeams,
  299. fetching: state.fetching || store.loading,
  300. initiallyLoaded: state.initiallyLoaded,
  301. fetchError: state.fetchError,
  302. hasMore: state.hasMore ?? store.hasMore,
  303. onSearch: handleSearch,
  304. loadMore: handleFetchAdditionalTeams,
  305. };
  306. return result;
  307. }
  308. export default useTeams;