0

私はFirebase Cloud Functions referenceguides、およびsample codeを読んで、なぜ私の機能が2回トリガされたのかを判断しましたが、私はまた、回避策としてFirebase-Queueを試しましたが、最新のアップデートでは、クラウド機能が行く方法が示唆されています。Firebase HTTPSクラウド機能が2回トリガされました

つまり、request-promiseを使用して外部APIから通知を取得しています。これらの通知を自分のデータベースに登録済みのものと照合し、新しい通知があると確認してデータベースに通知します。対応する開催地は、新しい通知への参照で更新されます。コードは次のとおりです。

'use strict'; 

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
const request = require('request'); 
const rp = require('request-promise'); 

admin.initializeApp(functions.config().firebase); 

const db = admin.database(); 
const venues = db.ref("/venues/"); 

exports.getNotices = functions.https.onRequest((req, res) => { 
    var options = { 
     uri: 'https://xxxxx.xxxxx', 
     qs: { 
      format: 'json', 
      type: 'venue', 
      ... 
     }, 
     json: true 
    }; 
    rp(options).then(data => { 
      processNotices(data); 
      console.log(`venues received: ${data.length}`); 
      res.status(200).send('OK'); 
     }) 
     .catch(error => { 
      console.log(`Caught Error: ${error}`); 
      res.status(`${error.statusCode}`).send(`Error: ${error.statusCode}`); 
    }); 
}); 

function processNotices(data) { 
    venues.once("value").then(snapshot => { 
     snapshot.forEach(childSnapshot => { 
      var existingKey = childSnapshot.val().key; 
      for (var i = 0; i < data.length; i++) { 
       var notice = data[i]; 
       var noticeKey = notice.key; 
       if (noticeKey !== existingKey) { 
        console.log(`New notice identified: ${noticeKey}`) 
        postNotice(notice); 
       } 
      } 
      return true; 
     }); 
    }); 
} 

function postNotice(notice) { 
    var ref = venues.push(); 
    var key = ref.key; 
    var loc = notice.location; 
    return ref.set(notice).then(() => { 
     console.log('notice posted...'); 
     updateVenue(key, loc); 
    }); 
} 

function updateVenue(key, location) { 
    var updates = {}; 
    updates[key] = "true"; 
    var venueNoticesRef = db.ref("/venues/" + location + "/notices/"); 
    return venueNoticesRef.update(updates).then(() => { 
     console.log(`${location} successfully updated with ${key}`); 
    }); 
} 

ダブルトリガを修正する方法についてのご意見は、大変ありがたく思います。前もって感謝します!

+0

これを一度だけ実行するようにどのように呼び出すのですか?ログには何が表示されますか? –

+0

processNotices()で完了するのを待たずに、非同期データベースの作業を行っていることにも注意してください。クライアントに応答を送信する前に、データベース作業が完全に完了したことを呼び出し元が知ることができるように、約束を返すべきです。 –

+0

プロンプト@DougStevensonに感謝します。私は解決策を見つけました(詳細は後述)。 – donovki

答えて

0

問題が解決されました - Firebaseコンソールログ(重複エントリ)からの誤った情報と入れ子になったforループが間違った順序で結合されていると、見かけのダブルトリガが発生しました。

関連する問題