2

I have a Firebase Functions with Express app and I would like to use the Firestore instance on multiple controllers. So I created a simple service:

./services/firebase.serivce.ts

  admin.initializeApp(functions.config().firebase);
  const firestore = admin.firestore();
  export const db = firestore;

Then in my controller

./controllers/test.ts

import { db } from './../services/firebase.service';
...

const collection = db.collection('contacts');
const router = express.Router();

router.post('/', (req, res) => {
...

and the app.js

 import { TestController } from './controllers/test'
 ...

  app.use('/contact', TestController);
  export const api = functions.https.onRequest(app);

But Im getting the error:

The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.

And if I try to initializeApp() in all my controllers, I get a message saying that the app already exists.

What can I do to share the same instance for multiple files?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
gog
  • 11,788
  • 23
  • 67
  • 129
  • Try to change it to `const app = admin.initializeApp(functions.config().firebase); const firestore = app.firestore(); export const db = firestore;` Does it work? – libik May 28 '18 at 14:40
  • 1
    If you're trying to do this for performance reasons, you should know that `admin.firestore()` is not at all expensive to call more than once. It returns the same thing every time. – Doug Stevenson May 28 '18 at 15:18
  • @DougStevenson I tried your solution, I´ve called the initalizedApp() on the main index.ts, and the in my controller I tried to call admin.firebase(), but I get a error saying that `The default Firebase app does not exist` – gog May 28 '18 at 22:12

0 Answers0