projects.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import {Component} from 'react';
  2. import memoize from 'lodash/memoize';
  3. import partition from 'lodash/partition';
  4. import uniqBy from 'lodash/uniqBy';
  5. import {Client} from 'sentry/api';
  6. import ProjectsStore from 'sentry/stores/projectsStore';
  7. import {AvatarProject, Project} from 'sentry/types';
  8. import {defined} from 'sentry/utils';
  9. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  10. import RequestError from 'sentry/utils/requestError/requestError';
  11. import withApi from 'sentry/utils/withApi';
  12. import withProjects from 'sentry/utils/withProjects';
  13. type ProjectPlaceholder = AvatarProject;
  14. type State = {
  15. /**
  16. * The error that occurred if fetching failed
  17. */
  18. fetchError: null | RequestError;
  19. /**
  20. * Projects from API
  21. */
  22. fetchedProjects: Project[] | ProjectPlaceholder[];
  23. /**
  24. * This is state for when fetching data from API
  25. */
  26. fetching: boolean;
  27. /**
  28. * Project results (from API) are paginated and there are more projects
  29. * that are not in the initial queryset
  30. */
  31. hasMore: null | boolean;
  32. /**
  33. * Reflects whether or not the initial fetch for the requested projects
  34. * was fulfilled
  35. */
  36. initiallyLoaded: boolean;
  37. /**
  38. * This is set when we fail to find some slugs from both store and API
  39. */
  40. isIncomplete: null | boolean;
  41. prevSearch: null | string;
  42. /**
  43. * Projects fetched from store
  44. */
  45. projectsFromStore: Project[];
  46. nextCursor?: null | string;
  47. };
  48. type RenderProps = {
  49. /**
  50. * Calls API and searches for project, accepts a callback function with signature:
  51. * fn(searchTerm, {append: bool})
  52. */
  53. onSearch: (searchTerm: string, options: {append: boolean}) => void;
  54. /**
  55. * We want to make sure that at the minimum, we return a list of objects with only `slug`
  56. * while we load actual project data
  57. */
  58. projects: Project[] | ProjectPlaceholder[];
  59. } & Pick<
  60. State,
  61. 'isIncomplete' | 'fetching' | 'hasMore' | 'initiallyLoaded' | 'fetchError'
  62. >;
  63. type RenderFunc = (props: RenderProps) => React.ReactNode;
  64. type DefaultProps = {
  65. /**
  66. * If slugs is passed, forward placeholder objects with slugs while fetching
  67. */
  68. passthroughPlaceholderProject?: boolean;
  69. };
  70. type Props = {
  71. api: Client;
  72. children: RenderFunc;
  73. /**
  74. * Organization slug
  75. */
  76. orgId: string;
  77. /**
  78. * List of projects that have we already have summaries for (i.e. from store)
  79. */
  80. projects: Project[];
  81. /**
  82. * Whether to fetch all the projects in the organization of which the user
  83. * has access to
  84. * */
  85. allProjects?: boolean;
  86. /**
  87. * Number of projects to return when not using `props.slugs`
  88. */
  89. limit?: number;
  90. /**
  91. * List of project ids to look for summaries for, this can be from `props.projects`,
  92. * otherwise fetch from API
  93. */
  94. projectIds?: number[];
  95. /**
  96. * List of slugs to look for summaries for, this can be from `props.projects`,
  97. * otherwise fetch from API
  98. */
  99. slugs?: string[];
  100. } & DefaultProps;
  101. class BaseProjects extends Component<Props, State> {
  102. static defaultProps: DefaultProps = {
  103. passthroughPlaceholderProject: true,
  104. };
  105. state: State = {
  106. fetchedProjects: [],
  107. projectsFromStore: [],
  108. initiallyLoaded: false,
  109. fetching: false,
  110. isIncomplete: null,
  111. hasMore: null,
  112. prevSearch: null,
  113. nextCursor: null,
  114. fetchError: null,
  115. };
  116. componentDidMount() {
  117. const {slugs, projectIds} = this.props;
  118. if (slugs?.length) {
  119. this.loadSpecificProjects();
  120. } else if (projectIds?.length) {
  121. this.loadSpecificProjectsFromIds();
  122. } else {
  123. this.loadAllProjects();
  124. }
  125. }
  126. componentDidUpdate(prevProps: Props) {
  127. const {projects} = this.props;
  128. if (projects !== prevProps.projects) {
  129. this.updateProjectsFromStore();
  130. }
  131. }
  132. /**
  133. * Function to update projects when the store emits updates
  134. */
  135. updateProjectsFromStore() {
  136. const {allProjects, projects, slugs} = this.props;
  137. if (allProjects) {
  138. this.setState({fetchedProjects: projects});
  139. return;
  140. }
  141. if (slugs?.length) {
  142. // Extract the requested projects from the store based on props.slugs
  143. const projectsMap = this.getProjectsMap(projects);
  144. const projectsFromStore = slugs.map(slug => projectsMap.get(slug)).filter(defined);
  145. this.setState({projectsFromStore});
  146. }
  147. }
  148. /**
  149. * List of projects that need to be fetched via API
  150. */
  151. fetchQueue: Set<string> = new Set();
  152. /**
  153. * Memoized function that returns a `Map<project.slug, project>`
  154. */
  155. getProjectsMap: (projects: Project[]) => Map<string, Project> = memoize(
  156. projects => new Map(projects.map(project => [project.slug, project]))
  157. );
  158. /**
  159. * Memoized function that returns a `Map<project.id, project>`
  160. */
  161. getProjectsIdMap: (projects: Project[]) => Map<number, Project> = memoize(
  162. projects => new Map(projects.map(project => [parseInt(project.id, 10), project]))
  163. );
  164. /**
  165. * When `props.slugs` is included, identifies what projects we already
  166. * have summaries for and what projects need to be fetched from API
  167. */
  168. loadSpecificProjects = () => {
  169. const {slugs, projects} = this.props;
  170. const projectsMap = this.getProjectsMap(projects);
  171. // Split slugs into projects that are in store and not in store
  172. // (so we can request projects not in store)
  173. const [inStore, notInStore] = partition(slugs, slug => projectsMap.has(slug));
  174. // Get the actual summaries of projects that are in store
  175. const projectsFromStore = inStore.map(slug => projectsMap.get(slug)).filter(defined);
  176. // Add to queue
  177. notInStore.forEach(slug => this.fetchQueue.add(slug));
  178. this.setState({
  179. // placeholders for projects we need to fetch
  180. fetchedProjects: notInStore.map(slug => ({slug})),
  181. // set initiallyLoaded if any projects were fetched from store
  182. initiallyLoaded: !!inStore.length,
  183. projectsFromStore,
  184. });
  185. if (!notInStore.length) {
  186. return;
  187. }
  188. this.fetchSpecificProjects();
  189. };
  190. /**
  191. * When `props.projectIds` is included, identifies if we already
  192. * have summaries them, otherwise fetches all projects from API
  193. */
  194. loadSpecificProjectsFromIds = () => {
  195. const {projectIds, projects} = this.props;
  196. const projectsMap = this.getProjectsIdMap(projects);
  197. // Split projectIds into projects that are in store and not in store
  198. // (so we can request projects not in store)
  199. const [inStore, notInStore] = partition(projectIds, id => projectsMap.has(id));
  200. if (notInStore.length) {
  201. this.loadAllProjects();
  202. return;
  203. }
  204. // Get the actual summaries of projects that are in store
  205. const projectsFromStore = inStore.map(id => projectsMap.get(id)).filter(defined);
  206. this.setState({
  207. // set initiallyLoaded if any projects were fetched from store
  208. initiallyLoaded: !!inStore.length,
  209. projectsFromStore,
  210. });
  211. };
  212. /**
  213. * These will fetch projects via API (using project slug) provided by `this.fetchQueue`
  214. */
  215. fetchSpecificProjects = async () => {
  216. const {api, orgId, passthroughPlaceholderProject} = this.props;
  217. if (!this.fetchQueue.size) {
  218. return;
  219. }
  220. this.setState({
  221. fetching: true,
  222. });
  223. let projects: Project[] = [];
  224. let fetchError = null;
  225. try {
  226. const {results} = await fetchProjects(api, orgId, {
  227. slugs: Array.from(this.fetchQueue),
  228. });
  229. projects = results;
  230. } catch (err) {
  231. console.error(err); // eslint-disable-line no-console
  232. fetchError = err;
  233. }
  234. const projectsMap = this.getProjectsMap(projects);
  235. // For each item in the fetch queue, lookup the project object and in the case
  236. // where something wrong has happened and we were unable to get project summary from
  237. // the server, just fill in with an object with only the slug
  238. const projectsOrPlaceholder: Project[] | ProjectPlaceholder[] = Array.from(
  239. this.fetchQueue
  240. )
  241. .map(slug =>
  242. projectsMap.has(slug)
  243. ? projectsMap.get(slug)
  244. : passthroughPlaceholderProject
  245. ? {slug}
  246. : null
  247. )
  248. .filter(defined);
  249. this.setState({
  250. fetchedProjects: projectsOrPlaceholder,
  251. isIncomplete: this.fetchQueue.size !== projects.length,
  252. initiallyLoaded: true,
  253. fetching: false,
  254. fetchError,
  255. });
  256. this.fetchQueue.clear();
  257. };
  258. /**
  259. * If `props.slugs` is not provided, request from API a list of paginated project summaries
  260. * that are in `prop.orgId`.
  261. *
  262. * Provide render prop with results as well as `hasMore` to indicate there are more results.
  263. * Downstream consumers should use this to notify users so that they can e.g. narrow down
  264. * results using search
  265. */
  266. loadAllProjects = async () => {
  267. const {api, orgId, limit, allProjects} = this.props;
  268. this.setState({
  269. fetching: true,
  270. });
  271. try {
  272. const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
  273. limit,
  274. allProjects,
  275. });
  276. this.setState({
  277. fetching: false,
  278. fetchedProjects: results,
  279. initiallyLoaded: true,
  280. hasMore,
  281. nextCursor,
  282. });
  283. } catch (err) {
  284. console.error(err); // eslint-disable-line no-console
  285. this.setState({
  286. fetching: false,
  287. fetchedProjects: [],
  288. initiallyLoaded: true,
  289. fetchError: err,
  290. });
  291. }
  292. };
  293. /**
  294. * This is an action provided to consumers for them to update the current projects
  295. * result set using a simple search query. You can allow the new results to either
  296. * be appended or replace the existing results.
  297. *
  298. * @param {String} search The search term to use
  299. * @param {Object} options Options object
  300. * @param {Boolean} options.append Results should be appended to existing list (otherwise, will replace)
  301. */
  302. handleSearch = async (search: string, {append}: {append?: boolean} = {}) => {
  303. const {api, orgId, limit} = this.props;
  304. const {prevSearch} = this.state;
  305. const cursor = this.state.nextCursor;
  306. this.setState({fetching: true});
  307. try {
  308. const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
  309. search,
  310. limit,
  311. prevSearch,
  312. cursor,
  313. });
  314. this.setState((state: State) => {
  315. let fetchedProjects;
  316. if (append) {
  317. // Remove duplicates
  318. fetchedProjects = uniqBy(
  319. [...state.fetchedProjects, ...results],
  320. ({slug}) => slug
  321. );
  322. } else {
  323. fetchedProjects = results;
  324. }
  325. return {
  326. fetchedProjects,
  327. hasMore,
  328. fetching: false,
  329. prevSearch: search,
  330. nextCursor,
  331. };
  332. });
  333. } catch (err) {
  334. console.error(err); // eslint-disable-line no-console
  335. this.setState({
  336. fetching: false,
  337. fetchError: err,
  338. });
  339. }
  340. };
  341. render() {
  342. const {slugs, children} = this.props;
  343. const renderProps = {
  344. // We want to make sure that at the minimum, we return a list of objects with only `slug`
  345. // while we load actual project data
  346. projects: this.state.initiallyLoaded
  347. ? [...this.state.fetchedProjects, ...this.state.projectsFromStore]
  348. : (slugs && slugs.map(slug => ({slug}))) || [],
  349. // This is set when we fail to find some slugs from both store and API
  350. isIncomplete: this.state.isIncomplete,
  351. // This is state for when fetching data from API
  352. fetching: this.state.fetching,
  353. // Project results (from API) are paginated and there are more projects
  354. // that are not in the initial queryset
  355. hasMore: this.state.hasMore,
  356. // Calls API and searches for project, accepts a callback function with signature:
  357. //
  358. // fn(searchTerm, {append: bool})
  359. onSearch: this.handleSearch,
  360. // Reflects whether or not the initial fetch for the requested projects
  361. // was fulfilled
  362. initiallyLoaded: this.state.initiallyLoaded,
  363. // The error that occurred if fetching failed
  364. fetchError: this.state.fetchError,
  365. };
  366. return children(renderProps);
  367. }
  368. }
  369. /**
  370. * @deprecated consider using useProjects if possible.
  371. *
  372. * This is a utility component that should be used to fetch an organization's projects (summary).
  373. * It can either fetch explicit projects (e.g. via slug) or a paginated list of projects.
  374. * These will be passed down to the render prop (`children`).
  375. *
  376. * The legacy way of handling this is that `ProjectSummary[]` is expected to be included in an
  377. * `Organization` as well as being saved to `ProjectsStore`.
  378. */
  379. const Projects = withProjects(withApi(BaseProjects));
  380. export default Projects;
  381. type FetchProjectsOptions = {
  382. cursor?: State['nextCursor'];
  383. prevSearch?: State['prevSearch'];
  384. search?: State['prevSearch'];
  385. slugs?: string[];
  386. } & Pick<Props, 'limit' | 'allProjects'>;
  387. async function fetchProjects(
  388. api: Client,
  389. orgId: string,
  390. {slugs, search, limit, prevSearch, cursor, allProjects}: FetchProjectsOptions = {}
  391. ) {
  392. const query: {
  393. collapse: string[];
  394. all_projects?: number;
  395. cursor?: typeof cursor;
  396. per_page?: number;
  397. query?: string;
  398. } = {
  399. // Never return latestDeploys project property from api
  400. collapse: ['latestDeploys'],
  401. };
  402. if (slugs && slugs.length) {
  403. query.query = slugs.map(slug => `slug:${slug}`).join(' ');
  404. }
  405. if (search) {
  406. query.query = `${query.query ? `${query.query} ` : ''}${search}`;
  407. }
  408. if (((!prevSearch && !search) || prevSearch === search) && cursor) {
  409. query.cursor = cursor;
  410. }
  411. // "0" shouldn't be a valid value, so this check is fine
  412. if (limit) {
  413. query.per_page = limit;
  414. }
  415. if (allProjects) {
  416. const projects = ProjectsStore.getAll();
  417. const loading = ProjectsStore.isLoading();
  418. // If the projects store is loaded then return all projects from the store
  419. if (!loading) {
  420. return {
  421. results: projects,
  422. hasMore: false,
  423. };
  424. }
  425. // Otherwise mark the query to fetch all projects from the API
  426. query.all_projects = 1;
  427. }
  428. let hasMore: null | boolean = false;
  429. let nextCursor: null | string = null;
  430. const [data, , resp] = await api.requestPromise(`/organizations/${orgId}/projects/`, {
  431. includeAllArgs: true,
  432. query,
  433. });
  434. const pageLinks = resp?.getResponseHeader('Link');
  435. if (pageLinks) {
  436. const paginationObject = parseLinkHeader(pageLinks);
  437. hasMore =
  438. paginationObject &&
  439. (paginationObject.next.results || paginationObject.previous.results);
  440. nextCursor = paginationObject.next.cursor;
  441. }
  442. // populate the projects store if all projects were fetched
  443. if (allProjects) {
  444. ProjectsStore.loadInitialData(data);
  445. }
  446. return {
  447. results: data,
  448. hasMore,
  449. nextCursor,
  450. };
  451. }