Skip to content

Instantly share code, notes, and snippets.

@abinavseelan
Last active May 18, 2020 00:17
Show Gist options
  • Save abinavseelan/ace0ae4d4c594194c6c698df800e516e to your computer and use it in GitHub Desktop.
Save abinavseelan/ace0ae4d4c594194c6c698df800e516e to your computer and use it in GitHub Desktop.
Firebase Cloud Function to handle online/offline status
const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();
exports.onUserStatusChanged = functions.database
.ref('/status/{userId}') // Reference to the Firebase RealTime database key
.onUpdate(event => {
const usersRef = firestore.collection('/users'); // Create a reference to the Firestore Collection
return event.data.ref.once('value')
.then(statusSnapshot => snapShot.val()) // Get the latest value from the Firebase Realtime database
.then(status => {
// check if the value is 'offline'
if (status === 'offline') {
// Set the Firestore's document's online value to false
usersRef
.doc(event.params.userId)
.set({
online: false
}, { merge: true });
}
})
});
@savan-gotrakiya
Copy link

I have used above code.
but I am getting an Error
TypeError: Cannot read property 'userId' of undefined
at exports.onUserStatusChanged.functions.database.ref.onUpdate.event

please help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment