How can I implement a firebase set request within

2019-08-30 01:50发布

I'm new to node js and I would like to write information within a callback function to my firebase database.

I've been searching and it seems that the callback is asynchronous. How can I use firestore in this callback?

    exports.registerRestaurantPayout = functions.firestore.document('*********')
  .onCreate(async (paymentSnap, context) => {

    var request = require('request');

    var authCode = paymentSnap.data().auth_code;
    var firstString = 'client_secret=********&code=';
    var secondString = '&grant_type=authorization_code';
    var dataString = firstString + authCode + secondString;

    var options = {
        url: 'https://connect.stripe.com/oauth/token',
        method: 'POST',
        body: dataString
    };

    function callback(error, response, body) {
        if (!error && response.statusCode === 200) {
            console.log(body);

            return await firestore.document('***********')
              .set({'account': body}, {merge: true});
            //return await paymentSnap.ref.set({'account': body}, {merge: true});
        }else{


            //return await paymentSnap.ref.set({'error' : error}, { merge: true });
        }
    }

    request(options, callback);

  });

I get the following error Parsing error: Unexpected token firestore even though I can use firestore outside of the callback. The specific problem is the return statement in the callback

1条回答
孤傲高冷的网名
2楼-- · 2019-08-30 02:44

In a Cloud Function you should use promises to handle asynchronous tasks (like the HTTP call to the stripe API, or the write to the Realtime Database). By default request does not return promises, so you need to use an interface wrapper for request, like request-promise, and adapt your code along the following lines:

const rp = require('request-promise');

exports.registerRestaurantPayout = functions.firestore.document('*********')
 .onCreate((paymentSnap, context) => {

   var authCode = paymentSnap.data().auth_code;
   var firstString = 'client_secret=**********=';
   var secondString = '&grant_type=authorization_code';
   var dataString = firstString + authCode + secondString;


   var options = { 
     method: 'POST',
     uri: 'https://connect.stripe.com/oauth/token',
     body: dataString,
     json: true // Automatically stringifies the body to JSON
   };

   return rp(options)
   .then(parsedBody => {
       return paymentSnap.ref.set({'account': parsedBody}, {merge: true});
   })
   .catch(err => {
       return paymentSnap.ref.set({'error' : err}, { merge: true });
   });

});

I would also suggest that you watch the two following "must see" videos from the Firebase team, about Cloud Functions and promises: https://www.youtube.com/watch?v=7IkUgCLr5oA and https://www.youtube.com/watch?v=652XeeKNHSk.

查看更多
登录 后发表回答