Firebase functions being called twice while running on Google App Engine

我们两清 提交于 2019-12-07 08:26:26

After testing for a while I figured it out. This issue is caused by running Firebase-Admin on Google App Engine. Essentially, every underlying VM that your AppEngine sits on is running its own instance of Firebase-Admin. AppEngine, by default, maintains at least two VMs for every service. So in testing (under minimal load) the firebase functions are being called once by each of the two VM instances.

Apparently, there is no documentation on this issue but there is a library from Google/Firebase that does solve this problem. It is called Firebase-Queue and it can be found on NPM. I solved my issue with this code:

// [START notificationsservice app]
'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var rp = require('request-promise');
var admin = require('firebase-admin');
var Queue = require('firebase-queue');

var app = express();

admin.initializeApp({
    credential: admin.credential.cert("serviceAccountCredentials.json"),
    databaseURL: "https://<YOUR PROJECT ID HERE>.firebaseio.com/"
});

var db = admin.database();
var notifications = db.ref('/notifications');

var API_KEY = "<YOUR API KEY HERE>"

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

var queue = new Queue(notifications, function(data, progress, resolve, reject) {

    var incomingNotification = data;
    var userID = incomingNotification.userID;
    var username = incomingNotification.username;

    rp({
        url: 'https://fcm.googleapis.com/fcm/send',
        method: 'POST',
        headers: {
            'Content-Type' :'application/json',
            'Authorization': 'key='+API_KEY
        },
        body: JSON.stringify({
            "to" : "/topics/follower-"+userID,
            "priority": "high",
            "notification" : {
                "body" : username+" you have a notification",
            },
            "data" : {
                "type" : "follower"
            }
        })
    }).then(function(body) {
        progress(100);
        console.log("Notification sent."+body);
        resolve();
    }).catch(function(error) {
        progress(21);
        console.log(error);
        reject(); 
    });

  setTimeout(function() {
    resolve();
  }, 1000);
});

// Start the server
var server = app.listen(process.env.PORT || '8080', function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END app]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!