import { firestore , Change , EventContext } from 'firebase-functions' ; import { Logger } from '../client/logger' ; import { RepositoryModel } from '../models/index.model' ; import { DocumentData , DocumentSnapshot , WriteResult } from './../client/firebase-admin' ; async function updateRepositories ( projectUid , newData , previousData ) { const isArrayNewDataRepositories = Array . isArray ( newData . repositories ) && newData . repositories . length > 0 ; const isArrayPreviousDataRepositories = Array . isArray ( previousData . repositories ) && previousData . repositories . length > 0 ; let add , remove ; const promiseList = [ ] ; if ( isArrayNewDataRepositories ) { if ( isArrayPreviousDataRepositories ) { add = newData . repositories . filter ( ( element ) => previousData . repositories . findIndex ( ( item ) => element === item ) === - 1 ) ; remove = previousData . repositories . filter ( ( element ) => newData . repositories . findIndex ( ( item ) => element === item ) === - 1 ) ; } else { add = newData . repositories ; remove = [ ] ; } } else { add = [ ] ; remove = isArrayPreviousDataRepositories ? previousData . repositories : [ ] ; } for ( const item of add ) { const repoData = ( await RepositoryModel . getRepositoryReference ( item ) . get ( ) ) . data ( ) ; if ( Array . isArray ( repoData . projects ) ) { const foundIndex = repoData . projects . findIndex ( ( element ) => element === projectUid ) ; if ( foundIndex === - 1 ) { repoData . projects . push ( projectUid ) ; } } else { repoData . projects = [ projectUid ] ; } const repo = RepositoryModel . getRepositoryReference ( repoData . uid ) . update ( { projects : repoData . projects } ) ; promiseList . push ( repo ) ; } for ( const item of remove ) { const repoData = ( await RepositoryModel . getRepositoryReference ( item ) . get ( ) ) . data ( ) ; if ( Array . isArray ( repoData . projects ) ) { repoData . projects = repoData . projects . filter ( ( element ) => element !== projectUid ) ; } else { repoData . projects = [ ] ; } const repo = RepositoryModel . getRepositoryReference ( repoData . uid ) . update ( { projects : repoData . projects } ) ; promiseList . push ( repo ) ; } return Promise . all ( promiseList ) ; } export const onUpdateProject = firestore . document ( 'projects/{projectUid}' ) . onUpdate ( async ( change , context ) => { try { const newData = change . after . data ( ) ; const previousData = change . before . data ( ) ; return updateRepositories ( context . params . projectUid , newData , previousData ) ; } catch ( err ) { Logger . error ( err ) ; throw new Error ( err ) ; } } ) ;