Deploying firebase cloud function in typescript - firebase

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.

Related

firebase emulator cannot refresh dynamic import Functions

Background
I use dynamic import for Firebase Functions to reduce cold start time based on this post: https://medium.com/firebase-developers/organize-cloud-functions-for-max-cold-start-performance-and-readability-with-typescript-and-9261ee8450f0
index.ts under functions folder has only one line
exports.consent = require("./myFunctionGroup");
index.ts under functions/myFunctionGroup
import * as functions from "firebase-functions";
export const helloWorld = functions.https.onCall(async (data, context) => {
return await (await import("./helloWorld")).default(data, context);
});
Content of helloWorld.ts under functions/myFunctionGroup
import * as functions from "firebase-functions";
export default async (
data: {},
context: functions.https.CallableContext
) => {
return "hello";
}
There is no problem when the emulator first launched as it return "hello" correctly. However, when I change to return to 'return "world";', even though the emulator seems to be aware of the change and prints ✔ functions: Loaded functions definitions from source:..., it still return the old value of hello. Maybe it has some kind of cache for the original imported module. When I restart process again, then it will then print "world".
Question:
Is there any setting to make the emulator aware my change and force to clear the Functions cache? I tried to use debugger and it realized my code has changed so that I can step through the new code. It's just not working for the Firebase emulator.
It was expected behavior,any changes/modification in the code after running the emulator will not be reflected. You can also refer to this documentation:
Note:Code changes you make during an active session are automatically
reloaded by the emulator. If your code needs to be transpiled
(TypeScript, React) make sure to do so before running the emulator.
You can run your transpiler in watch mode with commands like tsc -w to
transpile and reload code automatically as you save.
You can follow the below steps,As mentioned in this stackoverflow thread
After every change to the ts files, run "npm run build" to compile the code again.
Change "build": "tsc" to "build": "tsc -w" in package.json if you want to auto-compile after every change.
There is a bug raised for this at github which is still open you can track the updates there.

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

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

Deploying Function Error on Cloud Function with error code 13 and Message "INTERNAL"

I'm deploying a Firestore trigger onCreate for my App, but everytime I want to deploy, it always Error
the console always showing Code 13 and Message "INTERNAL"
this is what comes up on Console
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{"code":13,"message":"INTERNAL"},
"authenticationInfo":{"principalEmail":"[My_EMAIL]"},
"requestMetadata":{"requestAttributes":{},"destinationAttributes":{}},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/etalase/locations/us-central1/functions/onNewMessage"}
this is my code on index.js
exports.onNewMessage = functions.firestore
.document('/messages/{groupChatId}/{groupChatId}/{messageFeedItem}')
.onCreate(async (snapshot, context) => {
const doc = snapshot.data();
console.log('------Message Created-----');
console.log(doc);
const idForm = doc.userID;
const idTo = doc.sellerID;
console.log('Message from : ', idForm);
console.log('Message to : ', idTo);
});
I expect this will deploy and every time a new message created on {messageFeedItem}, it will trigger the console, but even I can't deploy it
Thank you
So right now I can deploy the function by changing the directory
'messages/{groupChatId}/{groupChatId}/{messageFeedItem}'
into
'messages/{groupChatId}/{groupChatId2}/{messageFeedItem}'
my speculation is you can't have same name to the wildcard
You have to import firebase functions
import functions = require('firebase-functions');
or
const functions = require('firebase-functions');
If you did, then check your package.json
For anyone who got this far and still does not have a solution - here is what was wrong in my case
exports.fnName = functions.firestore
.document('Collection/{collId}/SubCollection/{subCollId')
.onUpdate((change, context) => {
...
});
Note the missing '} at the end of the document reference.
This caused the deploy to fail with the following on the client
Failed to configure trigger provider
And with the following in the function logs
"status":{
"code":13,
"message":"INTERNAL"
},
Set up Node.js and the Firebase CLI
In many cases, new features and bug fixes are available only with the
latest version of the Firebase CLI and the firebase-functions SDK.
It's a good practice to frequently update both the Firebase CLI and
the SDK with these commands inside the functions folder of your
Firebase project:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
my issue is because I use - character in my wild card
'chat/{abc-efg}'
I change - to _ and it works

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.

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