Debugging firebase RT database connection - javascript

I'm following this tutorial on building in-app presence using cloud firestore and they recommend using Firebase realtime database. The relevant bit of code for this question is:
database.onValue(database.ref(db, '.info/connected'), function (snapshot) {
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.'
console.log('not connected to rtdb');
firestore.setDoc(userStatusFirestoreRef, isOfflineForFirestore);
return;
};
userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function () {
console.log('connected to rtdb');
userStatusDatabaseRef.set(isOnlineForDatabase);
// We'll also add Firestore set here for when we come online.
firestore.setDoc(userStatusFirestoreRef, isOnlineForFirestore);
});
});
The line not connected to rtdb consistently prints to my console, but I haven't seen connected to rtdb once. Is there an additional step I need to do to establish a connection to the realtime database?

Related

Does Firebase Firestore keep a local copy of snapshot

I am using firebase firestore for my chat room application.
I have a function to send messages to firebase as
const sendMessageHandler = message => {
if (message) {
firestore()
.collection(`ChatRooms/${roomId}/messages`)
.doc(moment().format('YYYY-MM-DD-HH-mm-sssss'))
.set({
message: Encrypt(message),
userId: userId,
});
}
};
and I am fetching messages into flatlist only from firestore as
// this messages const is getting data only from firestore
const [messages, setMessage] = useState([]);
firestore()
.collection(`ChatRooms/${roomId}/messages`)
.onSnapshot(
querySnapshot => {
const messages = [];
querySnapshot.forEach(dataSnapshot => {
messages.push({
id: dataSnapshot.id,
message: dataSnapshot.data().message,
userId: dataSnapshot.data().userId,
});
});
setMessage(messages.reverse());
setLoading(false);
},
error => {
console.log('error : ', error);
},
);
// And now I am using this messages somewhere in return function of a component as :
<FlatList
data={messages}
renderItem={flatListItemRenderer}
inverted={true}
/>
Notice I am fetching only from firestore and not locally.
Now I turned off the internet and tried sending messages so this happens
The data has not been updated to firestore (of course because of no internet), but the flatlist has been updated with the new message !!
The only possibility I can think of is that the setter methods of firestore is storing data in both local and remote database and the getter method is first getting snapshot from local database and then remote database.
So the question is does #react-native-firebase/firestore keep a local snapshot also and updates both local and remote snapshot of data whenever we change something?
Github Link
Edit :
Firestore docs says
Firestore provides out of the box support for offline capabilities. When reading and writing data, Firestore uses a local database which synchronizes automatically with the server.This functionality is enabled by default, however it can be disabled if you need it to be disabled
I tried turning off persistence, but this property is related to storing data offline not the state. i.e, now when my app loads it fetch all the data directly from server(previously fetching from storage and server both), but the flatlist still updates with the new message(maybe it is storing some state like useState also???)
The Firestore SDK keeps a local copy of:
All data that you have an active listener for.
All pending writes.
In addition, if offline persistence is enabled, it also keeps a local copy of data that your code has recently read.
When you make a write operation, the SDK:
Writes your operation to its queue of pending writes.
Fires an event for any local listeners.
Tries to synchronize the pending write with the server.
Steps 1 and 2 always happen, regardless of whether you are online or offline. Only step 3 won't complete immediately when you are offline.

Is there a way to close the connection after using firebase.initializeApp() with Cloud Firestore?

I'm attempting to make a Discord.js command that uploads data to Cloud Firestore. It works, just if I attempt to reuse the command it reruns the firebase.initializeApp() line, which throws an error. Is there any way to disconnect after I have uploaded the data?
It is not recommended to disconnect - the time and processing cycle cost of .initializeApp() is prohibitive unless these calls are quite rare.
There are a few of valid approaches:
=> Keep a state value that indicates that the app is already initialized
=> initialize firebase at a "higher point" in your code to avoid reloading the module
=> I believe you can actually "ask" firebase if there is a running app, in which case don't re-initialize (const app = firebase.app())
If for some reason you do need to remove a firebase app instance:
const app = firebase.app(); //retrieves the default instance
app.delete()
.then(function() {
console.log("App deleted successfully");
})
.catch(function(error) {
console.log("Error deleting app:", error);
});

React Native Could not reach Cloud Firestore backend

I was previously using firebase realtime database however now want to switch over to Cloud Firestore but am getting the below error, even when authenticated. I'm currently using Android Simulator, tried disabling my realtime database but cannot find a solution.
Firebase v5.4.2
[2018-09-02T12:53:42.064Z] #firebase/firestore:', 'Firestore (5.0.4):
Could not reach Cloud Firestore backend. Backend didn't respond within
10 seconds. This typically indicates that your device does not have a
healthy Internet connection at the moment. The client will operate in
offline mode until it is able to successfully connect to the backend.
My config is setup:
{
"apiKey": "apiKey",
"authDomain": "authDomain.firebaseapp.com",
"databaseURL": "https://databaseURL.firebaseio.com",
"projectId": "projectID",
"storageBucket": "storageBucket.appspot.com",
"messagingSenderId": "messagingSenderId"
}
As per docs I'm adding a users collection. Note that I do not get into the .then or the .catch statement even if I setup a users collection manually against the database.
onTestPress() {
console.log("onTestPress");
var db = firebase.firestore();
//console.log(db);
const settings = { timestampsInSnapshots: true };
db.settings(settings);
db.collection("users").add({
first: "Ada",
last: "Lovelace"
}).then(function (docRef) {
console.log("adding document: ", docRef.id);
}).catch(function (error) {
console.log("Error adding document: ", error);
});
db.collection("users").get().then((querySnapshot) => {
console.log(`querySnapshot: ${querySnapshot}`)
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
});
});
}
This is from Android Logcat you can see the .get() query returns the local copy. Only thing suspicious is the duplicate layer name?
09-02 14:05:37.811 2987-4016/com.myApp I/ReactNativeJS: onTestPress
09-02 14:05:47.837 2987-4016/com.myApp E/ReactNativeJS: '[2018-09-02T13:05:47.837Z] #firebase/firestore:', 'Firestore (5.0.4): Could not reach Cloud Firestore backend. Backend didn\'t respond within 10 seconds.\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.'
09-02 14:05:47.849 2987-4016/com.myApp I/ReactNativeJS: querySnapshot: [object Object]
09-02 14:05:47.849 2987-4016/com.myApp I/ReactNativeJS: 3jifIc5kyEkGU4Bzvau9 => {"first":"Ada","last":"Lovelace"}
09-02 14:05:47.858 1431-1431/? D/SurfaceFlinger: duplicate layer name: changing com.myApp/com.myApp.MainActivity to com.myApp/com.myApp.MainActivity#1
09-02 14:05:47.931 2987-3021/com.myApp D/EGL_emulation: eglMakeCurrent: 0x9d7857e0: ver 3 0 (tinfo 0x9d783540)
Here's my import:
import firebase from "firebase";
import '#firebase/firestore'
Rules setup which should allow read and write?
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
I'm really not sure what else I can check so any advise would be greatly appreciated!
I also had this issue. The warning should appear after 10 seconds. but in my case, it appears when i load the component, without timeout. because my laptop's time in not correct. I did correct time and still had that issue. so i had to turn on "Set time automatically" and "Set time zone automatically" in "Date & time" settings in windows. everything works out for me.

Firebase script code is shown in console [duplicate]

This question already has answers here:
Is it safe to expose Firebase apiKey to the public?
(10 answers)
Closed 4 years ago.
I'm quite new to Firebase in general and I have some questions which I'm not sure if they are an issue or not.
First I set up my API keys and such
<script>
firebase.initializeApp({
apiKey: '#####',
authDomain: '#####',
projectId: '####'
});
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
</script>
And than I went and used the example given by google
<script>
var docRef = db.collection("MyTable").doc("person1");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
</script>
And it worked i got the stuff that I needed. Buy my main question is isn't this unsafe?
I opened the Developer Console and i inspected the scripts to see what's going on and I saw that it shows everything , my database name , the collection I'm accessing and so on.
What makes a random person just copying my code and running it on their side? Is there a fix to this is it meant to work like this?
As I said I'm new to this so maybe I'm missing something here.
You are unable to whitelist domains for your database. Keep in mind as a public cloud hosted database, public really means public. That said there are a few things you can do;
Use firebase cloud functions for anything you want to keep out of the client.
Use /__/firebase/init.js in your web client which will configure and initialize your firebase instance without it being explicitly loaded onto the page - Keep in mind users can still get the info by following the JS link.
If your users are authenticated then can use database rules to make sure they only logged in users see data { "rules": { ".read": "auth !== null" } } , or that the logged in user can see their own data. Check here for more info https://firebase.google.com/docs/firestore/security/get-started#writing_rules
If you setup rules to require your users to be signed in, you can use google auth to whitelist your domain. This will ensure only your users can view your data and also that it is only via your client. For more info in writing queries with rules applied, see this page https://firebase.google.com/docs/firestore/security/rules-query

How to sync CouchDB from multiple PouchDB in Angularjs?

I am working on an angular app. How I can make multiple PouchDB sync to a single CouchDB without any information loss?
You need to do replication by filter
Created filter in CouchDB for every client databases;
Start replication from CouchDB to client by filter (look at replication option named filter)
Start replication for all documents from client to CouchDB for every client database.
You can find everything you need here (examples 3, 4)
if you mean by creating multiple PouchDB instances, then you have to create their respective listener to each PouchDB instance pointing to the remote DB you want ( the CouchDB in question ).
this example for the listener worked for me:
var sync = PouchDB.sync('mydb', 'http://localhost:5984/mydb', {
live: true,
retry: true
}).on('change', function (info) {
// handle change
}).on('paused', function (err) {
// replication paused (e.g. replication up to date, user went offline)
}).on('active', function () {
// replicate resumed (e.g. new changes replicating, user went back online)
}).on('denied', function (err) {
// a document failed to replicate (e.g. due to permissions)
}).on('complete', function (info) {
// handle complete
}).on('error', function (err) {
// handle error
});

Categories