Reputation: 506
I'm following the instructions on https://firebase.google.com/docs/functions/organize-functions to reorganize my cloud functions.
But I'm struggling to reuse some of the global const defined in the index.js file.
// index.js
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp()
const db = admin.firestore()
db.settings({ ignoreUndefinedProperties: true })
exports.choice = require('./choice')
...
// choice.js
const functions = require('firebase-functions')
exports.redirection = functions
.region('europe-west1')
.https.onRequest(async (req, res) => {
try {
const doc = await db.doc(`stbk${req.params[0]}`).get()
...
Got the following error: > ReferenceError: db is not defined
Any help would be greatly appreciated !
UPDATE
I've done the following:
// global.js
const admin = require('firebase-admin')
admin.initializeApp()
const db = admin.firestore()
db.settings({ ignoreUndefinedProperties: true })
module.exports = { admin, db }
// choice.js
const functions = require('firebase-functions')
const global = require('./global')
exports.redirection = functions
.region('europe-west1')
.https.onRequest(async (req, res) => {
try {
const doc = await global.db.doc(`stbk${req.params[0]}`).get()
Is it a valid solution?
Upvotes: 0
Views: 48
Reputation: 2487
You are getting the error because you are not initializing the Firestore database correctly. You can use the following code:
Index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firestore);
const firestoreDB = admin.firestore()
exports.choice = require('./choice')
module.exports = { db }
Choice.js
const functions = require('firebase-functions')
const global = require('./index')
exports.redirection = functions
.region('europe-west1')
.https.onRequest(async (req, res) => {
try {
const doc = await global.doc(`stbk${req.params[0]}`).get()
I think only the index.js and choice.js are sufficient. Why do you want to create an another .js called global? If you want to separate as mentioned above in global.js, then your code seems valid to me.
Let me know if you have any other questions.
Upvotes: 1
Reputation: 456
This is because db is not declared inside choice.js. You can either declare db as a global variable inside index.js or declare it in choice.js too.
Upvotes: 0