0

ラムダ関数を使用してfirebaseデータベースにデータを保存できません。それはタイムアウトします。私は5分までタイムアウトを設定しようとしましたが、それは理想的には実行する必要はありませんが、それでもタイムアウトします。AWS Lambda関数がfirebaseエントリを追加中にタイムアウトします

'use strict'; 

var firebase = require('firebase'); 

exports.handler = (event, context, callback) => { 

    console.log(context); 

    var params = JSON.stringify(event); 

    var config = { 
    apiKey: "SECRETAPIKEY", 
    authDomain: "myapplication.firebaseapp.com", 
    databaseURL: "https://myapplication.firebaseio.com", 
    storageBucket: "myapplication.appspot.com", 
    messagingSenderId: "102938102938123" 
    }; 

    if(firebase.apps.length === 0) { // <---Important!!! In lambda, it will cause double initialization. 
     firebase.initializeApp(config); 
    } 

    var db = firebase.database(); 

    var postData = { 
    username: "test", 
    email: "[email protected]" 
    }; 

    // Get a key for a new Post. 
    var newPostKey = firebase.database().ref().child('posts').push().key; 

    // Write the new post's data simultaneously in the posts list and the user's post list. 
    var updates = {}; 
    updates['/posts/' + newPostKey] = postData; 

    callback(null, {"Hello": firebase.database().ref().update(updates)}); // SUCCESS with message 
}; 

上記のコードは、データをファイヤーベースに保存しますが、タイムアウトします。

私がcontext.callbackWaitsForEmptyEventLoop = falseLinkで説明したように使用すると、タイムアウトにはなりませんが、データは保存されません。

この問題を解決する方法を教えてください。クラウドウォッチには有益な情報はありません。

さらにもう1つ、データを保存するためにfirebase用の残りのAPIを使用するとうまくいきます。

+0

はここに私の答えはhttps://stackoverflow.com/a/45266181/2073325 – gchao

答えて

2

問題はFirebaseが更新を行うことができます前に、コールバック関数

callback(null, {"Hello": firebase.database().ref().update(updates)}); // SUCCESS with message 

が呼び出されるということです。

代わりにあなたの現在のコールバックの、あなたはFirebase更新コールバックでコールバック関数を置く必要があります。

firebase.database().ref().update(updates, function (err) { 

    // your processing code here 

    callback(null, {<data to send back>}); 
}) 
+1

これがうまく機能しているお役に立てば幸いです。それは私が追加しなければならなかったことに加えて \t context.callbackWaitsForEmptyEventLoop = false;最初の文として – prashant

+0

これは私の問題のためにも多くの助けになりました!あなたは男だ! – SmiffyKmc

関連する問題