调用firebase pubsub函数,但不写入firestore

时间:2019-05-06 14:12:32

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

我有一个简单的pub sub cloud功能

var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});


exports.updateNews = functions.pubsub
  .topic("firebase-schedule-cronForNews-us-central1")
  .onPublish(message => {
    axios
      .get(
        "https://newsapi.org/v2/top-headlines?apiKey=241414&sources=espn-cric-info"
      )
      .then(result => {
        return result.data.articles.forEach(article => {
          db.collection("news").add(article);
        });
      })
      .then(result => {
        console.log(result);
        return result;
      })
      .catch(error => {
        console.log(error);
        return error;
      });

    return null;
  });

该函数正在被调用,但是它没有写到firestore中,当我将其转换为http函数时,相同的代码也可以工作。

1 个答案:

答案 0 :(得分:1)

您可以尝试返回承诺链并使用batched write,如下所示:

exports.updateNews = functions.pubsub
  .topic("firebase-schedule-cronForNews-us-central1")
  .onPublish(message => {
    return axios  // Note the return here
      .get(
        "https://newsapi.org/v2/top-headlines?apiKey=241414&sources=espn-cric-info"
      )
      .then(result => {
        const batch = admin.firestore().batch();
        result.data.articles.forEach(article => {
           const docRef = admin.firestore().collection("news").doc();
           batch.set(docRef, article);
        });
        return batch.commit();
      })
      .then(result => {  // You don't need this then if you don't need the console.log
        console.log(result);  
        return null;
      });
  });