useMembers.tsx 9.7 KB

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