ReallySmallSoftware / cordova-plugin-firestore

A Google Firebase Firestore plugin to enable realtime synchronisation between app and cloud and automatically handle limited connectivity.
Other
22 stars 10 forks source link

Troubles with Basic Example #13

Open luigi37 opened 5 years ago

luigi37 commented 5 years ago

Expected Behavior

I expect any of the console messages from the basic example

Actual Behavior

I get error Uncaught (in promise) TypeError: db.collection is not a function at lp.js: xxxx at

Steps to Reproduce the Problem

Used this code. Plugin version is 1.3.2

function onceLoaded() { console.log('aaa');

    var options = {
            "datePrefix": '__DATE:',
            "fieldValueDelete": "__DELETE",
            "fieldValueServerTimestamp": "__SERVERTIMESTAMP",
            "persist": true,
            "timestampsInSnapshots": true,  // <-- set true
            "config": {}
        };

    console.log("cordova.platformId: "+cordova.platformId);

    if (cordova.platformId === "browser") {
        options.config = {
            apiKey: "my_apy_key",
            authDomain: "localhost",
            projectId: "my_project_id"
        };
    }

    Firestore.initialise(options).then(function(db) {
    // Add a second document with a generated ID.
        db.collection("users").add({
            first: "Alan",
            middle: "Mathison",
            last: "Turing",
            born: 1912
        })
        .then(function(docRef) {
            console.log("Document written with ID: ", docRef.id);
        })
        .catch(function(error) {
            console.error("Error adding document: ", error);
        });
    });   

} var app = { // Application Constructor initialize: function() { document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); },

// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
    this.receivedEvent('deviceready');

    onceLoaded();
},

// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
}

};

app.initialize();

Specifications

luigi37 commented 5 years ago

Any suggestion? A small working example would work.... I'm not sure if it's a problem with the plugin or maybe something is missing in my setup. Maybe I need to load in index.html the firebase and firestore javascript libraries?

ReallySmallSoftware commented 5 years ago

Sorry - pretty swamped at the moment!

Have had a look at a working app and I think you need to try this:

db.get().collection("users").add({
            first: "Alan",
            middle: "Mathison",
            last: "Turing",
            born: 1912
        })

ie add the get()

Are you running this in the browser or on a device?

Do let me know how you get on and I will update the docs.

luigi37 commented 5 years ago

Thanks a lot Error happens on both "browser" platform and on android app loaded on a mobile. I will try and report

luigi37 commented 5 years ago

Yes, it works! At least on "browser" platform (tomorrow I will try in Android app)

Two things:

1- I had to modify the index.html header like this to allow calls to google js lib:

 <meta http-equiv="Content-Security-Policy" content="
            default-src 'self' *.googleapis.com data: gap:
                https://ssl.gstatic.com;
            script-src 'self' 'unsafe-inline' 'unsafe-eval'
                https://*.gstatic.com https://*.googleapis.com;
            style-src 'self' 'unsafe-inline';
            media-src *;
            connect-src *
        ">

2- The call needs the get:

db.get().collection("users").add({
luigi37 commented 5 years ago

Same code on Android gives error:

Attempt to invoke virtual method 'com.google.firebase.firestore.CollectionReference com.google.firebase.firestore.FirabseFirestore.collection(java.lang.String)' on a null object reference

luigi37 commented 5 years ago

Ok, worked also in Android (no chance at the moment to test iOS) following the suggestion in https://github.com/ReallySmallSoftware/cordova-plugin-firestore/issues/11#issuecomment-453435050

So the readme could be update to include the head tag as my above comment:

<meta http-equiv="Content-Security-Policy" content="
           default-src 'self' *.googleapis.com data: gap:
               https://ssl.gstatic.com;
           script-src 'self' 'unsafe-inline' 'unsafe-eval'
               https://*.gstatic.com https://*.googleapis.com;
           style-src 'self' 'unsafe-inline';
           media-src *;
           connect-src *
       ">

And code would become (I've put alert in place of console.log just for easiness with App messages):

var options = {
    "datePrefix": '__DATE:',
    "fieldValueDelete": "__DELETE",
    "fieldValueServerTimestamp" : "__SERVERTIMESTAMP",
    "persist": true,
//  "config" : {}
};

if (cordova.platformId === "browser") {
    options.config = {
        apiKey: "my_api_key",
        authDomain: "localhost",
        projectId: "my_projectid"
    };
}

Firestore.initialise(options).then(function(db) {
// Add a document with a generated ID
//db.collection("users").add({
db.get().collection("users").add({    
        first: "Antonio",
        middle: "Santi",
        last: "Meucci",
        born: 1808
    })
    .then(function(docRef) {
        alert("Document written with ID: "+ docRef.id);
    })
    .catch(function(error) {
        alert("Error adding document: "+ error);
    });
});

Note that I've commented out (removed) config{}: with this the code works both in browser and app.

Thanks if someone could test on iOS.

Also, I have a question: once removed the browser option (and the apiKey) is it correct that only the specific app can read the data, or anyone with the json file can create an app that use my Goole Firebase quota?

Thanks

gabrielpotumati commented 5 years ago

I tried all the suggestions and it did not work, does anyone have any idea to try to make it work?

I have this error: Error adding document: Attempt to invoke virtual method 'com.google.firebase.firestore.CollectionReference com.google.firebase.firestore.FirebaseFirestore.collection(java.lang.String)' on a null object reference

ReallySmallSoftware commented 5 years ago

I will try and test this. I am going to be working on the plugin soon.

As for the access to the data, this will work in association with firebase authentication and you can add rules to firestore to ensure only authenticated users can access the data. Note this is authentication and not authorization which is something you would need to implement once you are happy the authenticated user is who they say they are.

bazuka5801 commented 3 years ago

@luigi37 @gabrielpotumati I intersects with this problem, check #28 issue, we need remove empty "config" key from initialization object.