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
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, likerequest-promise
, and adapt your code along the following lines: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.