import { errorApiRef , useApi } from '@backstage/core-plugin-api' ; import { useState } from 'react' ; import { useAsyncRetry } from 'react-use' ; import { buildKiteApiRef } from '../api' ; import { BuildkiteBuildInfo } from './types' ; import { generateRequestUrl } from './utils' ; export const transform = ( buildsData , restartBuild ) : BuildkiteBuildInfo [ ] => { return buildsData . map ( ( buildData ) => { const tableBuildInfo = { ... buildData , onRestartClick : ( ) => { restartBuild ( generateRequestUrl ( buildData . url ) ) ; } , } ; return tableBuildInfo ; } ) ; } ; export const useBuilds = ( { owner , repo } ) => { const api = useApi ( buildKiteApiRef ) ; const errorApi = useApi ( errorApiRef ) ; const [ total , setTotal ] = useState ( 0 ) ; const [ page , setPage ] = useState ( 0 ) ; const [ pageSize , setPageSize ] = useState ( 5 ) ; const { value , loading , retry } = useAsyncRetry ( async ( ) => { let builds = [ ] ; try { builds = await api . getBuilds ( owner , repo , page + 1 , pageSize ) ; } catch ( e ) { errorApi . post ( e ) ; } if ( page === 0 ) setTotal ( builds ?. [ 0 ] . number ) ; const response = transform ( builds ?? [ ] , restartBuild ) as any ; return response ; } , [ page , pageSize ] ) ; const restartBuild = async ( requestUrl ) => { try { await api . restartBuild ( requestUrl ) ; retry ( ) ; return ; } catch ( e ) { errorApi . post ( e ) ; throw e ; } } ; const projectName = `${ owner }/${ repo }` ; return [ { page , pageSize , loading : loading , builds : value as BuildkiteBuildInfo [ ] , projectName , total , } , { setPage , setPageSize , restartBuild , retry , } , ] as const ; } ;