2022-06-06 17:36:59 +00:00
|
|
|
import * as functions from 'firebase-functions'
|
2022-06-22 16:05:54 +00:00
|
|
|
import * as admin from 'firebase-admin'
|
|
|
|
|
2022-06-06 17:36:59 +00:00
|
|
|
import { getUser } from './utils'
|
|
|
|
import { createNotification } from './create-notification'
|
2022-06-22 16:05:54 +00:00
|
|
|
import { FieldValue } from 'firebase-admin/firestore'
|
2022-06-06 17:36:59 +00:00
|
|
|
|
|
|
|
export const onFollowUser = functions.firestore
|
|
|
|
.document('users/{userId}/follows/{followedUserId}')
|
|
|
|
.onCreate(async (change, context) => {
|
2022-06-22 16:05:54 +00:00
|
|
|
const { userId, followedUserId } = context.params as {
|
2022-06-06 17:36:59 +00:00
|
|
|
userId: string
|
2022-06-22 16:05:54 +00:00
|
|
|
followedUserId: string
|
2022-06-06 17:36:59 +00:00
|
|
|
}
|
|
|
|
const { eventId } = context
|
|
|
|
|
|
|
|
const follow = change.data() as { userId: string; timestamp: number }
|
|
|
|
|
|
|
|
const followingUser = await getUser(userId)
|
|
|
|
if (!followingUser) throw new Error('Could not find following user')
|
|
|
|
|
2022-06-22 16:05:54 +00:00
|
|
|
await firestore.doc(`users/${followedUserId}`).update({
|
|
|
|
followerCountCached: FieldValue.increment(1),
|
|
|
|
})
|
|
|
|
|
2022-06-06 17:36:59 +00:00
|
|
|
await createNotification(
|
|
|
|
followingUser.id,
|
|
|
|
'follow',
|
|
|
|
'created',
|
|
|
|
followingUser,
|
|
|
|
eventId,
|
2022-06-08 14:43:24 +00:00
|
|
|
'',
|
2022-06-06 17:36:59 +00:00
|
|
|
undefined,
|
|
|
|
undefined,
|
|
|
|
follow.userId
|
|
|
|
)
|
|
|
|
})
|
2022-06-22 16:05:54 +00:00
|
|
|
|
|
|
|
const firestore = admin.firestore()
|