简体   繁体   中英

How can i get data snapshot and then update database in firebase cloud functions http request

I am trying to take data shapshot of firebase realtime database in HTTPS request of cloud functions and then add value coming from query to snapshot value and again set it to database.

Here is my code.

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);
    })
})

Here is error in terminal while deploying the code.

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

How can i get the snapshot of my database and again write it?

Those error messages are very helpful Ganesh, read both of them...

18:70 warning Unexpected function expression prefer-arrow-callback

is a WARNING, saying that you should use ES6 arrow function syntax instead of the old fashioned syntax with the word " function ":

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

And then the actual ERROR...

18:70 error Each then() should return a value or throw promise/always-return

tells you that every time you use .then() , the interior function needs to return something.

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;
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM