Request not returning Write to database. Just show

2019-08-29 11:14发布

I am trying to save my response into the database. but it shows only the console and does not return the write to the database.

here is my code....

exports.saveGroups = functions.firestore.document("Users/{user_id}").onWrite((change,context) => {



token_id1 = change.after.data().token_id;
token_email = change.after.data().email;
image = change.after.data().image;
name1 = change.after.data().name;
user_id = context.params.user_id;
console.log('token_id1:' + token_id1);
console.log('token_email:' + token_email);
console.log('Image:' + image);
console.log('name:' + name1);
console.log('user_id' + user_id);

var headers = {
   'Authorization': 'key = AAAATmJbwHE:APA91bGIEsq0aioIzAa_7g5JvLX1NPU3z1Gkt6vxB2J-I_9IvllwDJaxjmEp5DPw6ZoEBmXfwiYwICrMuE0kQrvxuHTGPc5YKr3i-JNru-o6AHnrAjq4r7iZWmzUuSmPwu8CbR2kXEIq',
   'project_id': '336657629297',
   'Content-Type': 'application/json'
}


var options = {
    url: 'https://android.googleapis.com/gcm/notification',
    method: 'POST',
    headers: headers,
    json: {'operation': 'create',
    'notification_key_name': token_email,
    'registration_ids': [token_id1]}
}



 const promise = request(options, function (error, response, body) {
 tokenName = body.notification_key;
 console.log('Key: ' + tokenName); //here it shows me the correct value
 return db.collection('Users').doc(user_id).set({name: name1,token_id: token_id1,notification_key: tokenName,image: image,email: token_email}).then(() => {        //never reach this line
 return console.log("Document successfully written!");   //never returns this console       
 }).catch(function(error) {
    return console.error("Error writing document: ", error);
   });


  })

  return promise;           //finishes with status "ok"

 });

I've gone through the promises documentation. but I don't find any example to handle the "request" functions.

requires help. thanks in advance.

1条回答
欢心
2楼-- · 2019-08-29 11:57

request supports callback interfaces natively but does not return a promise, which is what you must do within a Cloud Function.

I strongly suggest that you watch these videos from the Firebase team: https://www.youtube.com/watch?v=7IkUgCLr5oA&t=28s and https://www.youtube.com/watch?v=652XeeKNHSk which explain this key concept.

You could use request-promise (https://github.com/request/request-promise) and rp(...) method which "returns a regular Promises/A+ compliant promise" and then do something like:

....
return rp(options)  // <- You should return this promise within the Function
    .then(function (body) {
        const tokenName = body.notification_key;
        console.log('Key: ' + tokenName);
        return db.collection('Users').doc(user_id).set({name: name1,token_id: token_id1,notification_key: tokenName,image: image,email: token_email});
    })
    .catch(function (err) {
        console.log(err);
    });
查看更多
登录 后发表回答