import * as functions from "firebase-functions" ; import * as admin from "firebase-admin" ; admin . initializeApp ( functions . config ( ) . firebase ) ; export const updateFollowerCounts = functions . firestore . document ( "relationships/{relationshipId}" ) . onWrite ( event => { if ( event . data . exists && event . data . previous ) { return null ; } const countChange = event . data . exists ? 1 : - 1 ; const ids = event . params . relationshipId . split ( "_" ) ; const followerId = ids [ 0 ] ; const followedId = ids [ 1 ] ; const db = admin . firestore ( ) ; const followerRef = db . collection ( "users" ) . doc ( followerId ) ; const followedRef = db . collection ( "users" ) . doc ( followedId ) ; return db . runTransaction ( async ( t ) => { const follower = await t . get ( followerRef ) ; const followed = await t . get ( followedRef ) ; const followerUpdate = { followingCount : ( follower . data ( ) . followingCount || 0 ) + countChange } ; const followedUpdate = { followerCount : ( followed . data ( ) . followerCount || 0 ) + countChange } ; await t . set ( followerRef , followerUpdate , { merge : true } ) ; await t . set ( followedRef , followedUpdate , { merge : true } ) ; return t ; } ) ; } ) ; export const updatePostCount = functions . firestore . document ( "posts/{postId}" ) . onCreate ( async ( event ) => { const userId = event . data . data ( ) . userId ; const db = admin . firestore ( ) ; const userRef = db . collection ( "users" ) . doc ( userId ) ; const user = await userRef . get ( ) ; const postCount = ( user . data ( ) . postCount || 0 ) + 1 ; return userRef . update ( { postCount } ) ; } ) ;