useTeams.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import {useEffect, 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. export 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. const fetchedTeams = uniqBy([...store.teams, ...results], ({slug}) => slug);
  207. TeamActions.loadTeams(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. async function handleSearch(search: string) {
  221. if (search === '') {
  222. // Reset pagination state to match store if doing an empty search
  223. if (state.hasMore !== store.hasMore || state.nextCursor !== store.cursor) {
  224. setState({
  225. ...state,
  226. lastSearch: search,
  227. hasMore: store.hasMore,
  228. nextCursor: store.cursor,
  229. });
  230. }
  231. return;
  232. }
  233. handleFetchAdditionalTeams(search);
  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. TeamActions.loadTeams(fetchedTeams);
  258. }
  259. } else {
  260. // If we fetched a page of teams without a search query, add cursor data to the store
  261. TeamActions.loadTeams(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 = slugs
  288. ? store.teams.filter(t => slugs.includes(t.slug))
  289. : ids
  290. ? store.teams.filter(t => ids.includes(t.id))
  291. : provideUserTeams && !isSuperuser
  292. ? store.teams.filter(t => t.isMember)
  293. : store.teams;
  294. const result: Result = {
  295. teams: filteredTeams,
  296. fetching: state.fetching || store.loading,
  297. initiallyLoaded: state.initiallyLoaded,
  298. fetchError: state.fetchError,
  299. hasMore: state.hasMore ?? store.hasMore,
  300. onSearch: handleSearch,
  301. loadMore: handleFetchAdditionalTeams,
  302. };
  303. return result;
  304. }
  305. export default useTeams;