Skip to content

Instantly share code, notes, and snippets.

@NazmusShakib
Last active August 6, 2020 09:26
Show Gist options
  • Save NazmusShakib/085724980b733563e68b57b568b84c49 to your computer and use it in GitHub Desktop.
Save NazmusShakib/085724980b733563e68b57b568b84c49 to your computer and use it in GitHub Desktop.
Presence feature using google firestore, realtime database and the cloud function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const firestore = functions.firestore;
exports.onUserPresenceStatusChanged = functions.database
.ref('/online/{userId}')
.onUpdate((change, context) => {
var db = admin.firestore();
const beforeData = change.before.val(); // data before the write
const afterData = change.after.val(); // data after the write
console.log('userId:: ' + context.params.userId);
console.log('BeforeData:: ' + beforeData);
console.log('AfterData:: ' + afterData);
presenceStatus = (afterData === 'online') ? true : false;
console.log('PresenceStatus:: ' + presenceStatus);
// const usersRef = firestore.document('/users/' + context.params.userId);
// const usersRef = db.collection("users");
db.doc('users/' + context.params.userId).set({
online: presenceStatus,
last_online_at: Date.now(),
}, {merge: true})
.then(function() {
console.log("Document successfully written.");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment