im making a type of chat app. Im trying to write a firestore function that listens to a specific document that, when updated, will trigger the function to send a push notification to a specific user. However, im receiving an error. So far, i have:
export const messageListener = functions.firestore
.document("stingrayMessageListener/stingrayMessageListener")
.onWrite(async (change) => {
const beforeData = change?.before?.data();
const afterData = change?.before?.data();
if (beforeData?.receiverId!=afterData?.receiverId) {
const docRef = admin.firestore().doc("users/${afterData?.receiverId}");
const docSnap = await docRef.get();
const payload = {
notification: {
title: "New message!",
body: "${afterData?.senderName} has sent you a message!",
},
data: {
body: "message",
},
};
admin.messaging().sendToDevice(docSnap.data()?.token, payload);
}
});
This function is spitting out the following error:
Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array
Im pretty sure this is implying that docSnap() is returning as null, because token is a field on all user documents. Am I doing something wrong?
2
Answers
So, turns out it was a very simple solution. In Typescript, you can dont use "" to use a variable in a string. You use ``.
In addition to using template literals in your document paths as you answered, both
beforeData
andafterData
are assigned tochange?.before?.data()
, meaning your function won’t send notifications to any device:You’d only need to use the after property which holds the changed document.
Let me know if this was helpful.