import * as firebase from 'firebase-admin' ; import { FirebaseAdmin } from '../client/firebase-admin' ; import { GitHubClient } from '../client/github' ; import { Logger } from '../client/logger' ; import { BuildTimes , GitHubPullRequestStatusInput , GitHubPullRequestStatusMapper , GitHubPullRequestStatusModel } from '../mappers/github/status.mapper' ; import { deleteCollection } from '../shared/delete-collection' ; param statuses export const getPullRequestBuildTime = ( statuses ) : BuildTimes [ ] => { const contexts = statuses . map ( ( status ) => status . context ) ; const uniqueContexts = Array . from ( new Set ( contexts ) . values ( ) ) ; const buildTimes = [ ] ; uniqueContexts . map ( ( context ) => { const filteredStatus = statuses . filter ( ( status ) => status . context === context ) ; if ( filteredStatus . length > 0 ) { const buildTime = Math . floor ( new Date ( filteredStatus [ 0 ] . updatedAt ) . getTime ( ) - new Date ( filteredStatus [ filteredStatus . length - 1 ] . updatedAt ) . getTime ( ) ) / 1000 ; buildTimes . push ( { context : context , time : buildTime } ) ; } } ) ; return buildTimes ; } ; /**
 * Save pull request status data in builds subcollection
 */ export const getPullRequestStatus = async ( token , fullName , ref , repositoryUid , pullRequestUid ) : Promise < GitHubPullRequestStatusModel [ ] > => { let data ; let mappedData ; try { data = await GitHubClient < GitHubPullRequestStatusInput [ ] > ( `/repos/${ fullName }/statuses/${ ref }` , token ) ; mappedData = data . map ( ( pullrequest ) => GitHubPullRequestStatusMapper . import ( pullrequest ) ) ; const buildTimes = getPullRequestBuildTime ( mappedData ) ; await FirebaseAdmin . firestore ( ) . collection ( `repositories/${ repositoryUid }/statuses` ) . doc ( pullRequestUid . toString ( ) ) . set ( { latest : { commitId : ref , statuses : mappedData , buildTimes : buildTimes } , historic : firebase . firestore . FieldValue . arrayUnion ( { commitId : ref , statuses : mappedData , buildTimes : buildTimes } ) , } , { merge : true } ) ; } catch ( error ) { Logger . error ( error , [ `Pull request status path: ${ fullName }/statuses/${ ref }` ] ) ; throw new Error ( error ) ; } return mappedData ; } ; export function deleteRepoBuilds ( repoUid ) { Logger . info ( 'deleteRepoBuilds' ) ; return deleteCollection ( FirebaseAdmin . firestore ( ) , `repositories/${ repoUid }/statuses` , 1000 ) ; } ;