Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NoSQL and Server-less Example with Google Firebase and Shield UI Grid

Introduction

NoSQL databases provide a storage and retrieval approach, different from the relational model, offered by SQL. There are many open-source and proprietary NoSQL engines, free and commercial web services, which provide functionalities for storage, easier scalability and faster access. These types of databases are suitable for storing heterogeneous and even unstructured data, making them ideal for the mobile and IoT world.

In this tutorial you will create a NoSQL Document-Store database on Google Firebase and manipulate it by using a client-side data-grid component, part of the Shield UI JavaScript library. In the last part, you will be asked to enhance your project by completing several tasks. Firebase documentation can be found here and Shield UI demos and docs can be found here.

I. Creating the Database

Go to https://firebase.google.com/ and Sign In (register if you need) with your account. Then click on the Go to console link to visit the Firebase Console (https://console.firebase.google.com/).

Create a Project, choosing any name you prefer.

From the console's navigation pane, select Database, then click Create database for Cloud Firestore. Select Start in test mode and click Next. Optionally change the location and click Done.

Firebase stores data in Documents, which are stored in Collections. From the Database page, create a collection called users (lower-case).

Create 2 documents in the users collection – click the + Add document link and the following documents (note the different fields). Leave the Document ID to empty.

II. Developing the Client-side Code

The next step is to create a web page, which retrieve and display, as well as allow management of your Firestore users collection.

Create an HTML page on your desktop (e.g. firebase.html) and add the following skeleton structure:




    Shield UI / Firebase

Now you can drag and drop the firebase.html file in Firefox, so you can quickly test any change you make to it.

The next step would be to include the Firebase and Cloud Firestore libraries, plus the jQuery and Shield UI libraries to your page. Add the following Code in your page’s section:


The next step is to add the code that initializes the Cloud Firestore through the Firebase API. To access this Firebase data store from a web browser (using JavaScript), you will need to know your Project’s ID. To get it, you can go to the Firebase Console, click the cog icon next to Project Settings item in the left menu and go to Project Settings.

Add the code to initialize the Firestore API client in JavaScript. Paste the following code in the beginning of the tag in your page’s body, replacing PROJECT_ID with your project’s ID:

// Initialize Cloud Firestore through Firebase
firebase.initializeApp({
    projectId: 'PROJECT_ID'
});
var db = firebase.firestore();

From this moment on, you can access the database through the global JavaScript variable called db.

The last thing to add to the page is the data grid, which will display and allow management of the Firebase data. The data grid will be rendered inside the already-inserted

element with id="grid", using the ShieldUI’s Grid widget. Shield UI follows the jQuery plugin architecture, and hence depends on it. So, all of its code should be wrapped in a jQuery() closure, so that it is executed when the web page’s DOM has been fully loaded. The grid initialization and configuration code is based on this demo.

Add the code to initialize a Grid component which will connect to Firestore and read data from it. In the end of the tag in your page body, add this jQuery closure and code:

// initialize the ShieldUI Grid widget
jQuery(function($) {
    $("#grid").shieldGrid({
        dataSource: {
            remote: {
                read: function(params, success, error) {
                    // read the items in the users Firestore collection
                    // https://firebase.google.com/docs/firestore/quickstart#read_data
                    db.collection("users").get().then(function(querySnapshot) {
                        var items = [];

                        // collect all data items returned from the database
                        querySnapshot.forEach(function(doc) {
                            var data = doc.data();
                            data.id = doc.id;
                            items.push(data);
                        });

                        // pass the data to the Grid by calling the success callback
                        success(items);
                    });
                },
                modify: {
                    create: function(items, success, error) {
                        // TODO
                    },
                    update: function(items, success, error) {
                        // TODO

                    },
                    remove: function(items, success, error) {
                        // TODO
                    }
                },
                schema: {
                    fields: {
                        id: { path: "id", type: String },
                        firstName: { path: "firstName", type: String },
                        middleName: { path: "middleName", type: String },
                        lastName: { path: "lastName", type: String },
                        company: { path: "company", type: String },
                        department: { path: "department", type: String }
                    }
                }
            },
            sorting: true,
            rowHover: false,
            editing: {
                enabled: true,
                type: "row"
            },
            columns: [
                { field: "firstName", title: "First Name" },
                { field: "middleName", title: "Middle Name" },
                { field: "lastName", title: "Last Name" },
                { field: "company", title: "Company" },
                { field: "department", title: "Department" },
                {
                    width: 160,
                    title: " ",
                    buttons: [
                        { commandName: "edit", caption: "Edit" },
                        { commandName: "delete", caption: "Delete" }
                    ]
                }
            ],
            toolbar: [
                {
                    buttons: [
                        { commandName: "insert", caption: "Add User" }
                    ],
                    position: "top"
                }
            ]
        }
    });
});

Make sure you do not miss any closing parenthesis/braces and keep the nesting of the JavaScript properties intact. Refreshing the page (with Ctrl + F5) at this point should result in something like this:

Adding an entry to the users collection in the Firebase console and refreshing the page, should refresh the table and cause all new entries to be shown.

Now let’s add the code that will allow creating new entries. The Shield UI Grid widget will do all the rendering of inputs, optional validation and etc, and will finally pass the data to the handler function specified in the dataSource.remote.modify.create property. The only thing you need to do is take the newly added objects and pass them to your data source – in this case, a remote Firebase data store. Add the following code in the body of the create callback:

// only one item is created in non-batch mode, so get it
var newItem = items[0].data;

// construct a new entry to add to Firebase, containing only non-empty keys
var entry = {};
$.each(["firstName", "middleName", "lastName", "company", "department"], function(i, key) {
    if (newItem[key]) {
        entry[key] = newItem[key];
    }
});

// add the entry to the users Firebase collection
// https://firebase.google.com/docs/firestore/quickstart#add_data
db.collection("users").add(entry)
    .then(function(docRef) {
        // save the newly created document's id to the Grid item
        newItem.id = docRef.id;
        success();
    })
    .catch(error);

The above code will take the data of the first (and only) newly created item, filter all non-empty properties (making sure no empty keys are sent to Firestore) and will add it as a new document to the users collection. Right after the new document is added, the Firebase API will execute the callback in the then() function (see JavaScript promise objects for more details about this pattern), in which we save the returned id back to the item object (so we can reference it later when updating/deleting it).

Try to test the create functionality by clicking the Add User button on top of the Grid and see if the new document will appear in the Firebase Console.

III. Additional Features

In order to practice the acquired knowledge, you can try to implement the following tasks:

Task 1. Implement the delete functionality by adding the code in the dataSource.remote.modify.remove callback. The id of the item being deleted can be accessed through items[0].data.id, and the call you will need to make to Firebase is described here.

Task 2. Implement the update functionality by completing the dataSource.remote.modify.update callback. The information about the updated object can be accessed via items[0].data and before sending it to Firestore, you need to exclude empty keys (check the implementation of the create method above). To update an existing Firestore document, use this API.

Tags: 
DataSource, Grid, NoSQL

Blog Categories

  • General
  • Showcase
  • Technical
  • White Papers
Sub Title: 


Vladimir Georgiev, May 2020
Computer Science Department, American University in Bulgaria

Sub Title Background: 


This post first appeared on Shield UI Blogs | Shield UI, please read the originial post: here

Share the post

NoSQL and Server-less Example with Google Firebase and Shield UI Grid

×

Subscribe to Shield Ui Blogs | Shield Ui

Get updates delivered right to your inbox!

Thank you for your subscription

×