Firebase函数提取令牌

nue99wik  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(124)

尝试使用Firebase函数从我的Cloud Firestore获取我的FCM令牌
我的函数代码:

const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotificationToFCMToken = functions.firestore.document('Posts/{likes}').onWrite(async (event) => {
    const title = event.after.get('title');
    const content = event.after.get('likes');
    let userDoc = await admin.firestore().doc('Users').get();
    let fcmToken = userDoc.get('{token}');

    var message = {
        notification: {
            title: title,
            body: "you have a new like",
        },
        token: fcmToken,
    }

    let response = await admin.messaging().send(message);
    console.log(response);
});

我的Firestore
职位:

用户:

如果我手动添加令牌一切工作,但只是发送每个“喜欢”到一个设备,我的目标是发送一个链接,只有所有者的职位

jm2pwxwz

jm2pwxwz1#

它可能更像这样:

let userRef = event.after.get('ref'); // obviously the path is mandatory ...
let userDoc = await admin.firestore().doc(userRef).get(); // then this should match
let token = userDoc.get('token'); // and the token should be accessible

添加日志记录以查看您得到的内容:functions.logger.info('🞬🞬🞬 ' + JSON.stringify(event)); ...可在https://console.cloud.google.com/logs/query查看。当监听Posts/{likes}时,您可能需要一个额外的查询,而当监听Posts时,您需要确定更改。要使后续查询工作,需要访问ref

li9yvcax

li9yvcax2#

Martin的答案是正确的,但似乎ref字段的类型是Reference,请参阅开头的斜杠,以及您得到的错误。
所以,如果这个假设是正确的,你应该使用path属性,如下所示(改编Martin的代码):

let userRef = event.after.get('ref'); // obviously the path is mandatory ...
let userDoc = await admin.firestore().doc(userRef.path).get(); // then this should match
let token = userDoc.get('token'); // and the token should be accessible

此外,为了正确地manage the life cycle of your Cloud Function,你应该做的,在结束时:

let response = await admin.messaging().send(message);
console.log(response);
return null;

或者只是

return admin.messaging().send(message);

相关问题