mohamed nageh
mohamed nageh

Reputation: 743

I keep getting this error in sails for firebase

I have a sails and node app ,i am using firebase to push notification on that app The issue I keep getting is that

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

my code in app.js file

  sails = require('sails');
  rc = require('sails/accessible/rc');
    const admin = require('firebase-admin');
    const serviceAccount = require('./serviceAccountKey.json');
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "my url"
    });
    // Start server
  sails.lift(rc('sails'));

I have tried some solution for the file that depend on that service by using setTimeOut to delay calling a specific require file and this actually help me on some cases but I want a solution so that I don't have to do this work around

Upvotes: 0

Views: 113

Answers (1)

Mohammed Eldadah
Mohammed Eldadah

Reputation: 23

For initializing your firebase admin I prefer to add it to config/bootstrap.js file as global variable (without const or var), so you can access it in all over your application

Note sails runs bootstrap file once the app started, so you can write any piece of code you'd like to run in each time you start the project

example

admin = require('firebase-admin');
serviceAccount = require('./serviceAccountKey.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "my url"
});

you can also define firestore, auth, bucket, etc,,

auth = admin.auth();
bucket = admin.storage().bucket();

db = admin.firestore();
db.settings({ timestampsInSnapshots: true });

now in any of your controllers you can use firestore just by

await db.collection('user').doc('userId').set({})

Upvotes: 1

Related Questions