Last active
August 6, 2020 09:26
-
-
Save NazmusShakib/085724980b733563e68b57b568b84c49 to your computer and use it in GitHub Desktop.
Presence feature using google firestore, realtime database and the cloud function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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