【问题标题】:Firebase callable function to read real time databaseFirebase 可调用函数来读取实时数据库
【发布时间】:2020-08-04 08:16:22
【问题描述】:

这里我试图通过提供 UID 从实时数据库中访问用户的数据。我尝试了很多东西,但都没有奏效。我已按照文档进行操作,但运气不佳,我不断收到错误 -

Sending back results [promise]

另一个example 用于编写我遵循的数据来创建我的逻辑但它没有用 -

exports.userData = functions.https.onCall((data, context) => {

    // verify Firebase Auth ID token
    if (!context.auth) {
        return { message: 'Authentication Required!', code: 401 };
    }

    const userId = data.text;
    const ref = database.ref('/USERS/' + userId);
    return ref.on('value', (snapshot) => {
            console.log(snapshot); /* <--- I have tried with this and without this none worked*/
        })
        .then(snapshot => {
            return {
                data: snapshot
            };
        }).catch((error) => {
            throw new functions.https.HttpsError('unknown', error.message, error);
        });
});

我在客户端遇到的错误是 -

service.ts:160 POST https://us-central1-gokuapp.cloudfunctions.net/userData 500
error.ts:66 Uncaught (in promise) Error: INTERNAL
    at new YN (error.ts:66)
    at XN (error.ts:175)
    at rC.<anonymous> (service.ts:231)
    at tslib.es6.js:100
    at Object.next (tslib.es6.js:81)
    at r (tslib.es6.js:71)

编辑: 之前,我正确地编写了自己的代码,但是根据我在发现过程中所做的更改,我得到了错误或空对象。遇到同样问题的人,请记住这一点……“云功能需要时间预热才能完全发挥作用”,尽管我非常感谢@Frank van Puffelen 和@oug Stevenson他们的意见。 :) :) :)

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    不要在 Cloud Functions 中使用 on(),因为这会将持久侦听器附加到查询(并且它不会返回承诺)。使用once() 代替一次查询数据并获得通过快照解析的承诺。此外,您应该使用snapshot.val() 来获取包含快照内容的纯 JavaScript 对象。

    return ref.once('value')   // use once() here
        .then(snapshot => {
            return {
                data: snapshot.val()   // also use val() here to get a JS object
            };
        })
        .catch((error) => {
            throw new functions.https.HttpsError('unknown', error.message, error);
        });
    

    【讨论】:

      【解决方案2】:

      Callable Cloud Functions 可以返回任何 JSON 数据。但是,您的 snapshot 变量是一个 DataSnapshot 对象,其中包含的不仅仅是 JSON 数据。

      您可能希望返回快照的值:

      .then(snapshot => {
          return {
              data: snapshot.val()
          };
      

      【讨论】:

      • 感谢您的回复。我之前尝试过,但仍然是同样的错误。
      • 道格也指出了另一个问题。你可能必须先做他,但这肯定是另一个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2021-05-10
      • 2023-02-23
      • 2020-06-05
      • 2021-07-18
      • 2020-12-24
      相关资源
      最近更新 更多