聆听Firestore中根集合云功能的更改

时间:2019-04-02 07:43:54

标签: firebase google-cloud-firestore google-cloud-functions

我看到的大多数示例都说明了如何使用用户的uid来监听文档。我试图只监听普通的父集合

CustomInputDialog.showDialog(Test14dialog.this, "Title", fields, new CustomInputDialog.CustomInputDialogListener() {
        @Override
        public void onResult(ArrayList<String> result) {
            this.result = result;
            doThings();
        }
    });

此云功能带来了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); } }); 。我猜的错误是因为未正确引用firestore集合。这是根集合。我该如何更好地引用

1 个答案:

答案 0 :(得分:1)

您应该在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

3 /最后,您应该返回由admin.messaging()异步任务返回的promise,并在情况为tokens.length = 0的情况下返回一个值。这两个操作可确保您向平台指示Cloud Function的工作已完成。 (我建议您观看Firebase视频系列中有关“ JavaScript承诺”的3个视频:https://firebase.google.com/docs/functions/video-series/

因此,最后,您的代码将如下所示。 (请注意,我尚未对其进行测试,因此我不能100%保证它会解决您的“ HTTP错误:400,请求有错误”问题...)

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;
    }
  });