Firebase Functions: Cannot read property 'val' of undefined - javascript

I'm trying to add a Function in my Firebase Database, that creates/updates a combined property of two others, whenever they change.
The model is like this:
database/
sessions/
id/
day = "1"
room = "A100"
day_room = "1_A100"
And my function so far:
exports.combineOnDayChange = functions.database
.ref('/sessions/{sessionId}/day')
.onWrite(event => {
if (!event.data.exists()) {
return;
}
const day = event.data.val();
const room = event.data.ref.parent.child('room').data.val();
console.log(`Day: ${day}, Room: ${room}`)
return event.data.ref.parent.child("day_room").set(`${day}_${room}`)
});
exports.combineOnRoomChange = functions.database
.ref('/sessions/{sessionId}/room')
.onWrite(event => {
if (!event.data.exists()) {
return;
}
const room = event.data.val();
const day = event.data.ref.parent.child('day').data.val();
console.log(`Day: ${day}, Room: ${room}`)
return event.data.ref.parent.child("day_room").set(`${day}_${room}`)
});
But it's throwing this error:
TypeError: Cannot read property 'val' of undefined
I'm following the very first example in the Firebase Functions Get Started (Add the makeUppercase() function) and this is what it does in order to reach the entity reference:
event.data.ref.parent
Am I using the child() function wrongly? Any ideas?

When Cloud Functions triggers your code, it passes in a snapshot of the data that triggered the change.
In your code:
exports.combineOnDayChange = functions.database
.ref('/sessions/{sessionId}/day')
This means you event.data has the data for /sessions/{sessionId}/day. It does not contain any data from higher in the tree.
So when you call event.data.ref.parent, this points to a location in the database for which the data hasn't been loaded yet. If you want to load the additional data, you'll have to load it explicitly in your code:
exports.combineOnDayChange = functions.database
.ref('/sessions/{sessionId}/day')
.onWrite(event => {
if (!event.data.exists()) {
return;
}
const day = event.data.val();
const roomRef = event.data.ref.parent.child('room');
return roomRef.once("value").then(function(snapshot) {
const room = snapshot.val();
console.log(`Day: ${day}, Room: ${room}`)
return event.data.ref.parent.child("day_room").set(`${day}_${room}`)
});
});
Alternatively, consider triggering higher in your tree /sessions/{sessionId}. Doing so means that you get all the necessary data in event.data already, and also means you only need a single function:
exports.updateSyntheticSessionProperties = functions.database
.ref('/sessions/{sessionId}')
.onWrite(event => {
if (!event.data.exists()) {
return; // the session was deleted
}
const session = event.data.val();
const day_room = `${session.day}_${session.room}`;
if (day_room !== session.day_room) {
return event.data.ref.parent.child("day_room").set(`${day}_${room}`)
});
});

Related

Firebase real time database - subscription .on() does not trigger on client

I have a collection of notes in my Firebase realtime database.
My code is set to subscribe to modifications in the /notes path of the database.
When updating a note in the Firebase web console my client gets the updates, but when another client updates the note via ref.update() the data is not pushed to my client.
When updating in the Firebase web console, I am performing the update from one browser and watching the update in another browser.
How can this be? See code below.
export const startSubscribeNotes = () => {
return (dispatch, getState) => {
const uid = getState().auth.uid
const dbPath = 'notes'
database.ref(`${dbPath}`)
.orderByChild(`access/members/${uid}`)
.equalTo(true)
.on('value', (snapshot) => {
console.log('notes .on()')
let updatednotes = []
console.log('Existing notes', existingnotes)
snapshot.forEach( (data) => {
const note = {
id: data.key,
...data.val()
}
updatednotes.push(note)
})
dispatch(setnotes(notes))
})
}
}
What I have noticed is that if I change my access rules in the Firebase database I am able to get the updates, but can no longer restrict read access.
"notes": {
//entry-level access
".read": "
auth.uid !== null //&& query.equalTo === auth.uid
",
I can then loop all notes and collect the ones I should only be able to read.
const uid = getState().auth.uid
database.ref('notes')
.on('value', (snapshot) => {
const notes = []
snapshot.forEach((data) => {
const noteData = data.val()
if(noteData.access){
const authorArray = (noteData.access.author) ? [noteData.access.author] : []
const members = (noteData.access.members) ? noteData.access.members : {}
const membersArray = Object.keys(members)
const allUsers = authorArray.concat(membersArray)
const accessGranted = allUsers.includes(uid)
if(accessGranted){
const note = {
id: data.key,
...data.val()
}
notes.push(note)
}
}
})
if(notes.length > 0){ dispatch(setNotes(notes)) } //Dispatch if not empty
})
How can I apply the access rules and still get the updates pushed to my client?
I have checked that all clients can write to the database at /notes
Any help much appreciated!

JavaScript Google Cloud Function: write Stripe values to Firebase

I'm new to JavaScript and I have written the following JS Google Cloud Function with the help of various resources.
This function handles a Stripe invoice.payment_succeeded event and instead of writing the entire data I am trying to save just both the sent period_start and period_end values back to the correct location in my Firebase DB (see structure below).
How can I write these two values in the same function call?
exports.reocurringPaymentWebhook = functions.https.onRequest((req, res) => {
const hook = req.body.type;
const data = req.body.data.object;
const status = req.body.data.object.status;
const customer = req.body.data.object.customer;
const period_start = req.body.data.object.period_start;
const period_end = req.body.data.object.period_end;
console.log('customer', customer);
console.log('hook:', hook);
console.log('status', status);
console.log('data:', data);
console.log('period_start:', period_start);
console.log('period_end:', period_end);
return admin.database().ref(`/stripe_ids/${customer}`).once('value').then(snapshot => snapshot.val()).then((userId) => {
const ref = admin.database().ref(`/stripe_customers/${userId}/subscription/response`)
return ref.set(data);
})
.then(() => res.status(200).send(`(200 OK) - successfully handled ${hook}`))
.catch((error) => {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with StackDriver
return snap.ref.child('error').set(userFacingMessage(error));
})
.then((error) => {
return reportError(error, {user: context.params.userId});
});
});//End
HTTP type functions are terminated immediately after the response is sent. In your code, you're sending the response, then attempting to do more work after that. You will have to do all the work before the response is sent, otherwise it may get cut off.
If you just want to save the period_start and period_end values, instead of the entire data object, you can use the update() method (see https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields).
You should then modify your code as follows. (Just note that it is not clear from where you receive the userId value, since you don't show the stripe_ids database node in your question. I make the assumption that it is the value at /stripe_ids/${customer}. You may adapt that.)
exports.reocurringPaymentWebhook = functions.https.onRequest((req, res) => {
const hook = req.body.type;
const data = req.body.data.object;
const status = req.body.data.object.status;
const customer = req.body.data.object.customer;
const period_start = req.body.data.object.period_start;
const period_end = req.body.data.object.period_end;
admin.database().ref(`/stripe_ids/${customer}`).once('value')
.then(snapshot => {
const userId = snapshot.val();
let updates = {};
updates[`/stripe_customers/${userId}/subscription/response/period_start`] = period_start;
updates[`/stripe_customers/${userId}/subscription/response/period_end`] = period_end;
return admin.database().ref().update(updates);
})
.then(() => res.status(200).send(`(200 OK) - successfully handled ${hook}`))
.catch((error) => {...});
});

Undefined username in cloud functions?

I want to send a notification to a specific device so I write this function and its work right but I got undefined in the username
Logs output:
Get this
after: { '-LhjfwZeu0Ryr6jYRq5r': { Price: '888', date: '2019-6-19', description: 'Ghh', id: 50, nameOfProblem: 'Vbh', providerName: 'Loy', providerService: 'Carpenter', statusInfo: 'Incomplete', time: '15:22', username:"devas" }}
And the username is undefined
Here is the function
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders')
.onWrite(async (snapshot, context) => {
const registrationTokens = "------";
const providerId = context.params.pid;
const userId = context.params.uid;
const event = context.params;
console.log("event", event);
console.log(`New Order from ${userId} to ${providerId}`);
const afterData = snapshot.after.val(); // data after the write
const username = snapshot.after.val().username;
console.log(afterData);
console.log(username);
const payload = {
notification: {
title: 'Message received',
body: `You received a new order from ${username} check it now! `,
sound: "default",
icon: "default",
}
};
try {
const response = await admin.messaging().sendToDevice(registrationTokens, payload);
console.log('Successfully sent message:', response);
}
catch (error) {
console.log('Error sending message:', error);
}
return null;
});
It looks like the code you wrote is meant to run when a new order is added to the database. But you've declared it to trigger like this:
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders')
.onWrite(async (snapshot, context) => {
This means that the code instead triggers whenever anything is written under the orders node for a user. To trigger only when an order is written under that orders node, define your trigger as:
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders/{orderid}')
.onWrite(async (snapshot, context) => {
The difference above is that the path now includes {orderid} meaning that it triggers one level lower in the tree, and your snapshot.after will no longer contain the -L level.
Since you actually only seem to care about when an order gets created, you can also only trigger on that (meaning your function won't get called when an order gets updated or deleted). That'd be something like this:
exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders/{orderid}')
.onCreate(async (snapshot, context) => {
...
const afterData = snapshot.val();
const username = snapshot.val().username;
console.log(afterData);
console.log(username);
...
});
Here we again trigger on the lower-level in the JSON. But since we now trigger onCreate, we no longer have a before and after snapshot, and instead just do snapshot.val() to get the data that was just created.
Since the object you are retrieving has a generated member you could use a for-in loop to retrieve the value.
const object = snapshot.after.val()
for(const key in object) {
if (object.hasOwnProperty(key)) {
const element = object[key];
if(element.username) {
console.log(element.username);
break;
}
}
}

How to make a subquery synchronously in Firebase realtime with Cloud Funtions

I'm using firebase functions with JavaScript to make a query about Firebase realtime, which will be used in an Android application. The main query obtains a collection of values that I then go through, and for each of them I launch another query. The results obtained from the second query stores in an array that is the one that I return as a result.
The problem is that the array that I return as an answer is empty, since the response is returned before the subqueries that add the data to the array end, that is, the problem I think is due to the asynchronous nature of the calls.
I have tried to reorganize the code in several ways and use promises to try that the result is not sent until all the queries have been made but the same problem is still happening.
The structure of the JSON database that I consult is the following:
"users" : {
"uidUser" : {
"friends" : {
"uidUserFriend" : "mail"
},
"name" : "nameUser",
...
},
"uidUser2" : {
"friends" : {
"uidUserFriend" : "mail"
},
"name" : "nameUser",
...
}
}
The functions are:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.searchFriends = functions.https.onCall((data,context) => {
const db = admin.database();
const uidUser = data.uidUser;
var arrayOfResults = new Array();
const refFriends = db.ref('/users/'+uidUser+'/friends');
let user;
return refFriends.once('value').then((snapshot) => {
snapshot.forEach(function(userSnapshot){
user = findUser(userSnapshot.key);
arrayOfResults.push(user);
});
return {
users: arrayOfResults
};
}).catch((error) => {
throw new functions.https.HttpsError('unknown', error.message, error);
});
});
function findUser(uid){
const db = admin.database();
const ref = db.ref('/users/'+uid);
return ref.once('value').then((snapshot) => {
console.log(snapshot.key,snapshot.val());
return snapshot.val();
}).catch((error) => {
console.log("Error in the query - "+error);
});
}
I do not know if the problem is because I do not manage the promises well or because I have to orient the code in another way.
Thank you.
Indeed, as you mentioned, you should "manage the promises" differently. Since you are triggering several asynchronous operations in parallel (with the once() method, which returns a promise) you have to use Promise.all().
The following code should do the trick:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.searchFriends = functions.https.onCall((data,context) => {
const db = admin.database();
const uidUser = data.uidUser;
var arrayOfPromises = new Array();
const refFriends = db.ref('/users/' + uidUser + '/friends');
let user;
return refFriends.once('value').then(snapshot => {
snapshot.forEach(userSnapshot => {
user = findUser(userSnapshot.key);
arrayOfPromises.push(user);
});
return Promise.all(arrayOfPromises);
})
.then(arrayOfResults => {
return {
users: arrayOfResults
};
})
.catch((error) => {
throw new functions.https.HttpsError('unknown', error.message, error);
});
});
function findUser(uid){
const db = admin.database();
const ref = db.ref('/users/' + uid);
return ref.once('value').then(snapshot => {
console.log(snapshot.key,snapshot.val());
return snapshot.val();
});
}
Note that I have modified the name of the first array to arrayOfPromises, which makes more sense IMHO.
Note also that you receive the results of Promise.all() in an array corresponding to the fulfillment values in the same order than the queries array, see: Promise.all: Order of resolved values

Firebase Multi path atomic update with child values?

I am succesfully updating my user's profile picture on their profile and on all of their reviews posted with this function:
export const storeUserProfileImage = (url) => {
const { currentUser } = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/profilePic`)
.update({ url });
firebase.database().ref('reviews')
.orderByChild('username')
.equalTo('User3')
.once('value', (snapshot) => {
snapshot.forEach((child) => {
child.ref.update({ profilePic: url });
});
});
};
I am aware that I should be using an atomic update to do this so the data updates at the same time (in case a user leaves the app or something else goes wrong). I am confused on how I can accomplish this when querying over child values.
Any help or guidance would be greatly appreciated!
Declare a variable to store all the updates. Add the updates as you read them on your listener's loop. When the loop is finished, run the atomic update.
export const storeUserProfileImage = (url) => {
const { currentUser } = firebase.auth();
firebase.database().ref('reviews')
.orderByChild('username')
.equalTo('User3')
.once('value', (snapshot) => {
var updates = {};
updates[`/users/${currentUser.uid}/profilePic`] = url;
snapshot.forEach((child) => {
updates[`/reviews/${child.key}/profilePic`] = url;
});
firebase.database().ref().update(updates);
});
};

Categories

Resources