Getting fired up with Firebase Database


Well, this is where Firebase comes to the rescue one more time!
 lets get started with this.

Step 1 :

Add your project to Firebase from the console.


Click on the Blue button

Step 2 :

Add Firebase to your webapp
Open the project, you’ve just created and click on the bright red button that says, “ Add Firebase to your web app”



Copy the contents from here and paste it after your HTML code.

Step 3 :

Next up, navigate to the Database section in your console and move to the Rules tab.



For now, let us edit the rules to allow anyone to read and write to the database.



Almost all set up now.

Step 4 :

Modify the HTML to allow entering data by the user
<form name="htmlform" id="form" enctype="multipart/form-data">
  <p align="center"><b><big>FOSSASIA's App Generator</big></b></p>
  <table align="center"
  width = "900px"
  height="200px">
  <tr>
   <td valign="top">
    <label for="Email">Email</label>
  </td>
  <td valign="top">
    <input id="email" type="email" name="Email"  size="30">
  </td>
  <td>

   <td valign="top">
    <label for="name">App's Name</label>
  </td>&nbsp;
  <td valign="top">
    <input id="appName" type="text" name="App_Name" maxlength="50" size="30">
  </td>&nbsp;

</tr>
<tr>
 <td valign="top">
  <label for="link">Api Link</label>
</td>
<td valign="top">
  <input id="apiLink" type="url" name="Api_Link" maxlength="90" size="30">
</td>
</tr>

<tr>
  <td valign="top">
    <label for="sessions">Zip containing .json files</label>
  </td>
  <td valign="top">
    <input accept=".zip" type="file" id="uploadZip" name="sessions">
  </td>
</tr>
<tr>
 <td colspan="5" style="text-align:center">
  <button type="submit">Generate and Download app</button>
</td>
</tr>
</table>
</form>
This looks something like this :



Now let us setup our javascript to extract this data and store this in Firebase Database.
<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
  var $ = jQuery;
  var timestamp = Number(new Date()); //this will server as a unique ID for each user
  var form = document.querySelector("form");
  var config = {
    apiKey: "API_KEY",
    authDomain: "app-id.firebaseapp.com",
    databaseURL: "https://app-id.firebaseio.com",
    storageBucket: "app-id.appspot.com",
  };
  firebase.initializeApp(config);
      var database = firebase.database();
      form.addEventListener("submit", function(event) {
        event.preventDefault();
        var ary = $(form).serializeArray();
        var obj = {};
        for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
          console.log("JSON",obj);
        var file_data = $('#uploadZip').prop('files')[0];
        var storageRef = firebase.storage().ref(timestamp.toString());       
        storageRef.put(file_data);
        var form_data = new FormData();                  
        form_data.append('file', file_data);                           
        firebase.database().ref('users/' + timestamp).set(obj);
        database.ref('users/' + timestamp).once('value').then(function(snapshot) {
        console.log("Received value",snapshot.val());
        )};
      });
    </script>
We are almost finished with uploading the data to the database.
Enter data inside the fields and press submit.
If everything went well, you will be able to see the newly entered data inside your database.



Now on to retrieving this data on the server.

Our backend runs on a python script, so we have a library known as python-firebase which helps us easily fetch the data stored in the Firebase database.
The code for it goes like this
firebase = firebase.FirebaseApplication('https://app-id.firebaseio.com', None)
result = firebase.get('/users', str(arg))
jsonData = json.dumps(result)
email = json.dumps(result['Email'])
email = email.replace('"', '')
app_name = json.dumps(result['App_Name'])
app_name = app_name.replace('"', '')
print app_name
print email
The data will be returned in JSON format, so you can manipulate and store it as you wish.
Well, that’s it!
You now know how to store and retrieve data to and from Firebase.
It makes the work a lot simpler as there is no Database schema or tables that need to be defined, firebase handles this on its own.

Comments

Popular posts from this blog

Documentation is Very vital before you develop any system or app

Everything you need to know when developing an on demand service app

Steps followed when creating a new software