projects.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 'app/actions/projectActions';
  6. import {Client} from 'app/api';
  7. import ProjectsStore from 'app/stores/projectsStore';
  8. import {AvatarProject, Project} from 'app/types';
  9. import {defined} from 'app/utils';
  10. import parseLinkHeader from 'app/utils/parseLinkHeader';
  11. import RequestError from 'app/utils/requestError/requestError';
  12. import withApi from 'app/utils/withApi';
  13. import withProjects from 'app/utils/withProjects';
  14. type ProjectPlaceholder = AvatarProject;
  15. type State = {
  16. /**
  17. * Projects from API
  18. */
  19. fetchedProjects: Project[] | ProjectPlaceholder[];
  20. /**
  21. * Projects fetched from store
  22. */
  23. projectsFromStore: Project[];
  24. /**
  25. * Reflects whether or not the initial fetch for the requested projects
  26. * was fulfilled
  27. */
  28. initiallyLoaded: boolean;
  29. /**
  30. * This is state for when fetching data from API
  31. */
  32. fetching: boolean;
  33. /**
  34. * This is set when we fail to find some slugs from both store and API
  35. */
  36. isIncomplete: null | boolean;
  37. /**
  38. * Project results (from API) are paginated and there are more projects
  39. * that are not in the initial queryset
  40. */
  41. hasMore: null | boolean;
  42. prevSearch: null | string;
  43. nextCursor?: null | string;
  44. /**
  45. * The error that occurred if fetching failed
  46. */
  47. fetchError: null | RequestError;
  48. };
  49. export type RenderProps = {
  50. /**
  51. * We want to make sure that at the minimum, we return a list of objects with only `slug`
  52. * while we load actual project data
  53. */
  54. projects: Project[] | ProjectPlaceholder[];
  55. /**
  56. * Calls API and searches for project, accepts a callback function with signature:
  57. * fn(searchTerm, {append: bool})
  58. */
  59. onSearch: (searchTerm: string, {append: boolean}) => void;
  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. /**
  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. * List of slugs to look for summaries for, this can be from `props.projects`,
  83. * otherwise fetch from API
  84. */
  85. slugs?: string[];
  86. /**
  87. * Number of projects to return when not using `props.slugs`
  88. */
  89. limit?: number;
  90. /**
  91. * Whether to fetch all the projects in the organization of which the user
  92. * has access to
  93. * */
  94. allProjects?: boolean;
  95. children: RenderFunc;
  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 && !!slugs.length) {
  123. this.loadSpecificProjects();
  124. } else {
  125. this.loadAllProjects();
  126. }
  127. }
  128. /**
  129. * List of projects that need to be fetched via API
  130. */
  131. fetchQueue: Set<string> = new Set();
  132. /**
  133. * Memoized function that returns a `Map<project.slug, project>`
  134. */
  135. getProjectsMap: (projects: Project[]) => Map<string, Project> = memoize(
  136. projects => new Map(projects.map(project => [project.slug, project]))
  137. );
  138. /**
  139. * When `props.slugs` is included, identifies what projects we already
  140. * have summaries for and what projects need to be fetched from API
  141. */
  142. loadSpecificProjects = () => {
  143. const {slugs, projects} = this.props;
  144. const projectsMap = this.getProjectsMap(projects);
  145. // Split slugs into projects that are in store and not in store
  146. // (so we can request projects not in store)
  147. const [inStore, notInStore] = partition(slugs, slug => projectsMap.has(slug));
  148. // Get the actual summaries of projects that are in store
  149. const projectsFromStore = inStore.map(slug => projectsMap.get(slug)).filter(defined);
  150. // Add to queue
  151. notInStore.forEach(slug => this.fetchQueue.add(slug));
  152. this.setState({
  153. // placeholders for projects we need to fetch
  154. fetchedProjects: notInStore.map(slug => ({slug})),
  155. // set initallyLoaded if any projects were fetched from store
  156. initiallyLoaded: !!inStore.length,
  157. projectsFromStore,
  158. });
  159. if (!notInStore.length) {
  160. return;
  161. }
  162. this.fetchSpecificProjects();
  163. };
  164. /**
  165. * These will fetch projects via API (using project slug) provided by `this.fetchQueue`
  166. */
  167. fetchSpecificProjects = async () => {
  168. const {api, orgId, passthroughPlaceholderProject} = this.props;
  169. if (!this.fetchQueue.size) {
  170. return;
  171. }
  172. this.setState({
  173. fetching: true,
  174. });
  175. let projects: Project[] = [];
  176. let fetchError = null;
  177. try {
  178. const {results} = await fetchProjects(api, orgId, {
  179. slugs: Array.from(this.fetchQueue),
  180. });
  181. projects = results;
  182. } catch (err) {
  183. console.error(err); // eslint-disable-line no-console
  184. fetchError = err;
  185. }
  186. const projectsMap = this.getProjectsMap(projects);
  187. // For each item in the fetch queue, lookup the project object and in the case
  188. // where something wrong has happened and we were unable to get project summary from
  189. // the server, just fill in with an object with only the slug
  190. const projectsOrPlaceholder: Project[] | ProjectPlaceholder[] = Array.from(
  191. this.fetchQueue
  192. )
  193. .map(slug =>
  194. projectsMap.has(slug)
  195. ? projectsMap.get(slug)
  196. : !!passthroughPlaceholderProject
  197. ? {slug}
  198. : null
  199. )
  200. .filter(defined);
  201. this.setState({
  202. fetchedProjects: projectsOrPlaceholder,
  203. isIncomplete: this.fetchQueue.size !== projects.length,
  204. initiallyLoaded: true,
  205. fetching: false,
  206. fetchError,
  207. });
  208. this.fetchQueue.clear();
  209. };
  210. /**
  211. * If `props.slugs` is not provided, request from API a list of paginated project summaries
  212. * that are in `prop.orgId`.
  213. *
  214. * Provide render prop with results as well as `hasMore` to indicate there are more results.
  215. * Downstream consumers should use this to notify users so that they can e.g. narrow down
  216. * results using search
  217. */
  218. loadAllProjects = async () => {
  219. const {api, orgId, limit, allProjects} = this.props;
  220. this.setState({
  221. fetching: true,
  222. });
  223. try {
  224. const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
  225. limit,
  226. allProjects,
  227. });
  228. this.setState({
  229. fetching: false,
  230. fetchedProjects: results,
  231. initiallyLoaded: true,
  232. hasMore,
  233. nextCursor,
  234. });
  235. } catch (err) {
  236. console.error(err); // eslint-disable-line no-console
  237. this.setState({
  238. fetching: false,
  239. fetchedProjects: [],
  240. initiallyLoaded: true,
  241. fetchError: err,
  242. });
  243. }
  244. };
  245. /**
  246. * This is an action provided to consumers for them to update the current projects
  247. * result set using a simple search query. You can allow the new results to either
  248. * be appended or replace the existing results.
  249. *
  250. * @param {String} search The search term to use
  251. * @param {Object} options Options object
  252. * @param {Boolean} options.append Results should be appended to existing list (otherwise, will replace)
  253. */
  254. handleSearch = async (search: string, {append}: {append?: boolean} = {}) => {
  255. const {api, orgId, limit} = this.props;
  256. const {prevSearch} = this.state;
  257. const cursor = this.state.nextCursor;
  258. this.setState({fetching: true});
  259. try {
  260. const {results, hasMore, nextCursor} = await fetchProjects(api, orgId, {
  261. search,
  262. limit,
  263. prevSearch,
  264. cursor,
  265. });
  266. this.setState((state: State) => {
  267. let fetchedProjects;
  268. if (append) {
  269. // Remove duplicates
  270. fetchedProjects = uniqBy(
  271. [...state.fetchedProjects, ...results],
  272. ({slug}) => slug
  273. );
  274. } else {
  275. fetchedProjects = results;
  276. }
  277. return {
  278. fetchedProjects,
  279. hasMore,
  280. fetching: false,
  281. prevSearch: search,
  282. nextCursor,
  283. };
  284. });
  285. } catch (err) {
  286. console.error(err); // eslint-disable-line no-console
  287. this.setState({
  288. fetching: false,
  289. fetchError: err,
  290. });
  291. }
  292. };
  293. render() {
  294. const {slugs, children} = this.props;
  295. const renderProps = {
  296. // We want to make sure that at the minimum, we return a list of objects with only `slug`
  297. // while we load actual project data
  298. projects: this.state.initiallyLoaded
  299. ? [...this.state.fetchedProjects, ...this.state.projectsFromStore]
  300. : (slugs && slugs.map(slug => ({slug}))) || [],
  301. // This is set when we fail to find some slugs from both store and API
  302. isIncomplete: this.state.isIncomplete,
  303. // This is state for when fetching data from API
  304. fetching: this.state.fetching,
  305. // Project results (from API) are paginated and there are more projects
  306. // that are not in the initial queryset
  307. hasMore: this.state.hasMore,
  308. // Calls API and searches for project, accepts a callback function with signature:
  309. //
  310. // fn(searchTerm, {append: bool})
  311. onSearch: this.handleSearch,
  312. // Reflects whether or not the initial fetch for the requested projects
  313. // was fulfilled
  314. initiallyLoaded: this.state.initiallyLoaded,
  315. // The error that occurred if fetching failed
  316. fetchError: this.state.fetchError,
  317. };
  318. return children(renderProps);
  319. }
  320. }
  321. export default withProjects(withApi(Projects));
  322. type FetchProjectsOptions = {
  323. slugs?: string[];
  324. cursor?: State['nextCursor'];
  325. search?: State['prevSearch'];
  326. prevSearch?: State['prevSearch'];
  327. } & Pick<Props, 'limit' | 'allProjects'>;
  328. async function fetchProjects(
  329. api: Client,
  330. orgId: string,
  331. {slugs, search, limit, prevSearch, cursor, allProjects}: FetchProjectsOptions = {}
  332. ) {
  333. const query: {
  334. query?: string;
  335. cursor?: typeof cursor;
  336. per_page?: number;
  337. all_projects?: number;
  338. collapse: string[];
  339. } = {
  340. // Never return latestDeploys project property from api
  341. collapse: ['latestDeploys'],
  342. };
  343. if (slugs && slugs.length) {
  344. query.query = slugs.map(slug => `slug:${slug}`).join(' ');
  345. }
  346. if (search) {
  347. query.query = `${query.query ? `${query.query} ` : ''}${search}`;
  348. }
  349. if (((!prevSearch && !search) || prevSearch === search) && cursor) {
  350. query.cursor = cursor;
  351. }
  352. // "0" shouldn't be a valid value, so this check is fine
  353. if (limit) {
  354. query.per_page = limit;
  355. }
  356. if (allProjects) {
  357. const {loading, projects} = ProjectsStore.getState();
  358. // If the projects store is loaded then return all projects from the store
  359. if (!loading) {
  360. return {
  361. results: projects,
  362. hasMore: false,
  363. };
  364. }
  365. // Otherwise mark the query to fetch all projects from the API
  366. query.all_projects = 1;
  367. }
  368. let hasMore: null | boolean = false;
  369. let nextCursor: null | string = null;
  370. const [results, , xhr] = await api.requestPromise(`/organizations/${orgId}/projects/`, {
  371. includeAllArgs: true,
  372. query,
  373. });
  374. const pageLinks = xhr && xhr.getResponseHeader('Link');
  375. if (pageLinks) {
  376. const paginationObject = parseLinkHeader(pageLinks);
  377. hasMore =
  378. paginationObject &&
  379. (paginationObject.next.results || paginationObject.previous.results);
  380. nextCursor = paginationObject.next.cursor;
  381. }
  382. // populate the projects store if all projects were fetched
  383. if (allProjects) {
  384. ProjectActions.loadProjects(results);
  385. }
  386. return {
  387. results,
  388. hasMore,
  389. nextCursor,
  390. };
  391. }