Cloud Functions for Firebase: how to use a Transaction promise? - javascript

I am trying to write a function in Cloud Functions that triggers every time a user gets created and which then saves that user into a list of users and finally increments a user counter.
However I am not sure if I am using promises correctly.
exports.saveUser = functions.auth.user().onCreate(event => {
const userId = event.data.uid
const saveUserToListPromise = db.collection("users").doc(userId).set({
"userId" : userId
})
var userCounterRef = db.collection("users").doc("userCounter");
const transactionPromise = db.runTransaction(t => {
return t.get(userCounterRef)
.then(doc => {
// Add one user to the userCounter
var newUserCounter = doc.data().userCounter + 1;
t.update(userCounterRef, { userCounter: newUserCounter });
});
})
.then(result => {
console.log('Transaction success!');
})
.catch(err => {
console.log('Transaction failure:', err);
});
return Promise.all([saveUserToListPromise, transactionPromise])
})
I want to make sure that even if many users register at once that my userCounter is still correct and that the saveUser function won't be terminated before the transaction and the save to the list has happened.
So I tried this out and it works just fine however I don't know if this is the correct way of achieving the functionality that I want and I also don't know if this still works when there are actually many users triggering that function at once.
Hope you can help me.
Thanks in advance.

The correct way to perform multiple writes atomically in a transaction is to perform all the writes with the Transaction object (t here) inside the transaction block. This ensures at all of the writes succeed, or none.
exports.saveUser = functions.auth.user().onCreate(event => {
const userId = event.data.uid
return db.runTransaction(t => {
const userCounterRef = db.collection("users").doc("userCounter")
return t.get(userCounterRef).then(doc => {
// Add one user to the userCounter
t.update(userCounterRef, { userCounter: FirebaseFirestore.FieldValue.increment(1) })
// And update the user's own doc
const userDoc = db.collection("users").doc(userId)
t.set(userDoc, { "userId" : userId })
})
})
.then(result => {
console.info('Transaction success!')
})
.catch(err => {
console.error('Transaction failure:', err)
})
})

Related

Trouble batch setting a document field by docId in Firestore

I have been using firebase (firestore) for a while but I'm a little stuck and was wondering if anyone can think of a solution.
On the firestore DB I have a single collection of users, each user has an email address and several other fields. In this instance I am checking if a user email exists and if it does, I want to create a list field for that particular user with a listUid. I am referencing the users by email, grabbing the docId for those users and then trying to set a list field for each of them.
I am not getting any error's from firestore, it's simply not updating in the DB for some reason and I can't figure out where I am going wrong. Thanks in advance
export const addListUidToExistingUserList = (
{ firestore },
emailArray,
listUid
) => {
return async () => {
let docIds = [];
emailArray.forEach((emailAddress) => {
//find users by email (works)
const query = db
.collection("users")
.where("email", "==", emailAddress);
//get docId's for user with matching email (works)
query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docIds.push(doc.id);
});
});
//add a new list with corresponding listUid (does not work)
docIds.forEach((id) => {
let userRef = db.collection("users").doc(id);
batch.set(userRef, { lists: [{ listUid }] });
});
});
return await batch.commit();
};
};
You are running into this issue because your docIds array is always empty at the time you call docIds.forEach.
That's because query.get().then runs asynchronously, and so docIds.forEach is not waiting for it to complete.
You could either:
await query.get().then; or
Add the docIds.forEach function INSIDE the then callback of query.get.
Here are your possible fixes:
await query.get().then
//get docId's for user with matching email (works)
await query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docIds.push(doc.id);
});
});
OR:
docIds.forEach inside then
//get docId's for user with matching email (works)
query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docIds.push(doc.id);
});
docIds.forEach((id) => {
let userRef = db.collection("users").doc(id);
batch.set(userRef, { lists: [{ listUid }] });
});
});
Note: Of course, you could also add batch.set directly into your first iteration of querySnapshot.docs.forEach to prevent an unnecessary iteration.

Retrieve multiple users info from firebase auth using Node js

I am using Firebase authentication to store users. I have two types of users: Manager and Employee. I am storing the manager's UID in Firestore employee along with the employee's UID. The structure is shown below.
Firestore structure
Company
|
> Document's ID
|
> mng_uid: Manager's UID
> emp_uid: Employee's UID
Now I want to perform a query like "Retrieve employees' info which is under the specific manager." To do that I tried to run the below code.
module.exports = {
get_users: async (mng_uid, emp_uid) => {
return await db.collection("Company").where("manager_uid", "==", mng_uid).get().then(snaps => {
if (!snaps.empty) {
let resp = {};
let i = 0;
snaps.forEach(async (snap) => {
resp[i] = await admin.auth().getUser(emp_uid).then(userRecord => {
return userRecord;
}).catch(err => {
return err;
});
i++;
});
return resp;
}
else return "Oops! Not found.";
}).catch(() => {
return "Error in retrieving employees.";
});
}
}
Above code returns {}. I tried to debug by returning data from specific lines. I got to know that the issue is in retrieving the user's info using firebase auth function which I used in forEach loop. But it is not returning any error.
Thank you.
There are several points to be corrected in your code:
You use async/await with then() which is not recommended. Only use one of these approaches.
If I understand correctly your goal ("Retrieve employees' info which is under the specific manager"), you do not need to pass a emp_uid parameter to your function, but for each snap you need to read the value of the emp_uid field with snap.data().emp_uid
Finally, you need to use Promise.all() to execute all the asynchronous getUser() method calls in parallel.
So the following should do the trick:
module.exports = {
get_users: async (mng_uid) => {
try {
const snaps = await db
.collection('Company')
.where('manager_uid', '==', mng_uid)
.get();
if (!snaps.empty) {
const promises = [];
snaps.forEach(snap => {
promises.push(admin.auth().getUser(snap.data().emp_uid));
});
return Promise.all(promises); //This will return an Array of UserRecords
} else return 'Oops! Not found.';
} catch (error) {
//...
}
},
};

Optimize Firestore real time updates in chat app

I’m using Firestore real time updates to create realtime chats in my React Native app. I read this may not be the best way to build a chat, but I decided to do so cause I’m using Firebase already and the chat is not the main purpose of the app.
 So, in the context of a real time chat, how would I optimize the Firestore connection? 
It usually works really well but I have experienced a few problems so far:
message comes in slowly
message doesn’t show after being sent
Push notification arrives before the message
These problems usually occur when internet connection is not great (though Whatsapp messages still work fine), but sometimes also on a good connection…
Here is how I query the data (real-time listener added in componentDidMount, removed in componenWillUnmount):
onLogUpdate = (querySnapshot) => {
allMessages = this.state.allMessages
cb = (allMsgs) => {
allMsgs.sort((a,b) => {
a = new Date(a.timestamp);
b = new Date(b.timestamp);
return a>b ? -1 : a<b ? 1 : 0;
})
messages = _.takeRight(allMsgs, this.state.messageLimit)
this.setState({ loading: false, messages, allMessages: allMsgs })
}
async.map(querySnapshot._changes, (change, done) => {
if (change.type === "added") {
const msgData = change._document.data()
if (msgData.origin == 'user') {
this.usersRef.doc(msgData.byWhom).get()
.then(usr => {
msgData.user = usr.data()
done(null, msgData)
})
.catch(err => { console.log('error getting user in log:', err) })
} else {
done(null, msgData)
}
} else {
done(null, 0)
}
}, (err, results) => {
const res = results.filter(el => { return el != 0 })
allMessages = _.concat(allMessages, res)
cb(allMessages)
})
}
And this is how I add new messages:
// in utils.js
exports.addLogMessage = (msgObj, moment_id, callback) => {
logMessagesRef.add(msgObj)
.then(ref => {
momentsRef.doc(moment_id).get()
.then(doc => {
const logMsgs = doc.data().logMessages ? doc.data().logMessages : []
logMsgs.push(ref.id)
momentsRef.doc(moment_id).update({ logMessages: logMsgs })
})
.then(() => {
if (callback) {
callback()
}
})
})
.catch(err => { console.log('error sending logMessage:', err) })
}
// in chat Screen
sendLogMessage = () => {
if (this.state.newMessage.length > 0) {
firebase.analytics().logEvent('send_log_message')
this.setState({ newMessage: '' })
const msgObj = {
text: this.state.newMessage,
origin: 'user',
timestamp: Date.now(),
byWhom: this.state.user._id,
toWhichMoment: this.state.moment._id
}
addLogMessage(msgObj, this.state.moment._id)
}
}
Any suggestions would be highly appreciated :)
I was working on something similar and after i submitted the data it wouldnt show in the ListView. I solved it by pushing the new entry into the preexisting state that was being mapped, and since setState() calls the render() method, it worked just fine. I did something like this:
sendLogMessage().then(newData => {
joined = this.state.data.concat(newData);
this.setState({ data: joined})
})
This is ofcourse assuming that you're using this.state.data.map to render the chat log. This will work when the message that I send cant be seen by me and as for the messages updating as the database updates, you may wanna make use of .onDataChange callback provided by Firebase API. I hope I helped.

firebase set/initialize values to zero dynamically

I'm looking a good and right way to set/ initalize values with http trigger.
what I did is ref to the node in firebase and get data then update it.
module.exports.initializeAnswers = functions.https.onRequest(async(req,res)=>{
try{
// i want to initalize each key
await firebase.ref('/CurrentGame').once('value',snapshot=>{
snapshot.forEach((childSnapshot)=>{
if(childSnapshot !=null){
childSnapshot.update(0)
}
return false
});
})
}catch(e){
console.info(e)
return res.status(400).send({error:0})
}
})
I'm looking for a right way and not by the 'update' function
I want to initalize each value to zero with http trigger
I understand that you will have several children (variable number) under the "answers" node and only one "rightAnswer" node. If my understanding is correct, the following code will do the trick:
exports.initializeAnswers = functions.https.onRequest((req, res) => {
admin.database().ref('/CurrentGame/answers').once('value', snapshot => {
const updates = {};
snapshot.forEach((child) => {
updates['/answers/' + child.key] = 0;
});
updates['/rightAnswer'] = 0;
return admin.database().ref('/CurrentGame').update(updates);
}).then(() => {
res.status(200).end();
}).catch((err) => {
console.log(err);
res.status(500).send(err);
});
});
You can use Firebase Cloud Functions to initialize the values on HTTP trigger. check this link

Remove node from Firebase with Functions

I'm trying to remove a node from Firebase using cronjob and i have this function but when it gets executed I get an error saying "Error: could not handle the request" and the log says: "database is not defined"
This is my function:
exports.cleanStatsOnRequest = functions.https.onRequest((req, res) => {
const ref1 = firebase.database.ref;
const dbref = ref1.child(`/dailystats`);
console.log('removing dailystats');
return dbref.remove
.then(() => {
res.send('dailystats removed');
})
.catch(error => {
res.send(error);
});
});
What am I doing wrong? What is the right way to define the database?
You need to use the Firebase Admin SDK to access the Realtime Database from an HTTP trigger Cloud Function. This documentation shows you how to read from the database. This example shows writing to the database, which would be similar to deleting.
Try this. database,ref and remove are functions. Read this guide.
Also you should not return dbref.remove() as remove() will return a promise.
exports.cleanStatsOnRequest = functions.https.onRequest((req, res) => {
const ref1 = firebase.database().ref(); // changes here
const dbref = ref1.child('/dailystats');
console.log('removing dailystats');
return dbref.remove() // changes here
.then(() => {
res.send('dailystats removed');
})
.catch(error => {
res.send(error);
});
});

Categories

Resources