Problem
I have a callable cloud function set up which writes to Firestore using the Admin SDK (node.js):
const admin = require('firebase-admin');
const functions = require("firebase-functions");
exports.myFunction = functions.https.onCall(async (data, context) => {
await admin.firestore().doc("/test").create({
timestamp: admin.firestore.FieldValue.serverTimestamp()
});
})
Testing this using the emulators. Also my packages are:
"firebase-admin": "^11.2.1",
"firebase-functions": "^4.0.2",
"firebase-tools": "11.16.0"
I am getting this error in my emulator logs:
TypeError: Cannot read properties of undefined (reading 'serverTimestamp')
I recently updated the admin SDK and the firebase-tools to the versions above, then the problem started occurring. I tried reinstalling firebase-tools and the admin SDK without luck.
Anyone have an idea of what I could try?
Found the API reference here. Instead of timestamp: admin.firestore.FieldValue.serverTimestamp() it should be timestamp: Firestore.FieldValue.serverTimestamp()
Also import: const { Firestore } = require("firebase-admin/firestore");
Related
app.resolve(token) throws UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getInstanceByContextId' of undefined
Current behavior
bootstrap function cannot resolve this transient provider:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// fails on versions below 8.0.0 !!!
const logger = await app.resolve<AbstractLoggerService>(LOGGER_TOKEN);
logger.setContext('bootstrap');
app.useLogger(logger);
await app.listen(3000);
}
Expected behavior
NestJS should resolve Logger provider and launch application without any errors.
Solution:
Upgrade nestjs/common and nestjs/core to 8.0.0 or above
I have a simple cloud function running on the functions emulator:
exports.helloFirebase = functions.https.onCall((data, context) => {
return "Hello"
})
When I call it from my firebase app, as follows...
export default {
helloFirebase: httpsCallable(fucntions, "helloFirebase")
}
then...
functionsObj.helloFirebase()
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log("ERROR IN FUNCTIONS")
console.log(error.message)
})
I get an error in my cloud functions console:
! functions: TypeError: Cannot read property 'data' of undefined
at processBackground (C:\Users\admin\AppData\Roaming\npm\node_modules\firebase-
tools\lib\emulator\functionsEmulatorRuntime.js:550:24)
at invokeTrigger (C:\Users\admin\AppData\Roaming\npm\node_modules\firebase-
tools\lib\emulator\functionsEmulatorRuntime.js:640:19)
at handleMessage (C:\Users\admin\AppData\Roaming\npm\node_modules\firebase-
tools\lib\emulator\functionsEmulatorRuntime.js:742:15)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
! Your function was killed because it raised an unhandled error.
I've tried everything to solve this issue and it's still not working. Is this a bug in the firebase admin SDK?
This was an issue with version 10.3.1 of firebase tools.
Here's the GitHub issue.
You can fix this quickly by running:
npm update -g firebase-tools
I have a Firebase Function that deletes a user's collection in a Firestore database when their account is deleted.
const firebase_tools = require("firebase-tools");
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.deleteUser = functions.auth.user().onDelete((user) => {
return firebase_tools.firestore
.delete(`users/${user.uid}`, {
project: process.env.GCLOUD_PROJECT,
token: functions.config().fb.token,
recursive: true,
yes: true
}).catch((error) => {
console.log(error);
throw new functions.https.HttpsError(
"unknown",
"Error deleting user's data"
);
});
});
Whenever a user is deleted and the function is executed, I get the following error in the Functions logs.
FirebaseError: Missing required options (force) while running in non-interactive mode
at prompt (/workspace/node_modules/firebase-tools/lib/prompt.js:16:15)
at promptOnce (/workspace/node_modules/firebase-tools/lib/prompt.js:29:11)
at Command.actionFn (/workspace/node_modules/firebase-tools/lib/commands/firestore-delete.js:69:51)
at Object.delete (/workspace/node_modules/firebase-tools/lib/command.js:190:25)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The only information I could find related to this is regarding deploying/deleting functions to Firebase and there's not much documentation for firebase-tools that I could find.
Add force: true to the JSON passed to firebase-tools. Worked for me with version 10.1.4
{
project: process.env.GCLOUD_PROJECT,
token: functions.config().fb.token,
recursive: true,
yes: true,
force: true // add this
}
I've reproduced the error that you have encountered.
This error occurs on the latest "firebase-tools": "^10.1.3".
Based on the Delete data with a Callable Cloud Function, the documentation have sample code that still uses "firebase-tools": "9.18.0".
You could downgrade your firebase-tools by modifying the package.json. E.g. below:
"dependencies": {
"firebase": "^9.6.5",
"firebase-admin": "^9.12.0",
"firebase-functions": "^3.16.0",
"firebase-tools": "9.18.0"
}
After downgrading, I'm able to delete the specified document successfully.
You could also use what's #Renaud Tarnec answered by using Admin SDK.
E.g. below:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
db = admin.firestore();
exports.deleteUser = functions.auth.user().onDelete((user) => {
db.collection("users").doc(user.uid).delete()
.then(function(user) {
console.log("Successfully Deleted User:", user.uid)
})
.catch((error) => {
console.log(error);
throw new functions.https.HttpsError(
"unknown",
"Error deleting user's data"
);
});
});
I am just starting up with firebase.
i am not sure ins and out of the firebase and based on my vaguely understanding, I have configured my app this way.
In the main Index.js file, I am requiring
const path = require('path')
const firebaseConfig = require("./src/config/firebaseConfig.js")
const firebaseDb = require("./src/helperFunctions/firebase_db.js")
Here, firebaseConfig is the place where I am configuring my firebase
const firebaseConfigJSON = require("./functions-config.json")
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert(firebaseConfigJSON),
databaseURL: "https://functions-firebase-43a59.firebaseio.com"
})
const db = admin.firestore()
db.settings({ timestampsInSnapshots: true });
module.exports = {
db
}
and then using this imported Db in firebaseDb
//All the operations at firebase store would be done from here
const firebaseDb = require("./../config/firebaseConfig.js")
firebaseDb.db.collection('users').add({
name: "Rohit Bhatia",
age: "24"
})
.then((response) => {
console.log("this is response", response)
})
.catch((err) => {
console.log("This is error in firebase", err)
})
Since most of the code is singleton here, I was expecting everything to go smoothly until I received following error
This is error in firebase TypeError: Path must be a string. Received
undefined
at assertPath (path.js:28:11)
at Object.join (path.js:1236:7)
at getPath (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:6:41)
at globs.concat.map.x (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:47:59)
at Array.map ()
at module.exports.sync (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:47:33)
at globDirs (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:58:9)
at getPattern (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:61:64)
at globTasks.reduce (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:107:19)
at Array.reduce ()
Can someone please help me in figuring out what could I be doing wrong? or perhaps did I actually got the firebase?
My initial goal was to create a collection in my firebase via my express app before putting data from api routes.
Try running:
npm install firebase-admin#6.4.0
Also you can do:
npm install
npm run build (inside functions folder.)
Then firebase deploy.
Fixed it for me.
We were able to revert the dir-glob to 2.0.0 by adding:
"dir-glob": "2.0.0",
"globby": "8.0.0",
In the package.json dependencies.
You can do this with:
npm install dir-glob#2.0.0 --save
npm install globby#8.0.0 --save
We then deleted the node_modules and run: npm install and deployed to Firebase
Future googler's
Make sure in your firebase.json file you have the correct source path:
{
"functions": {
"predeploy": "npm run build",
"source": "."
}
}
I am trying to do a simple hello world firebase function with my mobile app, I want to log the user ID so I can see that the function does work.
This is my current javascript code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((event) => {
console.log('Testing stuff', event.params.user_id);
return;
});
It does trigger when new data is written to specific databasetable but this error shows up:
TypeError: Cannot read property 'user_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:8:44)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
The notification database looks like this:
You need to install the latest firebase-functions and firebase-admin:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
to be able to use the new API, check here for more info:
https://firebase.google.com/docs/functions/get-started#set_up_and_initialize
Change this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((event) => {
console.log('Testing stuff', event.params.user_id);
into this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((change, context) => {
console.log('Testing stuff', context.params.user_id);
For onWrite and onUpdate events, the data parameter has before and after fields. Each of these is a DataSnapshot with the same methods available in admin.database.DataSnapshot
params
An object containing the values of the wildcards in the path parameter provided to the ref() method for a Realtime Database trigger.
more info here:
Cloud functions v1.0 Changes
EventContext#params
Change