Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase cloud function admin

I tried to split all my function in many files but I've a problem with firebase-admin initialization. I've my first file like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const userHandler = require('./user')

and second file user.js

const functions = require('firebase-functions')
const admin = require('firebase-admin')
...
exports.update = (req, res) => {
   admin.auth().verifyIdToken(req.body).catch(error => {console.log(error)}
}

All in a single file it works perfectly, in 2 separate file give me this error:

ReferenceError: ISTANCE_NAME is not defined

I can't do a second initializeApp in a user.js because firebase throw an error:

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

How I can use the same istance of admin shared in 2 files? I've tried also to put the initializeApp function in another file and import it but not works, same error (ISTANCE_NAME is not defined)

like image 889
Stefano Avatar asked Nov 08 '22 12:11

Stefano


1 Answers

that's a good question.

So you're correct in saying that you can only call admin.initializeApp() once.

index.js

const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const userHandler = require('./user')

user.js

const admin = require('firebase-admin')

You do not need to initialize it again. The configuration is stored correctly after it's first initialized.

Alternatively, you can do messier things like a getAdmin() function.

The way I've done it in the past is have the functions defined and make separate files with handler functions, which look like

updateHandler(req, res, admin); // or the other
updateHander(whateverParamsToOtherFile);

Note

All your functions must be exported from the index.js file to be correctly deployed on Firebase. I'd recommend the index.js to store all the functions and it calls handlers from other files.

Through parameter passing, you can achieve the result you're after. But in the specific case of admin.initializeApp(), it'll work fine in other files if it's initialized in the index.js.

like image 106
Ishan Joshi Avatar answered Nov 15 '22 07:11

Ishan Joshi