Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous>) - javascript

Description of the problem:
My App aim is to store family spending in Firebase Realtime Database. I want that, when a new spending is stored, a notification is sent to all other devices.
I try to send a notification to a single device and it works fine, but when I try to get all the tokens in an array, I have an error:
TypeError: Cannot convert undefined or null to object at Function.keys ().
code of index.js :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.androidPushNotification = functions.database
.ref("{nodo}/spese/{spesaPush}")
.onCreate(async (snapshot, context) => {
const original = snapshot.val();
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/{tutti}/token`).once('value');
let tokensSnapshot;
let tokens;
tokensSnapshot = await getDeviceTokensPromise;
// This is the line generating the errors.
// If I get only a specific token and
// use tokens = tokensSnapshot.val(); anything works fine
tokens = Object.keys(tokensSnapshot.val());
const result = original.chi + " ha speso " +
original.costo + " € per acquistare " +
original.desc;
console.log(result);
const payload = {
notification: {
title: 'New spending inserted!',
body: result,
}
};
const response = await admin.messaging().sendToDevice(tokens, payload);
return result;
});
It seems that values are not reached yet, but I thought that the keyword await lets system to wait until all data are available. From the log I noticed that the value I need is null and I don't understand why.
If I use this line of code:
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/SpecificUser/token`).once('value');
....
//then
tokens = tokensSnapshot.val();
The notification is sent to the device that has the token under the name of "SpecificUser"
EDIT:
I provide a pic of my db. I notice that none of the field is null, so I don't know why I see this error
Thank you to anyone that helps me

i had same error and it is solve by database...
when i saw my database values unfortunately i stored undefined value so my whole result got error like you...
see your whole values and fields that store values properly.

Related

Solana web3 js keep gives Cannot read properties of undefined (reading 'negative') while trying to confirm transaction

I'm trying to sign a transaction with connected user's wallet, through phantom but I keep getting this error message
Cannot read properties of undefined (reading 'negative')
below is my transaction function
async SendTransaction(from,to){
console.log(from);
// const f = JSON.stringify(from)
// console.log(f);
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: new PublicKey(from.publicKey),
toPubkey: new PublicKey(to),
lamports: LAMPORTS_PER_SOL / 100,
}),
);
let blockhash = (await connection.getLatestBlockhash("finalized")).blockhash;
transaction.recentBlockhash = blockhash
transaction.feePayer = from
// Sign transaction, broadcast, and confirm
const signature = await sendAndConfirmTransaction(
connection,
transaction,
[from],
);
console.log(signature);
return transaction
},
I faced the exact same issue.
In my case the problem was with the value I was passing in as feePayer.
We need to be passsing a PublicKey object just like we do for toPubKey and fromPubKey in the SystemProgram.transfer method.
However I was passing in the publicKey string.
I, instead passed a PublicKey object ( new PublicKey(fromAddress) ) as the value for feePayer and it started working.
Please verify your feePayer value.

What does .where.get() return?

i am new this website and to mobile programming.
My questions is:
In firebase i have a collection path with some documents.
.collection(maybe).doc(random)
Each doc has subcollection as well.
Also each doc has data such as:
roomName: randomName
roomPassword: randomPass.
So, now i would like to use the query with .where operator and .get like this:
const docRef=db.collection(‘maybe’)
docRef.where(‘roomName’ ‘==‘ ‘randomName’).get()
My question is what do i get back? As i understand i get the querySnapshot, but i do not fully get how to get the second field in data specifically i.e. how to get roomPass?
const docRef = db.collection(‘maybe’);
const futureSnapshot = docRef.where(‘roomName’,‘==‘,‘randomName’).get();
gives you a promise of snapshot.
You have to "await".
const docRef = db.collection(‘maybe’);
const snapshot = await docRef.where(‘roomName’,‘==‘,‘randomName’).get();
after that you can get your data :
const room = snapshot.data(); // undefined if your query has no results
This link could help you
Happy coding !
EDIT
If your document looks like this :
{
randomName: "a name",
randomPassword: "a password"
}
Then you get your data like that :
const room = snapshot.data(); // undefined if your query has no results
const { randomPassword } = room;

Flutter Firebase Functions Error: Database not defined

I've created a delete oldFiles function for my Database that deletes nodes from my chat messages. I've used the example function provided by Firebase and updated it to fit my use. My database structure is databaseName/messages/{pushId} and I've added const functions = require('firebase-functions') and const admin = require('firebase-admin') and admin.initializeApp(). Here is what I have...
exports.deleteOldItems = functions.database.ref('messages/{pushId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = (DateTime.now().millisecondsSinceEpoch - CUT_OFF_TIME);
const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
When I review my Function logs, I'm getting the following errors...
ReferenceError: DateTime is not defined
at exports.deleteOldItems.functions.database.ref.onWrite (/srv/index.js:17:18)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
And my Functions are finishing with status: error. Any ideas to what may be going on?
DateTime isn't a valid JavaScript object or identifier. If you want to work with dates and times, you will need to work with Date, as you are in the line just above where you have DateTime. You should probably review the JavaScript documentation for Date to learn how it works.

JS SDK, Thrift error code 12 when getting SharedNotebooksList

It's the first time that I work with evernote,
Like the example given in the JS SDK, I create my client with the token that I get from the OAuth and I get all the notebooks of my current user so it was good for me.
But I'm facing a problem that I can't understand, when I use any method of my shared store it throw an Thrift exception with error code 12 and giving the shard id in the message.
I know that 12 error code is that the shard is temporary unavailable..
But I know that it's another thing because it's not temporary...
I have a full access api key, it work with the note store, did I miss something ?
// This is the example in the JS SDK
var linkedNotebook = noteStore.listLinkedNotebooks()
.then(function(linkedNotebooks) {
// just pick the first LinkedNotebook for this example
return client.getSharedNoteStore(linkedNotebooks[0]);
}).then(function(sharedNoteStore) {
// /!\ There is the problem, throw Thrift exception !
return sharedNoteStore.listNotebooks().then(function(notebooks) {
return sharedNoteStore.listTagsByNotebook(notebooks[0].guid);
}).then(function(tags) {
// tags here is a list of Tag objects
});
});
this seems to be an error with the SDK. I created a PR (https://github.com/evernote/evernote-sdk-js/pull/90).
You can work around this by using authenticateToSharedNotebook yourself.
const client = new Evernote.Client({ token, sandbox });
const noteStore = client.getNoteStore();
const notebooks = await noteStore
.listLinkedNotebooks()
.catch(err => console.error(err));
const notebook = notebooks.find(x => x.guid === guid);
const { authenticationToken } = await client
.getNoteStore(notebook.noteStoreUrl)
.authenticateToSharedNotebook(notebook.sharedNotebookGlobalId);
const client2 = new Evernote.Client({
token: authenticationToken,
sandbox
});
const noteStore2 = client2.getNoteStore();
const [notebook2] = await noteStore2.listNotebooks();
noteStore2.listTagsByNotebook(notebook2.guid)

Cloud Function for Firebase Type Error - Cannot Read Property

I'm trying to write a Cloud Function that creates a record whenever someone uses our legacy app to create a record (we have changed the Firebase backend architecture and want to slowly migrate users). However, I'm getting the following error in my logs:
TypeError: Cannot read property 'update' of undefined
at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
Here is the script in question:
//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');
// Listens for new comments added to /comments/ and adds it to /post-comments/
exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
const commentId = event.params.commentId;
const comment = event.data.val();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
//return event.data.ref.parent.child('post-comments').set(comment);
return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
});
});
//initialize
admin.initializeApp(functions.config().firebase);
Thanks!
You can't use functions.database.ref() in the middle of a function to get a ref to somewhere in your database. That's only for defining a new Cloud Function.
If you want a ref to somewhere in your database, you can use event.data.ref or event.data.adminRef to get a ref to the location where the event triggered. You could then use the root property of that to rebuild a new ref to somewhere else in the database. Or you can use your admin object to build a new ref.
It might be helpful to look at some sample code to get a sense of how things work.
Based on Doug's answer, you can replace functions.database.ref with event.data.ref.root.
var functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
const commentId = event.params.commentId;
const comment = event.data.val();
return event.data.ref.root.child('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
return event.data.ref.root.child('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
});
});
admin.initializeApp(functions.config().firebase);

Categories

Resources