projects.tsx 14 KB

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