我正在开发iOS应用程序,现在我已经遇到了Firebase部署功能。我试图发送推送通知,我准备了如下代码。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotifications = functions.database.ref('/messages/{messageId}')
.onCreate(event => {
const data = event.data;
const fromId = data.fromId;
const toId = data.toId;
const message = data.message;
console.log(fromId + ' sent a message to' + toId);
return admin.database().ref('/users/' + fromId).once('value', snapshot => {
var user = snapshot.val();
var payload = {
notification: {
title: user.username,
body: message
}
}
admin.messaging().sendToDevice(user.fcmToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
})
数据库结构:
messages - messageId -fromId
└toId
└Message
└ messageId -fromId
└toId
└Message
.
.
.
这是错误信息。
37:1 error Parsing error: Unexpected token
✖ 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/...
Error: functions predeploy error: Command terminated with non-zero exit code1
同样在日志中,我收到如下错误:
TypeError: Cannot read property 'fromId' of undefined
是否发生了错误,因为我没有抓取fcmToken对吗?
我从未用JavaScirpt编码。我很感激任何建议!
答案 0 :(得分:5)
改变这个:
exports.pushNotifications = functions.database.ref('/messages/{messageId}')
.onCreate(event => {
const data = event.data;
const fromId = data.fromId;
const toId = data.toId;
const message = data.message;
进入这个:
exports.pushNotifications = functions.database.ref('/messages/{messageId}')
.onCreate((snap,context) => {
const data = snap.val();
const fromId = data.fromId;
const toId = data.toId;
const message = data.message;
});
点击此处了解更多信息:
答案 1 :(得分:3)
你最有可能运行v1的firebase函数,这是最新版本,它给api带来了不少变化。您可以阅读有关更改的更多信息here。具体而言,您希望将event =>
参数更改为(snap, context) =>
exports.dbWrite = functions.database.ref('/path').onCreate((snap, context) => {
const data = snap.val();
const { fromId, toId } = data;
...
});