Last active
April 2, 2023 20:55
-
-
Save duytq94/33f9c35975d232d228d5066ed982e7a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require('firebase-functions') | |
const admin = require('firebase-admin') | |
admin.initializeApp() | |
exports.sendNotification = functions.firestore | |
.document('messages/{groupId1}/{groupId2}/{message}') | |
.onCreate((snap, context) => { | |
console.log('----------------start function--------------------') | |
const doc = snap.data() | |
console.log(doc) | |
const idFrom = doc.idFrom | |
const idTo = doc.idTo | |
const contentMessage = doc.content | |
// Get push token user to (receive) | |
admin | |
.firestore() | |
.collection('users') | |
.where('id', '==', idTo) | |
.get() | |
.then(querySnapshot => { | |
querySnapshot.forEach(userTo => { | |
console.log(`Found user to: ${userTo.data().nickname}`) | |
if (userTo.data().pushToken && userTo.data().chattingWith !== idFrom) { | |
// Get info user from (sent) | |
admin | |
.firestore() | |
.collection('users') | |
.where('id', '==', idFrom) | |
.get() | |
.then(querySnapshot2 => { | |
querySnapshot2.forEach(userFrom => { | |
console.log(`Found user from: ${userFrom.data().nickname}`) | |
const payload = { | |
notification: { | |
title: `You have a message from "${userFrom.data().nickname}"`, | |
body: contentMessage, | |
badge: '1', | |
sound: 'default' | |
} | |
} | |
// Let push to the target device | |
admin | |
.messaging() | |
.sendToDevice(userTo.data().pushToken, payload) | |
.then(response => { | |
console.log('Successfully sent message:', response) | |
}) | |
.catch(error => { | |
console.log('Error sending message:', error) | |
}) | |
}) | |
}) | |
} else { | |
console.log('Can not find pushToken target user') | |
} | |
}) | |
}) | |
return null | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment