我需要有关firestore功能的帮助。我正在开发一个需要通知的应用程序,我正在使用firebase作为后端,我对云功能特性完全陌生。
所以我想在将文档添加到集合时向用户发送通知,我已经尝试为函数设置一些东西,但是由于我不知道的原因它不起作用,我的Node Js是更新版本,firebase工具更新但我仍然得到错误。
这是我的index.js文件和错误消息。我感谢任何帮助。
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document('Users/{userId}/Notifications/{notificationId}').onWrite((change, context) =>{
const userId = context.params.userId;
const notificationId = context.params.notificationId;
console.log('The User id is : ', userId);
if(!context.data.val()){
return console.log('A notification has been deleted from the database');
}
// ref to the parent document
const device_token = admin.firestore.doc('Users/${userId}/Token/${userId}/deviceToken').once('value');
return device_token.then(result => {
const token_id = result.val();
const payLoad = {
notification:{
title: "Qubbe",
body: "You have a new comment!",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payLoad).then(response => {
console.log('This is the notification feature');
});
});
device_token.catch(error => {
console.log(error);
});
});
由于您使用以下语法onWrite((change, context)...)
,我假设您使用的是Cloud Functions版本> = 1.0。
对于版本> = 1.0,您应该在没有任何参数的情况下初始化firebase-admin
,如下所示:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
见https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin
感谢您的回复,问题现在已经解决了。
我首先删除了我的旧功能,然后重新开始,然后我全局安装了最新的firebase工具,并像平时一样在启动时更新npm工具。然后我在我的firestore中使用了这段代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
//const firestore = new Firestore();
//const settings = {/* Date... */ timestampsInSnapshots: true};
//firestore.settings(settings);
exports.sendNotification =
functions.firestore.document('Users/{userId}/Notifications/{notificationId}')
.onWrite((c hange, context) =>{
const userId = context.params.userId;
const notificationId = context.params.notificationId;
console.log('The User id is : ', userId);
console.log('The Notification id is : ', notificationId);
// ref to the parent document
return admin.firestore().collection("Users").doc(userId).collection("Token").doc(userId).get().then(queryResult => {
const tokenId = queryResult.data().deviceToken;
//const toUser = admin.firestore().collection("Users").doc(userId).collection("Notifications").doc(notificationId).get();
const notificationContent = {
notification:{
title: "/*App name */",
body: "You have a new Comment!",
icon: "default",
click_action: "/*Package */_TARGET_NOTIFICATION"
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
console.log("Notification sent!");
//admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).delete();
});
});
});