import { useEffect , useState } from 'react' ; import { useAsyncRetry } from 'react-use' ; import { githubPullRequestsApiRef } from '../api/GithubPullRequestsApi' ; import { useApi , githubAuthApiRef } from '@backstage/core-plugin-api' ; import { PullsListResponseData } from '@octokit/types' ; import moment from 'moment' ; import { PullRequestState } from '../types' ; import { useBaseUrl } from './useBaseUrl' ; export type PullRequest = { id : number ; number : number ; url : string ; title : string ; updatedTime : string ; createdTime : string ; state : string ; draft : boolean ; merged : string | null ; creatorNickname : string ; creatorProfileLink : string ; } ; export function usePullRequests ( { owner , repo , branch , state , } ) { const api = useApi ( githubPullRequestsApiRef ) ; const auth = useApi ( githubAuthApiRef ) ; const baseUrl = useBaseUrl ( ) ; const [ total , setTotal ] = useState ( 0 ) ; const [ page , setPage ] = useState ( 0 ) ; const [ pageSize , setPageSize ] = useState ( 5 ) ; const getElapsedTime = ( start ) => { return moment ( start ) . fromNow ( ) ; } ; const { loading , value : prData , retry , error } = useAsyncRetry < PullRequest [ ] > ( async ( ) => { const token = await auth . getAccessToken ( [ 'repo' ] ) ; if ( ! repo ) { return [ ] ; } return ( api . listPullRequests ( { token , owner , repo , pageSize , page : page + 1 , branch , state , baseUrl , } ) . then ( ( { maxTotalItems , pullRequestsData , } ) => { if ( maxTotalItems ) { setTotal ( maxTotalItems ) ; } return pullRequestsData . map ( ( { id , html_url , title , number , created_at , updated_at , user , state : pr_state , draft , merged_at , } ) => ( { url : html_url , id , number , title , state : pr_state , draft , merged : merged_at , creatorNickname : user . login , creatorProfileLink : user . html_url , createdTime : getElapsedTime ( created_at ) , updatedTime : getElapsedTime ( updated_at ) , } ) ) ; } ) ) ; } , [ page , pageSize , repo , owner ] ) ; useEffect ( ( ) => { setPage ( 0 ) ; retry ( ) ; } , [ state ] ) ; return [ { page , pageSize , loading , prData , projectName : `${ owner }/${ repo }` , total , error , } , { prData , setPage , setPageSize , retry , } , ] as const ; }