首页 > 解决方案 > Firebase 功能已部署,但未生成日志且未响应 onCreate() 事件触发

问题描述

我正在尝试创建一个 Firebase 云函数,它将在我的 react 本机应用程序的提要上侦听新帖子,然后将帖子的通知发送给所有用户。我决定从小处着手,首先从基本层面了解 Firebase Cloud Functions。

按照实时数据库触发器的 firebase 文档,我尝试创建下面代码中显示的函数。我相信该功能可以很好地部署到我的数据库,因为这是在命令提示符下输出的: 命令提示符输出

此外,我的 firebase 项目似乎也接收并存储了该函数: Firebase 项目功能 但是,当我返回我的数据库并在指定路径创建一个新节点时,什么也没有发生。此外,我检查了功能选项卡中的“日志”,但那里什么也没有。

任何帮助将不胜感激......谢谢!

编辑 1 这是我的数据库的屏幕截图: 在此处输入图像描述

编辑 2 尝试包括管理 SDK(如下所示)但没有变化。

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');

admin.initializeApp();

exports.sendPushNotifications = functions.database.ref('/{organization}/posts/')
    .onCreate((snapshot, context) => {
      const post = snapshot.val();
      console.log('Uppercasing', context.params.organization, post);
      const uppercasePost = post.toUpperCase();
      // You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
      return snapshot.ref.parent.child('cloudFunctionTest').set(uppercasePost);
    });

标签: firebasereact-nativefirebase-realtime-databasegoogle-cloud-functions

解决方案


您可能没有在正确的路径下创建“帖子”。

事实上,用你的代码

exports.sendPushNotifications = functions.database.ref('/{organization}/posts/')
    .onCreate((snapshot, context) => {})

Cloud Function 将为任何节点触发,如下所示

ksigapp   // <- Root of your database
    - abcd  //<- This corresponds to {organization} in your code
        - posts: "lowercase"
    - efgh  // <- This corresponds to {organization} in your code
        - posts: "whatever"
    - IUUY7676676fgfgfg7  //<- This corresponds to {organization} in your code
        - posts: "lowercase2"

....

其次, 的值posts必须是字符串,不能是对象,因为post.toUpperCase();会产生错误(不能将此方法应用于对象)。

换句话说,以下将产生错误:

ksigapp   // <- Root of your database
    - abcd  
        - posts
           - postId
              - author: "John"
              - subject: "Lorem ipsus"

所以你很可能不得不重新考虑你的云函数路径

您可以学习以下官方 Firebase 示例:https ://github.com/firebase/functions-samples/tree/master#rtdb


推荐阅读