Question:
I have a database in Firebase to which I’m trying to write some data from within my Alexa Skill. The Node.js code for that skill sits inside an AWS Lambda function and when that code is run I want to push some data to Firebase.
I’ve tested the code that connects to and pushes to Firebase outside of Lambda and it works exactly as expected. Below is that code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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."); } }); |
This same code doesn’t push anything to the database instance when executed from within the Lambda function. I read online that Lambda timeout limit could be a reason for this, so I increased the timeout limit to a minute, and it still doesn’t run as expected. I’ve also tried using the Firebase REST API instead of their Node.js SDK and that didn’t work either. What is the correct way to push data to Firebase from within AWS Lambda?
Answer:
I think I know why this happens, I had a similar issue and this is what I’ve done.
If you want to write some date into your database you need to make sure that you don’t call this.emit(*****) until you are done. As soon as you return the response to the user the Thread gets closed and your information doesn’t get saved.
The easiest way to solve this problem is to return the response to the user once you get confirmation that the information has been saved.
In case of Firebase something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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 couldn’t get anything saved until I started doing it like this.
Hope it helps.