import { firestore , Change , EventContext } from 'firebase-functions' ; import { v4 as uuid } from 'uuid' ; import { Logger } from '../client/logger' ; import { GitHubRepositoryModel } from '../mappers/github/index.mapper' ; import { DocumentData , DocumentSnapshot } from './../client/firebase-admin' ; import { RepositoryModel } from '../models/index.model' ; async function updateRepositories ( newData , previousData ) { const isArrayNewDataRepositories = ! ! ( newData && newData . repositories && Array . isArray ( newData . repositories . data ) && newData . repositories . data . length > 0 ) ; if ( ! isArrayNewDataRepositories ) { return null ; } const newRepos = newData . repositories . data ; const isArrayPreviousDataRepositories = ! ! ( previousData && previousData . repositories && Array . isArray ( previousData . repositories . data ) && previousData . repositories . data . length > 0 ) ; const oldRepos = isArrayPreviousDataRepositories ? previousData . repositories . data : [ ] ; let isExitFn = true ; if ( isArrayPreviousDataRepositories && newRepos . length === oldRepos . length ) { for ( const item1 of newRepos ) { if ( ( ! item1 ) || ( ! item1 . uid ) || item1 . id === null || item1 . id === undefined || oldRepos . findIndex ( ( item2 ) => item1 . id === item2 . id ) === - 1 ) { isExitFn = false ; break ; } } } else { isExitFn = false ; } if ( isExitFn ) { return null ; } const result = newRepos . filter ( ( item ) => item && item . id !== null && item . id !== undefined ) ; const uids = [ ] ; if ( isArrayPreviousDataRepositories ) { result . forEach ( ( item1 ) => { const found = oldRepos . find ( ( item2 ) => item1 . id === item2 . id ) ; if ( found && found . uid ) { item1 . uid = found . uid ; } } ) ; } for ( const item of result ) { if ( ! item . uid ) { const exitsRepoUid = await RepositoryModel . getRepositoryUidById ( item . id ) ; if ( exitsRepoUid ) { item . uid = exitsRepoUid ; } else { item . uid = uuid ( ) ; } } uids . push ( item . uid ) ; } return { repositories : { ... newData . repositories , data : result , uids , } , } ; } export const onUpdateUser = firestore . document ( 'users/{userUid}' ) . onUpdate ( async ( change , context ) => { try { const newData = change . after . data ( ) ; const previousData = change . before . data ( ) ; const result = await updateRepositories ( newData , previousData ) ; return result ? change . after . ref . update ( result ) : null ; } catch ( err ) { Logger . error ( err ) ; throw new Error ( err ) ; } } ) ;