Firebase-tools is not uploading newly created functions to Firebase - 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.

Related

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

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.

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.

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

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!

Resources