import { firestore , CloudFunction , EventContext } from 'firebase-functions' ; import { Logger } from '../client/logger' ; import { ProjectModel , RepositoryModel } from '../models/index.model' ; import { deleteMonitorPings } from '../monitor/monitor' ; import { DocumentData , DocumentReference , DocumentSnapshot , FirebaseAdmin , Transaction , WriteResult } from './../client/firebase-admin' ; async function deleteProjectRepositories ( projectUid , project ) { Logger . info ( 'deleteProjectRepositories' ) ; try { if ( Array . isArray ( project . repositories ) && project . repositories . length > 0 ) { for ( const repositoryUid of project . repositories ) { if ( ! repositoryUid ) { continue ; } const repoRef = RepositoryModel . getRepositoryReference ( repositoryUid ) ; await FirebaseAdmin . firestore ( ) . runTransaction ( ( t ) => { return t . get ( repoRef ) . then ( ( repo ) => { const repoData = repo . data ( ) ; if ( Array . isArray ( repoData . projects ) ) { repoData . projects = repoData . projects . filter ( ( element ) => element !== projectUid ) ; } else { repoData . projects = [ ] ; } t . update ( repoRef , { projects : repoData . projects } ) ; } ) ; } ) ; } } } catch ( err ) { Logger . error ( err ) ; throw new Error ( err ) ; } } ; export const deleteProjectPings = async ( project , isExpiredFlag ) : Promise < WriteResult [ ] > => { Logger . info ( 'deleteProjectPings' ) ; try { if ( Array . isArray ( project . monitors ) && project . monitors . length > 0 ) { const promises = [ ] ; for ( const monitor of project . monitors ) { promises . push ( deleteMonitorPings ( project . uid , monitor . uid , isExpiredFlag ) ) ; } return Promise . all ( promises ) ; } return Promise . all ( [ ] ) ; } catch ( err ) { Logger . error ( err ) ; throw new Error ( err ) ; } } ; export const onDeleteProject = firestore . document ( 'projects/{projectUid}' ) . onDelete ( async ( projectSnapshot , context ) => { const project = < ProjectModel > projectSnapshot . data ( ) ; deleteProjectPings ( project ) ; await deleteProjectRepositories ( context . params . projectUid , project ) ; } ) ;