Unable to drag data to Firebase from Alexa Skill hosted on AWS Lambda

I have a database in Firebase to which I am trying to write some data from my Alexa Skill. The Node.js code for this skill is inside the AWS Lambda function, and when this code is executed, I want to push some data to Firebase.

I tested the code that connects to Firebase outside of Lambda and pushes it, and works exactly as expected. Below is the code:

var firebase = require('firebase'); firebase.initializeApp({ databaseURL: 'https://myapp.firebaseio.com', serviceAccount: './myapp.json', }); var cart = firebase.database().ref('/cart'); console.log(cart); cart.push( { item: 'apples', quantity: '1', amount: '0' }, function(error) { if (error) { console.log("Data could not be saved." + error); } else { console.log("Data saved successfully."); } }); 

The same code does not click anything on the database instance when executed from the Lambda function. I read on the Internet that the Lambda timeout limit could be the reason for this, so I increased the timeout limit to a minute and it still doesn't work as expected. I also tried using the Firebase REST API instead of my Node.js SDK, and that didn't work either. What is the correct way to transfer data to Firebase from AWS Lambda?

+5
source share
2 answers

I think I know why this is happening, I had a similar problem and this is what I did.

If you want to write some date to your database, you need to make sure that you do not call this.emit (*****) until you are done. As soon as you return a response to the user, the stream closes and your information is not saved.

The easiest way to solve this problem is to return a response to the user after confirming that the information has been saved.

In the case of Firebase, something like this:

 function writeUserData(userId) { // Get a key for a new Post. var userKey = db.ref('users/').push().key; var reference = db.ref('users/' + userKey).set({ user: userId }); reference.then(() => { alexa.emit(':ask', "Works"); }, (err) => { alexa.emit(':ask', "Does not work"); }); 

}

I could not save anything until I began to do so.

Hope this helps.

+2
source

I came across this too, and the only way I figured out how to make it work is to defer the lambda callback function in the handler. Try this and let me know if that works.

 var firebase = require('firebase'); firebase.initializeApp({ databaseURL: 'https://myapp.firebaseio.com', serviceAccount: './myapp.json', }); exports.handler = (event, context, callback) => { var cart = firebase.database().ref('/cart'); console.log(cart); cart.push( { item: 'apples', quantity: '1', amount: '0' setTimeout(()=>{ callback(null, 'success'); },2000); }, function(error) { if (error) { console.log("Data could not be saved." + error); setTimeout(()=>{ callback(error); },2000); } else { console.log("Data saved successfully."); setTimeout(()=>{ callback(null, 'success'); },2000); } }); } 
0
source

Source: https://habr.com/ru/post/1258572/


All Articles