when performing testing, I have `Bucket name not specified or invalid` error after initialize the app in Cloud Function - firebase

I know there are a lot of similar thread discussing similar issue, but I still don't find any solution because maybe my case is slightly different.
so I have this error when performing testing using Mocha in Firebase emulator
Error: Bucket name not specified or invalid. Specify a valid bucket
name via the storageBucket option when initializing the app, or
specify the bucket name explicitly when calling the getBucket()
method.
import * as admin from "firebase-admin";
export const app = admin.initializeApp();
const storage = app.storage();
const defaultBucket = storage.bucket(); // it seem error is in here
I am using cloud function, so I assume initializeApp() with empty argument is fine according to the documentation in here. but I have that error when run the test in emulator
my mocha test script is like this
export FIRESTORE_EMULATOR_HOST="localhost:8080" && export FIREBASE_AUTH_EMULATOR_HOST="localhost:9099" && mocha -r ts-node/register src/tests/cloud_function_tests --recursive --extension .test.ts --timeout 60000 --exit
and it seems that error only appears when I perform the testing, if I run those code above using emulator (without mocha testing), that error will never occured
I am using
Node 14
firebase-admin: 9.6.0
firebase-functions: 3.13.2
firebase tools: 9.10.0

Related

How can I deploy a single Firebase Cloud Function in a group and a region?

I have created a group of Firebase Cloud Functions (v2) that are deployed in a region (europe-west1).
#index.ts
import * as apiV2 from './v2';
export const v2 = apiV2;
#v2.ts
export const addTextMessage = functions.region('europe-west1').onCall(
...
)
I want only to deploy the addTextMessage function.
I tried:
firebase deploy --only functions:v2-addTextMessage
# or
firebase deploy --only "functions:v2-addTextMessage(europe-west1)"
However the function is not deployed:
✔ functions: functions folder uploaded successfully
i functions: current functions in project: v2-addTextMessage(europe-west1)
⚠ functions: the following filters were specified but do not match any functions in the project: v2-addTextMessage(europe-west1)
What command should I use?
Try to replace the "-" by ".".
You should use :
firebase deploy --only functions:groupName.functionName
In your case :
firebase deploy --only functions:v2.addTextMessage
It's true that the CLI terminal log is misleading because if you've exceeded your deployment quota and the CLI detects that the name of your function is for instance v2-addTextMessage(europe-west-1), it will print a message suggesting you to use the command firebase deploy --only functions:v2-addTextMessage to deploy this function only, which doesn't work.
See the full Firebase CLI documentation here
You are using the correct command, however, you have not exported the addTextMessage function to your index.ts file, without that the deployment cannot find the funtion to deploy. You can export it by adding the following code to your index.ts:
export const v2-addTextMessage = apiV2.addTextMessage
Also, you cannot use the functions parameter and the function name as a String. So your command on this case would have to be:
firebase deploy --only functions:v2-addTextMessage
For Specifying region on deployment, as you already added to your code on the edited version of the question, you cannot do it on the FirebaseCLI command, thanks to #Doug Stevenson for pointing that out on the comment section.
Ideally, as you can see on this video, you would have to specify that in your cloud function code, before deployment by adding the following:
exports.v2-addTextMessage = functions
.region('europe-west1')
.storage.object().onFinalize((object) => { });

Deploying firebase cloud function in typescript

I'm trying to deploy the very first cloud function.
It works perfectly fine, but when I try to deploy it in terminal, it sets out warning saying that "functions is declared but it's value is never read".
Is this some common starting mistake, as I am new to this subject? Thank you.
I tried both imports , deploy erros remains same
// const functions = require('firebase-functions');
import * as functions from 'firebase-functions'
Errors message
index.ts file code here
Your code doesn't declare any Cloud Functions yet, so eslint warns you that you're importing functions but not using it.
The message will disappear when you declare a Cloud Function in your index.js/index.ts. For example, the documentation on getting started contains this example:
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
return res.redirect(303, snapshot.ref.toString());
});
});
As you can see, this code uses functions in its first line. So if you add this (or any other Cloud Functions declaration) to your code, you're using functions and eslint will no longer warn you about it not being used.
The error will disappear when you finally use "functions" in a cloud function.
nevermind, you are better off using
const functions = require('firebase-functions');
when importing firebase-functions in your index.js
========
EDIT : ======
Make sure that you have correctly installed those dependencies, by running those npm commands in the right folder:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
Probably solved, but for me I was expecting ~/functions/index.ts to be the file building but the firebase cli added ~/functions/src/index.ts and THAT was the file.

Why do the firebase cli give a TypeError

I already have some firebase cloud functions that runs fine, and now I try to add SendGrid functionality to one of the functions as described in https://youtu.be/JVy0JpCOuNI. The firebase CLI won't run my code because it says it has a TypeError
The code is written in Typescript and the transpiler doesn't give any error. I am using the latest versions of the CLI and the SDK.
admin.initializeApp();
const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
const sgMail = require(‘#sendgrid/mail’);
sgMail.setApiKey(SENDGRID_API_KEY);
I have checked that the firebase config contains the sendgrid key:
$ firebase functions:config:get
{
"sendgrid": {
"key": "MY_SEND_GRID_KEY"
}
}
I get this output when I try to deploy --only functions:
functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory. :warning: functions: Error from emulator. Error occurred while parsing your function triggers.
TypeError: Cannot read property ‘key’ of undefined
It is this line that has the error:
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
What can I change so I don't get this error?
The variables that you set using the CLI via firebase functions:config:get don't end up in process.env.FIREBASE_CONFIG. They end up in functions.config().
import * as functions from 'firebase-functions'
const key = functions.config().sendgrid.key
FIREBASE_CONFIG just determines how the admin SDK should be initialized with no parameters passed to admin.initializeApp().
Please read the documentation for more information.

Firebase CLI: the following filters were specified but do not match any functions in the project

I use Firebase Cloud Functions in my project, and I have a plenty of them so when I run the regular firebase deploy I exceed the quota, so one option is to deploy only the function that was modified by using firebase deploy --only functions:function1 as mentioned in this web page. This method works only with functions that start with: exports.funcName but when I try to use it with a function like this:
function doesNotStartWithExports() {
// Does something.
}
It doesn't work. I use firebase deploy --only functions:doesNotStartWithExports but I get this output:
⚠ functions: the following filters were specified but do not match any functions in the project: doesNotStartWithExports
The Question: How to deploy Firebase functions that does not start with exports?
I faced a very similar error while trying to delete some deprecated functions:
firebase functions:delete mymodule-helloWorld --region us-central1
Output:
Error: The specified filters do not match any existing functions in project my-firebase-project.
Turns out that if I replace the '-' in namespaced/grouped (module) functions with '.', the error goes away. Weird.
firebase functions:delete mymodule.helloWorld --region us-central1
Output:
? You are about to delete the following Cloud Functions:
mymodule-helloWorld(us-central1)
Are you sure? Yes
i functions: deleting function mymodule-helloWorld(us-central1)...
✔ functions[mymodule-helloWorld(us-central1)]: Successful delete operation.
The solution is adapted from this github thread
I actually found the solution, and it's by deploying one of the function that starts with exports and uses the function that doesn't start with exports, for example:
function doesNotStartWithExports() {
// I want to deploy only this function but I can't
}
exports.anotherFunction = functions.https.onRequest((request, response) => {
// This functions uses the one that I want to deploy.
doesNotStartWithExports()
})
To update doesNotStartWithExports I use this command:
firebase deploy --only functions:anotherFunction.
I also found that if you have a regular function exported somewhere with the same name as the Firestore function you will get this error:
export myFunction() {
// do somethig here
}
exports.myFunction = functions.https.onCall((data, context) => {
// function
})
renaming either of them to a unique name will solve the issue.
This works:
But this does not work (extra lines preceding function)

How to test Cloud Functions with Firestore?

I'm trying to test cloud functions function.
But, in testing(npm run test) I got this error.
Why did I get this error? how to fix it?
TypeError: Path must be a string. Received undefined
at assertPath (path.js:7:11)
at Object.join (path.js:1218:7)
at database (node_modules/firebase-functions/lib/providers/firestore.js:36:45)
at Object.document (node_modules/firebase-functions/lib/providers/firestore.js:44:12)
at Object.<anonymous> (src/index.ts:6:21)
at Object.loadTypeScript (node_modules/espower-typescript/index.js:23:17)
at require (internal/module.js:20:19)
at Context.before (test/initialize-pair.ts:19:23)
This is my index.ts.
It is working as a real cloud functions function.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
export const aFunc = functions.firestore.document('/users/{uid}').onUpdate(() => { console.log('called')});
thanks
It looks like you're running npm run test without understanding what your particular test script is supposed to actually do. There isn't an npm script provided by the Firebase CLI for testing functions automatically.
If you want to do unit testing of your functions, read the advice in the documentation here.
If you want to use the local emulator to manually simulate events to your function, read the documentation here.

Resources