Sunday, October 29, 2017

Firebase Real Time Database for Web App

1) Create a Firebase project

- Create a firebase Project at https://console.firebase.google.com
- Go to Project Overview -> Click "Add firebase to your webapp"
- It will open a popup and you will find apikeys and endpoints as per your project settings.
- You will use this data in your frontend html file that will connect to firebase.
- Go to Database -> Rules and update the content as following

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This will allow anyone to read and write to the database. Its only for testing purpose. In actual production app you can see more complicated rules. You must not do this for your production app.

2) Checkout the following frontend demo app from github.

https://github.com/fullstacktechnos/firebase-frontend

- I am using node.js as local server to serve the page. If you want to use node.js then please check the following article:

http://www.fullstacktechnos.com/2017/10/serving-static-file-using-nodejs-and.html

- I have a single page called index.html and a config file called firebaseconf.js inside public. Config file has all dummy data. You have to replace with your actual project configs.
- Open the firebaseconf.js inside public folder.
- Add the firebase initialization code.

  // Initialize Firebase
  var config = {
    apiKey: "bjfuawfbajbawfbawawfbfawbbawflf",
    authDomain: "testproject.firebaseapp.com",
    databaseURL: "https://testproject.firebaseio.com",
    projectId: "testproject",
    storageBucket: "testproject.appspot.com",
    messagingSenderId: "123456789123"
  };
  firebase.initializeApp(config);

* I have added all dummy data. Please use the actual data in your project.  

- Open the index.html and check the following code.

Send data to Firebase

                             //Send data to DB
            $("#sendmsg").click(function() {
                var content = $("#content").val();
                if (!content) {
                    return console.log('No content');
                }
                $("li").remove();
                var ref = firebase.database().ref('messages');
                var data = {
                    type: 'Generic',
                    description: content
                }
                ref.push(data);
            });


- In the above piece of code I am getting the message text from the html element (with id 'content') and sending it to the firebase when user clicks on the button (with id 'sendmsg'). Check the elements in the index.html.
- firebase.database().ref('messages') will get the database reference. Create the payload and send it to the firebase realtime db with ref.push(payload).

- Once message sent successfully go to firebase console. https://console.firebase.google.com
- Inside your project, go to Database.
- Check the messages.
- You will find the new message inside uid with your given content in description.


Getting data from Firebase

- You need to listen to the database event in your frontend webapp to get db updates.
- Check the following code.

                            //Read Data
            var ref = firebase.database().ref('messages');
            ref.on('value',function(result) {
                var messages = result.val();
                if (messages) {
                    $("li").remove();
                    keys = Object.keys(messages)
                    keys.forEach(function(key) {
                    console.log('Type :' + messages[key].type + ' :: Content :' +  messages[key].description);
                    $("#messagelist").append('<li class="singlemsg">' + messages[key].description + '</li>');
                    });
                }
            }, 
            function(error) {
                console.log(error);
            });


* If you have not checked out the code from git then please don't worry about dom manipulation code written above. Just ignore them.


- Get the reference of the database and call ref.on. It will be invoked whenever there is a db insert or update on messages. Get the result and show to the user.
- You can notice as soon as you send the message to firebase it will be displayed in the page.


Note :

For more info please visit firebase official documentation link given below.
https://firebase.google.com/docs/database/web/start

To know more about firebase and cloud functions please find the below articles:
1) http://www.fullstacktechnos.com/2017/10/firebase-authentication-service-for-web.html
2) http://www.fullstacktechnos.com/2017/10/why-we-need-firebase-cloud-functions.html
3) http://www.fullstacktechnos.com/2017/10/introduction-to-cloud-functions-for.html

No comments:

Post a Comment