首页 > 解决方案 > Firebase 可调用函数来读取实时数据库

问题描述

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

发回结果[承诺]

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

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 的投入。:) :) :)

标签: javascriptnode.jsfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


不要on()在 Cloud Functions 中使用,因为它会将持久侦听器附加到查询(并且它不会返回承诺)。而是使用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);
    });

推荐阅读