-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsetOnlineStatus.js
58 lines (48 loc) · 1.7 KB
/
setOnlineStatus.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import db, { createTimestamp, createTimestamp2, db2 } from "./firebase";
var disconnectRef;
function setOnlineStatus(uid) {
try {
console.log("setting up online status");
const isOfflineForDatabase = {
state: 'offline',
last_changed: createTimestamp2,
id: uid,
};
const isOnlineForDatabase = {
state: 'online',
last_changed: createTimestamp2,
id: uid
};
const userStatusFirestoreRef = db.collection("users").doc(uid);
const userStatusDatabaseRef = db2.ref('/status/' + uid);
// Firestore uses a different server timestamp value, so we'll
// create two more constants for Firestore state.
const isOfflineForFirestore = {
state: 'offline',
last_changed: createTimestamp(),
};
const isOnlineForFirestore = {
state: 'online',
last_changed: createTimestamp(),
};
disconnectRef = db2.ref('.info/connected').on('value', function (snapshot) {
console.log("listening to database connected info")
if (snapshot.val() === false) {
// Instead of simply returning, we'll also set Firestore's state
// to 'offline'. This ensures that our Firestore cache is aware
// of the switch to 'offline.'
userStatusFirestoreRef.set(isOfflineForFirestore, { merge: true });
return;
};
userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function () {
userStatusDatabaseRef.set(isOnlineForDatabase);
// We'll also add Firestore set here for when we come online.
userStatusFirestoreRef.set(isOnlineForFirestore, { merge: true });
});
});
} catch (error) {
console.log("error setting onlins status: ", error);
}
};
export { disconnectRef }
export default setOnlineStatus;