javascript 监听firestore中Root集合云函数的变化

ddarikpa  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(59)

我看到的大多数例子都解释了如何监听带有用户uid的文档

exports.sendNotifications = functions.firestore.document('Notifications').onCreate(async (snapshot) => {
    // Notification details.
    const payload = {
      notification: {
          title: 'Hello',
          body: 'Hello again',
        click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
      }
    };

    // Get the list of device tokens.
    const allTokens = await admin.firestore().collection('fcmTokens').get();
    const tokens = [];
    allTokens.forEach((tokenDoc) => {
      tokens.push(tokenDoc.id);
    });

    if (tokens.length > 0) {
      // Send notifications to all tokens.
      const response = await admin.messaging().sendToDevice(tokens, payload);

    }
  });

这个云函数带来了functions: failed to create function sendNotifications HTTP Error: 400, The request has errors。我猜这个错误是因为没有正确引用firestore集合。它是根集合。怎样才能更好地参考呢

vmdwslir

vmdwslir1#

您应该在Cloud Function中修改以下几点:
1/您应该在创建文档时触发它,如下所示。参见https://firebase.google.com/docs/functions/firestore-events?authuser=0#wildcards-parameters。

exports.sendNotifications = functions.firestore.document('Notifications/{notifId}')
    .onCreate(async (snap, context) => {

      const newValue = snap.data();

      // perform desired operations ...
      // You may not need the notifId value but you have to keep the wildcard in the document path
    });

2/另外,请注意onCreate()如何具有datacontext参数。有关https://firebase.google.com/docs/functions/firestore-events?authuser=0#trigger_a_function_when_a_new_document_is_createdhttps://firebase.google.com/docs/functions/beta-v1-diff?authuser=0#cloud-firestore更多详细信息,请参见www.example.com和www.example.com。
3/最后,您应该返回admin.messaging()异步任务返回的promise,并在tokens.length = 0情况下返回一个值。这两个动作确保您向平台指示Cloud Function的工作已经完成。(我建议你观看Firebase视频系列中关于“JavaScript承诺”的3个视频:https://firebase.google.com/docs/functions/video-series/
因此,在最后,您的代码看起来如下所示。* (注意,我没有测试过它,所以我不能100%保证它会解决你的“HTTP错误:400,请求有错误”problem...)*

exports.sendNotifications = functions.firestore.document('Notifications/{notifId}')
.onCreate(async (snap, context) => {
    // Notification details.
    const payload = {
      notification: {
          title: 'Hello',
          body: 'Hello again',
        click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
      }
    };

    // Get the list of device tokens.
    const allTokens = await admin.firestore().collection('fcmTokens').get();
    const tokens = [];
    allTokens.forEach((tokenDoc) => {
      tokens.push(tokenDoc.id);
    });

    if (tokens.length > 0) {
      // Send notifications to all tokens.
      return await admin.messaging().sendToDevice(tokens, payload);
    } else {
      return null;
    }
  });

相关问题