projects.tsx 13 KB

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