Query into firebase realtime database through functions - javascript

I am using firebase functions and Admin SDK to implement a functions on a event trigger. I am trying to push a notification to user when a new update is available. So, when the update version changes from the current, I want to make some changes in the user object and set update_available key as true
Now, the location of event(update_version) that is being tracked and the data to be changed are in to completely different objects. The Object model is as follows:
|root
|- app_info
|- version
|- users
|- <uid>
|- checker
|- update_available: true
Not so far I have achieved this :
function setUpdateValueTrue() {
db.ref().orderByChild("checker/update_available").equalTo("false").once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log("got in here");
console.log(childSnapshot.val())
});
})
}
I guess this maybe completely wrong. At the moment i feel stuck. Any help is really appreciated. My major concern is how to I bypass the uid or query through it.

The following should work (not tested however).
Note the use of Promise.all(), since you need to update a variable number of users nodes in parallel.
exports.versionUpdate = functions.database.ref('/app_info').onUpdate((change, context) => {
const beforeData = change.before.val(); // data before the update
const afterData = change.after.val(); // data after the update
if (beforeData.version !== afterData.version) {
const promises = [];
const usersRef = admin.database().ref('/users');
return usersRef.once('value', function(snapshot) {
snapshot.forEach(childSnapshot => {
const uid = childSnapshot.key;
promises.push(usersRef.child(uid + '/checker/update_available').set(true));
});
return Promise.all(promises);
});
} else {
return null;
}
});

Related

How to retrieve nested data using Javascript (Firebase Realtime Database)?

I want to retrieve the data from donation and display it in a table. I was able to retrieve the user data from Users and displayed it on a table. But now I don't know how I will be able to retrieve the data from donation.
This is my database structure in Firebase. Note: All of the data that was entered came from a mobile app created in Android Studio.
This is the code that I made when retrieving the User data.
function AddAllITemsToTable(User) {
id=0;
tbody.innerHTML="";
User.forEach(element => {
AddItemToTable(element.uid, element.fullName, element.organization, element.contactPerson, element.contactNo, element.location, element.emailAddress, element.status);
});
}
function GetAllDataRealtime() {
const dbRef = ref(database, 'Users');
onValue(dbRef,(snapshot) => {
var Users = [];
snapshot.forEach(childSnapshot => {
Users.push(childSnapshot.val());
});
AddAllITemsToTable(Users);
})
}
window.onload = GetAllDataRealtime;
Since you're calling onValue on /Users, you already get all data for all users and all of their donations. To process the donations in your code:
const dbRef = ref(database, 'Users');
onValue(dbRef,(snapshot) => {
var Users = [];
snapshot.forEach(userSnapshot => {
Users.push(userSnapshot.val());
userSnapshot.child("donation").forEach((donationSnapshot) => {
console.log(donationSnapshot.key, donationSnapshot.val());
});
});
AddAllITemsToTable(Users);
})
As I said in my comment, I recommend reading the Firebase documentation on structuring data, as the way you nest donations under each user does not follow the guidance on nesting data and keeping your structure flat.

Firestore Delete All References of A User

I have a chat app build in react native. When a user decides to delete their profile, I want to remove all references of them from the database.
The DB has references to their user id in the "matches" table, the "chat" table, and the "messages" table for each of the people the deleted user was chatting with.
I am using firebase functions to handle the deletion of the user doc data and auth but I am not sure what the best way to go about removing all of these references would be. My question is: what is the best way to remove all references of an ID out of a somewhat complex database? I assume this will be taxing to loop through every single user in the DB to search for this one ID.
deleteAccount = () => {
var db = firebase.firestore();
firebase.auth().onAuthStateChanged(async (user) => {
if (user) {
//delete user data
db.collection("Users")
.doc(user.uid)
.delete();
} else {
console.log("user needs to reauth");
return false;
}
});
};
firebase functions
exports.deleteUser = functions.firestore
.document("Users/{userID}")
.onDelete((snap, context) => {
const deletedValue = snap.data();
// Delete the images
try {
admin.auth().deleteUser(deletedValue.id);
const imgRef1 = firebase.storage().ref(user.uid + "/images/0")
? firebase.storage().ref(user.uid + "/images/0")
: null;
const imgRef2 = firebase.storage().ref(user.uid + "/images/1")
? firebase.storage().ref(user.uid + "/images/1")
: null;
const imgRef3 = firebase.storage().ref(user.uid + "/images/2")
? firebase.storage().ref(user.uid + "/images/2")
: null;
imgRef1.delete().then(function() {
imgRef2.delete().then(function() {
imgRef3.delete().then(function() {});
});
});
} catch (e) {
console.log("no images to delete");
}
});
Firebase products such as the databases and storage have no implicit knowledge of what data belongs to what user. That relation only exists because your application code made it.
For that reason you will also have to look up/traverse the relations when deleting the user, to find (and delete) their data. There are no shortcuts in the product here, although there is a open-source library that contains an implementation that works from a configuration file: user-data-protection
Edit: I just realized there's actually an Extension to Delete User Data, which does pretty much the same as the library linked above. It might be worth to have a look if that suits your needs

How to move Firebase relational queries server side

This is my first project with Firebase, and I've created a relational data structure. Now I see why this isn't the best way to do things!
In this part of my app, users can add multiple items to an outfit - here's a diagram of the data structure/relationship I have in Firebase now.
I've included code from a Redux action creator in my React Native app. When a user edits an outfit - removing some items - this code:
takes an array with the new list of items from the client
compares this array with the current saved items server side
creates a new array of the diff (removed items)
loops through the outfits for each of those items, matching against the outfit being edited
removes references that match
This code works, but is pretty deeply nested and messy:
export const updateTagReferences = (localTags, outfitId) => {
//localTags represents the new set of items from application state
//outfitId is the uid for the outfit where those items appear
const {currentUser} = firebase.auth();
return dispatch => {
firebase
.database()
.ref(`users/${currentUser.uid}/outfits/${outfitId}/taggedItems`)
.once('value')
.then(snapshot => {
var serverTags = snapshot.val();
// Work out the diff (ie, which items have been removed locally)
return _.differenceWith(serverTags, localTags, _.isEqual);
})
.then(toDelete => {
toDelete.map(item => {
firebase
.database()
.ref(`users/${currentUser.uid}/items/${item.item.uid}/outfits`)
.once('value')
.then(snapshot => {
var outfits = snapshot.val();
for (var taggedItem in outfits) {
if (outfits.hasOwnProperty(taggedItem)) {
var i = outfits[taggedItem];
return i.uid === outfitId
? firebase
.database()
.ref(
`users/${currentUser.uid}/items/${item.item.uid}/outfits/${taggedItem}`,
)
.remove()
: null;
}
}
});
});
})
.then(console.log('Done'));
};
};
As you can see, I'm trying to use Firebase promises to loop through the outfits nested in each item server side.
My issues are:
I'm making lots of queries to Firebase, which isn't ideal
console.log('Done') fires before .remove() - I need to follow up with a second action once this action completes
I've tried the following code, based on this answer, but I can't seem to get it to work:
export const updateTagReferences = (localTags, outfitId) => {
const {currentUser} = firebase.auth();
return dispatch => {
// Create a ref for the outfit the user is editing
firebase
.database()
.ref(`users/${currentUser.uid}/outfits/${outfitId}/taggedItems`)
.once('value')
.then(snapshot => {
// Compare local (app state) with remote (Firebase) to work out which items have been removed
var serverTags = snapshot.val();
return _.differenceWith(serverTags, localTags, _.isEqual);
})
.then(toDelete => {
var promises = [];
// Create a ref for each item to delete
toDelete.map(item => {
firebase
.database()
.ref(`users/${currentUser.uid}/items/${item.item.uid}/outfits`)
.once('value')
.then(snapshot => {
var outfits = snapshot.val();
for (var taggedItem in outfits) {
// Loop through the outfits that item appears in
if (outfits.hasOwnProperty(taggedItem)) {
var i = outfits[taggedItem];
// Match against the outfit the user is editing
return i.uid === outfitId
? promises.push(
firebase
.database()
.ref(
`users/${currentUser.uid}/items/${item.item.uid}/outfits/${taggedItem}`,
)
// Remove the reference
.remove(),
)
: null;
}
}
})
// Execute all the promises, removing firebase references for each item removed locally
.then(Promise.all(promises).then(console.log('Done')));
});
});
};
};
I'm trying to make my code more efficient overall, so I can replicate it elsewhere in my project. I'd love an explanation of the best way to move this kind of query server side.
Currently, changing the whole data structure is out of scope (that's for next time!)
Thanks.

Firestore Comparing two collection documents is very slow

I'm currently uploading the phones contact of my mobile users to a Firestore database.
On average a user has ~500 phone numbers, and I will be having ~1000 users.
My structure is as follow:
Firestore-root
|
--- users_contacts (collection)
|
--- uid (document)
|
--- contacts (subcollection)
|
--- phoneNumberOfContact (document)
|
--- phoneNumberOfContact: true
And I have another collection where I store general phone numbers that I want to compare a specific user's contacts with.
I have about 50,000 phone number in there, each as a document. This will greatly increase later, maybe to 1 million.
Firestore-root
|
--- db_contacts (collection)
|
--- phoneNumber (document)
|
--- phoneNumber: true
I'm trying to check the common numbers of a specific known uid and the db_contacts collection. How many numbers of a known uid exist in the db_contacts collection.
My Cloud Function will be as follow:
Fetch all the Phone Numbers of a Contact
First I wanted to only fetch the ids of the document of a user, since the id is the phone number, hoping it would make the proccess faster. But it seems its not possible in Javascript as snapshotChanges() does not exist.
Loop through the fetched contacts and check if the contact exists in db_contacts. Since I already know the reference path to check if it exists or not, this should go fast
Return all the common contacts
If there was an alternative to snapshotChanges() in JavaScript my script would run much faster. Is my way of thinking correct?
What I did so far:
exports.findCommonNumbers = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
fetchCommonNumbers().then((commonNumbers) => {
console.log(commonNumbers);
resolve("Done");
}).catch((err) => {
console.log(err);
reject("Error Occured");
});
});
});
async function fetchCommonNumbers() {
var commonNumbers = [];
let contactsReference = admin.firestore().collection("user_contacts").doc("iNaYVsDCg3PWsDu67h75xZ9v2vh1").collection("contacts");
const dbContactReference = admin.firestore().collection('db_contacts');
userContacts = await contactsReference.get();
userContacts = userContacts.docs;
for(var i in userContacts){
var userContact = userContacts[i];
const DocumentID = userContact.ref.id;
//Check if Document exist
dbContact = await dbContactReference.doc(DocumentID).get();
if (dbContact.exists) {
commonNumbers.push(DocumentID);
}
}
return Promise.resolve(commonNumbers);
}
The function findCommonNumbers is taking 60 seconds to execute. It has to be much faster. How can I make it faster?
When you're looking for documents in common, you're fetching one, waiting for it to come back, fetching the next, waiting for it... I haven't used async/await before, but I'd do something like:
Promise.All(userContacts.map(userContact => {
const DocumentID = userContact.ref.id;
//Check if Document exists
return dbContactReference.doc(DocumentID).get().then(dbContact => {
if (dbContact.exists) {
commonNumbers.push(DocumentID);
}
});
}));
Sorry for the code fragment and mistakes; I'm on mobile. This should request them all at once.
Edit: to return after something other than all have returned:
new Promise((resolve, reject) => {
var returned = 0;
userContacts.map(userContact => {
const DocumentID = userContact.ref.id;
//Check if Document exists
dbContactReference.doc(DocumentID).get().then(dbContact => {
if (dbContact.exists) {
commonNumbers.push(DocumentID);
}
returned++;
if (returned == userContact.length || commonNumbers.length >= 5) {
resolve(commonNumbers);
}
});
});
});

Firebase - Update specific fields simultaneously without replacing all of the data

I would like to be able to publish simultaneously in two directories of my Firebase database. I created a function for this, according to the example proposed in the "Update specific fields" section of the Firebase Javascript documentation:
function linkTwoUsers(user1, user2) {
// The two users are "connected".
var user1Data = {
userLink: user2
};
var user2Data = {
userLink: user1
};
var updates = {};
updates["/users/" + user1] = user1Data;
updates["/users/" + user2] = user2Data;
return database
.ref()
.update(updates)
.then(() => {
return res.status(200).end();
})
.catch(error => {
return res.status(500).send("Error: " + error.message);
});
}
The problem is that when I run the function, instead of uploading the directories, it replaces all the data present in it.
Here are the user directories before the function:
And then:
How do we make sure the data doesn't overwrite the others? Thank you for your help.
Try to narrow your path to just the property you are trying to update:
updates["/users/" + user1 + "/userLink/"] = user1;
updates["/users/" + user2 + "/userLink/"] = user2;
It seems as though you're creating an entirely new object when you set:
var userData = { someThing: stuff }
When you pass that in, it will override the original object. One way you might solve this (there might be a more efficient way) is to grab the objects from Firebase, add the new property and value to the object, then send the entire object back into Firebase.
In some javascript frameworks, you should be able to use the spread operator to set all of an object's props to another object like this:
var newObject = { ...originalObject }
newObject.userData = "something"
// then save newObject to firebase

Categories