useTeams.tsx 9.9 KB

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