I have been reading multiple articles and stack overflow posts on how to send a push notification. I have tried using collection listeners on my firestore collection, but it ends up sending notifications for all documents when the app closes. Then, I've tried firebase cloud functions and there always seems to be an error, even though I've taken it from a medium or stack overflow post and modified it to my database.
Every time I run $firebase deploy in the terminal, I get this error:
20:7 error Parsing error: Unexpected token body
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/g30r93g/.npm/_logs/2018-07-10T00_28_45_371Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
Here is my javascript code:
const functions = required('firebase-functions');
const admin = required('firebase-admin');
// initializes your application
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.firestore
.document("Users/{user-ID}/sub-Collection/{sub-Document-ID}")
.onCreate((events) => {
// Access data required for payload notification
const data = event.data.data();
const senderName = data.storeName;
// Determine the message
const payload = {
notification: {
title: "New Document"
body: "Tap me to show new document"
sound: 'default'
badge: '1'
}
}
// Get the user's tokenID
var pushToken = "";
return functions
.firestore
.collection("Users/{user-ID}")
.get()
.then((doc) => {
pushToken = doc.data().tokenID;
// Send the message to the device
return admin.messaging().sendTodevice(pushToken, message)
});
});
Thanks in advance for any replies.
You've written invalid JavaScript. Your payload
object needs its fields and values separated by commas:
// Determine the message
const payload = {
notification: {
title: "New Document",
body: "Tap me to show new document",
sound: 'default',
badge: '1'
}
}
Note the trailing commas.
The error message was "Parsing error: Unexpected token body". It was complaining specifically that it found the "body" field unexpectedly, which would have been your clue what it got hung up on.