Firebase 函数在本地运行但部署失败

时间:2021-03-21 14:08:18

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

我目前正在开发一个需要在 Firebase 上运行的后端代码的应用。我从未使用过 Typescript 和 Functions,因此我的代码中很可能存在阻止该函数部署的错误。让我感到困扰的是,这些函数在使用 firebase serve 的本地运行没有问题,但是,当我想部署该函数时,我收到错误消息,指出该函数没有正确部署。当我用调试运行它时,它说错误可能是由于用户代码中的错误造成的。 错误日志:

{"code":3,"message":"加载用户代码时函数失败。这可能是由于用户代码中的错误。错误消息:错误:请检查您的函数日志以查看错误原因: cloud.google.com/functions/docs/monitoring/logging#viewing_logs。其他故障排除文档可以在 cloud.google.com/functions/docs/troubleshooting#logging 找到。请访问 cloud.google.com/functions/docs/troubleshooting获取深入的故障排除文档。"}

我想让函数做的是从api下载数据,检查Firestore数据库中是否已经存在相同的数据,如果没有,则写入数据库。函数如下所示:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import fetch from "cross-fetch";

admin.initializeApp();

const db = admin.firestore();

export const scheduledFetch = functions.pubsub.schedule("*/15 * * * *").onRun( (context) => {
  fetch(url)
      .then((res) => {
        return res.json();
      }).then((data) => {
        console.log(data.articles);
        data.articles.array.forEach((article : any) => {
          const query = db
              .collection("sampleData")
              .where("title", "==", String(article.title));
          query.get().then((snapshot) => {
            if (snapshot.empty) {
              console.log("writing document");
              const data = {
                type: "article",
                author: article.author,
                title: article.title,
                description: article.description,
                url: article.url,
                urlToImage: article.urlToImage,
                publishedAt: article.publishedAt,
                content: article.content,
                source: article.source,
              };
              db.collection("sampleData")
                  .doc()
                  .set(data);
            } else {
              console.log("Already exists, not writing");
            }
          }).catch((error) => {
            console.log(error);
          });
        });
      }).catch((error) => {
        console.log(error);
      });
});

1 个答案:

答案 0 :(得分:0)

因此,在尝试定位问题几个小时后,firebase 函数服务似乎与交叉提取不兼容。安装并使用node-fetch后,功能部署正常。