I am setting up a Firebase project with functions organised in separate files. I am trying this out with 2nd gen functions.
Looking at the documentation, it seems like it has not been updated for 2nd gen as the example code functions are 1st gen: https://firebase.google.com/docs/functions/organize-functions?gen=2nd#write_functions_in_multiple_files
Even so, everything is working fine using this simple setup:
index.ts:
import { initializeApp } from 'firebase-admin/app'
import addAmessage from './api/addAmessage'
import app from './onCall/app'
initializeApp()
exports.addAmessage = addAmessage
exports.app = app
And in the addAmessage.ts file I use the Firebase example function only adding the setGlobalOptions:
api/addAmessage.ts:
import { onRequest } from 'firebase-functions/v2/https'
import { getFirestore } from 'firebase-admin/firestore'
import { setGlobalOptions } from 'firebase-functions/v2'
setGlobalOptions({ region: 'europe-west3' })
// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
const addAmessage = onRequest(async (req, res) => {
// Grab the text parameter.
const message = req.query.text
if (message !== undefined) {
// Push the new message into Firestore using the Firebase Admin SDK.
const writeResult = await getFirestore()
.collection('messages')
.add({ message })
// Send back a message that we've successfully written the message
res.json({ result: `Message with ID: ${ writeResult.id } added.` })
}
})
export default addAmessage
With just one Function this works fine, but since I set use the setGlobalOptions in my other functions files also I get a warning in the emulator console:
"Calling setGlobalOptions twice leads to undefined behavior"
I originally put the setGlobalOptions method in my index.ts file but then it was ignored.
So, I would love to only have to setGlobalOptions once, but how is it done correctly with multiple files?
I had a similar issue and incase anyone is still struggling with this, you can pass an options object to the callable function. One of the options is region
, which you can set as required.
Here is the code that should work :
import { onRequest } from 'firebase-functions/v2/https'
import { getFirestore } from 'firebase-admin/firestore'
// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
const addAmessage = onRequest({region: 'europe-west3'}, async (req, res) =>
{
// Grab the text parameter.
const message = req.query.text
if (message !== undefined) {
// Push the new message into Firestore using the Firebase Admin SDK.
const writeResult = await getFirestore()
.collection('messages')
.add({ message })
// Send back a message that we've successfully written the message
res.json({ result: `Message with ID: ${ writeResult.id } added.` })
}
})
export default addAmessage