Deploying cloud functions to firebase successful in the CLI but none appear in the dashboard - firebase

I've been following the codelabs tutorial here to deploy my first functions to firebase. I've made it to step 8 of the tutorial ("Welcome new users").
The deploy looks successful when I run firebase deploy --only functions from within the functions subdirectory:
Marks-MacBook-Air-3:functions mf$ firebase deploy --only functions
=== Deploying to 'friendlychat-21221'...
i deploying functions Running command: npm --prefix "$RESOURCE_DIR"
run lint
functions# lint /Users/mf/Desktop/friendlychat-web/cloud-functions-start/functions
eslint .
✔ functions: Finished running predeploy script. i functions:
ensuring necessary APIs are enabled...
✔ functions: all necessary
APIs are enabled
i functions: preparing functions directory for
uploading...
✔ Deploy complete!
But looking at my firebase dashboard, it doesn't look like they deployed after all:
I'm not even sure where to begin troubleshooting, since the logs in the cloud functions tab is empty.
Has anyone encountered this before and/or have a good troubleshooting strategy?
Update 1:15 PM Friday 25 May, 2018: This is my index.js file in the functions subdirectory:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// TODO(DEVELOPER): Write the addWelcomeMessages Function here.
// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(user => {
console.log('A new user signed in for the first time.');
const fullName = user.displayName || 'Anonymous';
// Saves the new welcome message into the database
// which then displays it in the FriendlyChat clients.
return admin.database().ref('messages').push({
name: 'Firebase Bot',
photoUrl: '/images/firebase-logo.png', // Firebase logo
text: `${fullName} signed in for the first time! Welcome!`, // Using back-ticks.
}).then(() => {
console.log('Welcome message written to database.');
});
});
// TODO(DEVELOPER): Write the blurOffensiveImages Function here.
// TODO(DEVELOPER): Write the sendNotifications Function here.
Here are the contents of the functions subdirectory:

I ended up getting it to work after changing two things (and I'm not sure which one fixed this issue; perhaps both):
run npm install from inside the functions directory before you deploy the functions (which should be done in the parent directory).
Be aware that when you run firebase init and cause an overwrite of your index.js file, that file may just have a commented out 'helloWorld' function...

Try Firebase list to list all the project that you have in firebase under the signed in account and see if the project you are deploying to shows up. In the case where it doesn't show try this:
firebase logout && firebase login
firebase list
firebase use <alias_or_project_id>
firebase deploy --only functions or firebase deploy --only functions:<function_name>
Hope this helps!

Related

Retry on failure Firebase Function deploy failing using Github Action

I have a firebase function that is triggers on firestore doc OnCreate with failurePolicy set to true like so:
const webhookHandler = functions
.runWith({
failurePolicy: true,
memory: '512MB',
timeoutSeconds: 60,
}).firestore.document(`${COLLECTIONS.eventsQueue}/{event_queue_id}`)
.onCreate(async (snap, context) => {
//some code here...
})
Locally, using Firebase CLI i can deploy successfully, but requires I acknowledge that this function will retried on failure, do you still want to deploy? Yes/No.
once Yes is selected the function deploys successfully.
I'm using Github Actions to deploy the firebase functions automatically on PR merge. and Once i added the above function the github action deploy fails.
My assumption is that github action deploy is failing because the prompt.
My github deploy github action script does have --non-interactive and also tried with --force and it keeps failing.
Seems the --force does not enforce on this function deploy locally or in github deploy. Any suggestions to resolve this.
You can use the yes command included with most linux distros.
yes | firebase deploy ...
credit to #nVitus helped solve this.
the exact script that solves it:
yes | firebase deploy --only functions --force

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 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

Firebase-tools is not uploading newly created functions to Firebase

I am working on an Angular project and I am writing Firebase functions that I would like to deploy to Firebase. As I write more functions for Firebase and try to deploy them to Firebase using firebase deploy --only functions, only existing functions get deployed. More specifically, I have 16 functions that I would like to deploy to Firebase but only the same 12 get deployed.
So far, I have done the following to try to fix the problem:
I made sure that I am on the latest firebase-tools (6.7.0)
I have tried specifying the newly written functions I would like to deploy using firebase deploy --only functions:<NEW FUNCTION NAME HERE>
Remove all export functions from the functions/src/index.ts file and upload a blank index.ts. Even when using a blank index.ts file, the same functions still get deployed to Firebase.
I know there can be up to a 30-second delay when uploading functions to Firebase, so I have even waited for an entire night before trying to upload new functions.
I have started from complete scratch using firebase init to recreate the whole functions directory and it still keeps uploading the same functions.
I upgraded from the free Firebase plan to the Spark plan.
The following code is the main index.ts file which is located in functions/src/index.ts.
import * as functions from 'firebase-functions';
import { firestore } from 'firebase-admin';
import * as moment from 'moment';
import { request } from 'https';
// Local Functions Imports
import * as Permissions from './permissions';
import * as Groups from './groups';
import * as Shifts from './shifts';
import * as Roles from './roles';
import * as Session from './sessions';
import * as Users from './users';
import * as Slack from './slack';
import * as ScheduleChanges from './schedule-changes';
import * as Email from './email';
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/* -------- USER MANAGEMENT -------------- */
export const createUser = Users.createUser;
export const addUserToDefaultJoinGroups = Users.addUserToDefaultJoinGroups;
export const deleteUser = Users.deleteUser;
/* -------- SESSION MANAGEMENT -------------- */
export const addSessionID = Session.addSessionID;
/* -------- ROLE MANAGEMENT -------------- */
export const addRoleID = Roles.addRoleID;
export const removeAllShiftsAssociatedWithRole = Roles.removeAllShiftsAssociatedWithRole;
/* -------- SHIFT MANAGEMENT -------------- */
export const addShiftID = Shifts.addShiftID;
export const hourly_job = Shifts.hourly_job;
export const changeShiftStatsTest = Shifts.changeShiftStatsTest;
/* -------- GROUPS MANAGEMENT -------------- */
export const addGroupID = Groups.addGroupID;
export const addGroupIDNewTestFunction = Groups.addGroupIDNewTestFunction;
/* -------- PERMISSIONS MANAGEMENT -------------- */
export const addPermissionID = Permissions.addPermissionID;
/* -------- Emailing -------------- */
export const sendWelcomeEmailToNewUser = Email.sendWelcomeEmailToNewUser;
export const sendWelcomeEmailToNewUser2 = Email.sendWelcomeEmailToNewUser2;
/* -------- SLACK MESSAGING MANAGEMENT -------------- */
export const sendWelcomingMessage = Slack.sendWelcomingMessage;
/* -------- SCHEDULE CHANGES MANAGEMENT -------------- */
export const addScheduleChangeID = ScheduleChanges.addScheduleChangeID;
As seen in the code above, there are 16 functions that should be deployed to Firebase. However, only 12 get deployed. The following code snippet is from functions/src/groups/index.ts. In this file, the addGroupID is an existing function which continually gets deployed to Firebase. On the other hand, addGroupIDNewTestFunction is a new function that isn't getting deployed to Firebase even though they are in the same file and being referenced the same way.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
export const addGroupID = functions.firestore
.document("organizations/{organizationID}/groups/{groupID}")
.onCreate(async (snap, context) => {
console.log("Adding group id");
await admin.firestore()
.doc(`organizations/${context.params.organizationID}/groups/${context.params.groupID}`).update({
'groupID': context.params.groupID
})
})
export const addGroupIDNewTestFunction = functions.firestore
.document("organizations/{organizationID}/groups2/{groupID}")
.onCreate(async (snap, context) => {
console.log("Adding group id");
await admin.firestore()
.doc(`organizations/${context.params.organizationID}/groups/${context.params.groupID}`).update({
'groupID': context.params.groupID
})
})
As mentioned previously, I have specified 16 functions in the main index.ts file that should get deployed to Firebase functions. However, only the existing 12 functions are getting deployed. The following code snippet is the output firebase gives me when I run firebase deploy --only functions inside the Angular project.
firebase deploy --only functions
=== Deploying to 'university-scheduling'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions
> tslint --project tsconfig.json
no-unused-variable is deprecated. Since TypeScript 2.9. Please use the built-in compiler checks instead.
Could not find implementations for the following rules specified in the configuration:
use-input-property-decorator
use-output-property-decorator
use-host-property-decorator
Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.
If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/email/index.ts:2:13 - 'admin' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:2:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:3:13 - 'moment' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:4:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:2:13 - 'admin' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:6:7 - 'request' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:7:7 - 'options' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:3:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:43:11 - 'groups' is declared but itsvalue is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:65:11 - 'uid' is declared but its value is never read.
Running command: npm --prefix "$RESOURCE_DIR" run build
> functions# build /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions
> tsc
✔ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (106.24 KB) for uploading
✔ functions: functions folder uploaded successfully
⚠ appEngineLocation us-central1
i functions: updating Node.js 6 function createUser(us-central1)...
i functions: updating Node.js 6 function deleteUser(us-central1)...
i functions: updating Node.js 6 function addSessionID(us-central1)...
i functions: updating Node.js 6 function addRoleID(us-central1)...
i functions: updating Node.js 6 function removeAllShiftsAssociatedWithRole(us-central1)...
i functions: updating Node.js 6 function addShiftID(us-central1)...
i functions: updating Node.js 6 function hourly_job(us-central1)...
i functions: updating Node.js 6 function changeShiftStatsTest(us-central1)...
i functions: updating Node.js 6 function addGroupID(us-central1)...
i functions: updating Node.js 6 function addPermissionID(us-central1)...
i functions: updating Node.js 6 function sendWelcomingMessage(us-central1)...
i functions: updating Node.js 6 function addScheduleChangeID(us-central1)...
✔ scheduler: all necessary APIs are enabled
✔ functions[addPermissionID(us-central1)]: Successful update operation.
✔ functions[createUser(us-central1)]: Successful update operation.
✔ functions[addShiftID(us-central1)]: Successful update operation.
✔ functions[changeShiftStatsTest(us-central1)]: Successful update operation.
✔ functions[sendWelcomingMessage(us-central1)]: Successful update operation.
✔ functions[hourly_job(us-central1)]: Successful update operation.
✔ functions[addSessionID(us-central1)]: Successful update operation.
✔ functions[deleteUser(us-central1)]: Successful update operation.
✔ functions[addGroupID(us-central1)]: Successful update operation.
✔ functions[removeAllShiftsAssociatedWithRole(us-central1)]: Successful update operation.
✔ functions[addScheduleChangeID(us-central1)]: Successful update operation.
✔ functions[addRoleID(us-central1)]: Successful update operation.
✔ Deploy complete!
Please note that it can take up to 30 seconds for your updated functions to propagate.
You should check the directory which is compiled js files.
The default is functions/lib/.
If you import like ../../foo.ts anywhere at functions/src or functions/src/tests, etc then the compiled js file is functions/lib/{any}/foo.js.
The deploy target files are functions/lib/*.js only. So, functions/lib/{any}/foo.js is ignored.
You should change directory or files structure.
If the reason is test files then you should meke tsconfig.json for deploy and exclude them.
I wanted to give you guys an update on the solution to the problem I described above. In one of my index.ts files, I had the following require statement, var mailgun = require('mailgun-js'). Whenever I replaced this the require statement with import * as mailgun from 'mailgun-js', all the functions were deployed properly.
The most confusing part about this whole issue was that I only received success messages even when things weren't working properly. I do thank you guys for the speedy support and all of your suggestions!!
I had the exact same problem and the solution was Editing functions/src/index.ts instead of functions/lib/index.js
In my case it's index.ts because of I selected that option when initialized the project with "firebase init", your case depends on it, can be index.js too, but always on /src and not in /lib.
I think that the /lib folder if for the compiled file.
When deploying functions the compiler converts the src/.ts files into "lib/src/.js" files.
Somehow I had some files hanging around from previous deployments in the "lib/*js" space. Sure enough these files were getting deployed but the files containing the new function I had created were located in "lib/src/*js. No new changes were being passed up into cloud functions.
and so I went into package.json and changed
"main": "lib/index.js",
to read
"main": "lib/src/index.js",
And to cleanup I deleted all .js files from "lib/
I was back in business.

Firebase Function not giving Function URL

I am creating my first firebase function app and I was going/following through this tutorial/repo
So what I did was in my main file Index.js (inside functions folder)
const app = express();
const functions = require("firebase-functions");
const authRoutes = require("./src/routes/auth.js");
const meetupRoutes = require("./src/routes/meetup.js");
const eventbriteRoutes = require("./src/routes/eventbrite.js");
const nonMiddleWareRoutes = require("./src/routes/nonMiddleware.js");
app.use("/", nonMiddleWareRoutes);
app.use("/auth", authRoutes);
app.use("/meetup", meetupRoutes);
app.use("/eventbrite", eventbriteRoutes);
const api = functions.https.onRequest(app);
module.exports = {
api
};
now moving back to the root folder we have firebase.json which just contains this
{}
and .firebaserc
{
"projects": {
"default": "functions-firebase-2312"
}
}
Now, Whenever I do firebase deploy, it logs this in terminal
=== Deploying to 'functions-firebase-2312'...
i deploying functions
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (60.3 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 8 function api(us-central1)...
✔ functions[api(us-central1)]: Successful update operation.
✔ Deploy complete!
Please note that it can take up to 30 seconds for your updated functions to propagate.
Project Console: https://console.firebase.google.com/project/functions-firebase-2312/overview
but does not give me the url for the function.
Any idea what I could be doing wrong?
You will be given a URL the first time you deploy a function. After that, you can go to the Firebase console to see the URL in the Functions dashboard. They appear in rather small letters.

Resources