8

Using the code here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js I get the "app already exists" error when deploying to Firebase. I have only changed the refs to work with my Firebase RTD.

It's easily fixed:

!admin.apps.length ? admin.initializeApp() : admin.app();

My question is, why does this happen? The function calls initializeApp() only once. Is it because app has been initialized already in my other functions?

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Keeps track of the length of the 'likes' child list in a separate property.
exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(
    async (change) => {
      const collectionRef = change.after.ref.parent;
      const countRef = collectionRef.parent.child('likes_count');

      let increment;
      if (change.after.exists() && !change.before.exists()) {
        increment = 1;
      } else if (!change.after.exists() && change.before.exists()) {
        increment = -1;
      } else {
        return null;
      }

      // Return the promise from countRef.transaction() so our function
      // waits for this async event to complete before it exits.
      await countRef.transaction((current) => {
        return (current || 0) + increment;
      });
      console.log('Counter updated.');
      return null;
    });

// If the number of likes gets deleted, recount the number of likes
exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onDelete(async (snap) => {
  const counterRef = snap.ref;
  const collectionRef = counterRef.parent.child('likes');

  // Return the promise from counterRef.set() so our function
  // waits for this async event to complete before it exits.
  const messagesData = await collectionRef.once('value');
  return await counterRef.set(messagesData.numChildren());
});

The error also says, "This means you called initializeApp() more than once without providing an app name as the second argument."

I'm not so sure about that...

Ken
  • 212
  • 3
  • 13
  • Can you share the entire content of your Cloud Functions file (i.e. the `index.js` or `index.ts` file)? – Renaud Tarnec Mar 01 '20 at 14:54
  • @RenaudTarnec okay, edited – Ken Mar 01 '20 at 15:03
  • Hmmm.... At first sight you correctly initialize the admin app instance. Difficult to say much... What if you try with a brand new Firebase project? – Renaud Tarnec Mar 01 '20 at 15:11
  • @RenaudTarnec I might do that. I need a clean friendlypix instance that works in Europe... see https://github.com/firebase/friendlypix-web/issues/90 – Ken Mar 03 '20 at 12:20

1 Answers1

1

I using:

try
{
   firebaseAdmin.initializeApp()
}
catch(err){
   firebaseAdmin.app()
}