javascript - 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 的投入。:) :) :)
解决方案
不要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);
});
推荐阅读
- php - 相等比较在php中不起作用
- php - 重力形式 + jQuery + PHP + ajax
- angular - Angular 5 中的 ActivatedRoute 不提供 URL 参数。想法?
- java - Firestore - 从添加的对象中获取自动生成的 ID
- azure-sql-database - Azure SqlServer 和 SqlDatabase 资源组
- python - 生成包含另一个 NumPy 数组索引的 NumPy 数组
- r - R:如何重定位值?
- docker - 无法使用 docker-compose.override 覆盖卷挂载
- regex - 如何将所有子域 url 重定向到主域
- python - How can I modify my script to allow Python to search recursively thought my folder structure?