import { firestore , CloudFunction , 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 addUidToRepositories ( user ) { if ( user . repositories && Array . isArray ( user . repositories . data ) && user . repositories . data . length > 0 ) { const uids = [ ] ; user . repositories . data = user . repositories . data . filter ( ( item ) => item && item . id !== null && item . id !== undefined ) ; for ( const item of user . repositories . data ) { const exitsRepoUid = await RepositoryModel . getRepositoryUidById ( item . id ) ; if ( exitsRepoUid ) { item . uid = exitsRepoUid ; } else { item . uid = uuid ( ) ; } uids . push ( item . uid ) ; } user . repositories . data . uids = uids ; return true ; } return false ; } export const onCreateUser = firestore . document ( 'users/{userUid}' ) . onCreate ( async ( userSnapshot , context ) => { try { const newData = userSnapshot . data ( ) ; const isNeedUpdate = await addUidToRepositories ( newData ) ; if ( isNeedUpdate ) { await userSnapshot . ref . update ( newData ) ; } } catch ( err ) { Logger . error ( err ) ; throw new Error ( err ) ; } } ) ;