javascript - 我如何获取数据快照,然后在 firebase 云函数 http 请求中更新数据库

标签 javascript firebase google-cloud-functions firebase-admin

我正在尝试在云函数的 HTTPS 请求中获取 Firebase 实时数据库的数据快照,然后将来自查询的值添加到快照值,然后再次将其设置为数据库。

这是我的代码。

exports.addCredits = functions.https.onRequest((req, res)=>{
    console.log(req.query.UserID);
    var credits = req.query.amount
    var userId = req.query.UserID

    return admin.database().ref('/Users/' + userId).once('value').then(function(snapshot) {
        var userPoints = snapshot.val().Credit
        const databaseRef = admin.database().ref("Users").child(userId+"/Credit")
        res.send("Your Credits  "+ credits + " And User ID " + userId + " user points" + userPoints);
        var total = credits + userPoints
        databaseRef.set(total);
    })
})

部署代码时终端出现错误。

18:70  warning  Unexpected function expression              prefer-arrow-callback
18:70  error    Each then() should return a value or throw  promise/always-return

如何获取数据库快照并再次写入?

最佳答案

这些错误消息非常有帮助 Ganesh,请阅读它们...

18:70 警告意外的函数表达式 Preferred-arrow-callback

是一个警告,表示您应该使用 ES6 箭头函数语法,而不是带有“function”一词的老式语法:

return admin.database().ref('/Users/' + userId).once('value').then( snapshot => {

然后是实际的错误...

18:70 错误 每个 then() 应该返回一个值或抛出 Promise/always-return

告诉你每次使用.then()时,内部函数都需要返回一些东西。

return admin.database().ref('/Users/' + userId).once('value').then( snapshot => {
        var userPoints = snapshot.val().Credit
        const databaseRef = admin.database().ref("Users").child(userId+"/Credit")
        res.send("Your Credits  "+ credits + " And User ID " + userId + " user points" + userPoints);
        var total = credits + userPoints
        databaseRef.set(total);
        // You are inside of a .then() block here...
        // you HAVE return SOMETHING...
        // if you want, you could do:   return databaseRef.set(total);
        // or even just:   return true;
    })

关于javascript - 我如何获取数据快照,然后在 firebase 云函数 http 请求中更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54006980/

相关文章:

Firebase 云函数模拟器在 30000 毫秒后超时

ios - 查询不工作 Firebase Swift

ios - 创建一个整个 iOS 应用程序都可以访问的网络监听器

Firebase 函数无法部署,所有函数都出现相同的错误

node.js - 从 Cloud Functions Realtime Database 中的子引用获取父 Node 的原始值 "val()"数据

javascript - 仅允许使用正则表达式和字符串替换在 HTML/Javascript 中输入 1-12 和 00-59

在变量或对象中存储值时的 Javascript 错误计算

用于 Chrome 检查元素的 Javascript API

javascript - eval 不是函数

javascript - 使用 firebase 函数检查数据是否存在