In this episode, we shall be taking a look at an emerging area known as Mobile Backend As a Service (mBaaS). The idea is that we shall be powered our Firefox OS Application from Server side infrastructure and functionality that shall be provided by the mBaaS Provider.
What we shall be doing is writing a Random Quotes Firefox OS Application. The Quotes are those said by famous men over the years. For e.g. Albert Einstein said “The difference between stupidity and genius, genius has its limits” and so on. All these quotes will not be present locally in the Firefox OS App local storage or database, it will in fact be delivered from a Server side solution. This will make it easier for us to update the Server side with data whenever we want.
- You have setup your machine with the Firefox OS Simulator. If not, you can check out Episode 1, which takes you through the entire setup.
- You have a basic understanding of writing Firefox OS Apps. If not, I strongly suggest to refer to earlier episodes, especially Episode 2, that covers how to write your first Firefox OS App.
What this Episode covers
- What is mBaaS, why it is important. Discussion of Kinvey, a leading mBaaS provider.
- Setup of the Random Quotes application on Kinvey.
- Sample Firefox OS Application that covers how demonstrates the integration with Kinvey. In other words, our Firefox OS application will be powered by Kinvey.
Episode 10 in Action
Let us check out the application in action first to understand what we are trying to do here.
What we shall write is a mobile application that shows us quotes made by famous personalities. We shall first show the list of famous personalities. When you select a personality, the quotes attributed to that person will be shown.
All right then, the first screen of the mobile app is shown below:
This screen shows the list of personalities. And when you click on a particular personality say “Albert Einstein”, you will see the quotes attributed to him as shown in the screen below.
Keep in mind that all data for this application is accessed from a hosted application that is running on the mBaaS Provider Kinvey’s infrastructure. We shall see how easy it is to focus on your mobile functionality and let the heavy duty work of a server side solution be taken care of by a provider like Kinvey.
The data is limited here, since I have just pulled some quotes from the Brainy Quotes site and populated my data store that is hosted on Kinvey.
Download Full Source Code – Episode 10
I suggest that you begin with a full download of the project source code. Since the project depends on libraries like jQuery and jQuery Mobile, it will save you the hassle of downloading the dependent libraries.
Go ahead & download the code from : https://github.com/rominirani/FirefoxOS-MBaaS
Extract all the code in some folder. For e.g. on my machine, the code is present in e:\firefox-os-blog\episode10\FirefoxOS-mBaaS but it could be any directory of your choice. You should see a folder structure inside of FirefoxOS-mBaaS, that looks something like this:
What is a mBaaS?
mBaaS stands for Mobile Backend As A Service. To give it some context, one of the challenges that most mobile developers face is that sooner or later, they have to create a common server side solution which can contain functionality for managing users, storing data in the cloud, etc.
For e.g. consider that you are writing a mobile game and you wish to track high scores across your different users. In such a scenario, you have no option but to centrally store user scores in some sort of a server side solution. This is all and good but what this means is that you have to now learn a server side stack and figure out how to write server side applications, host them and manage them. This takes away your focus as a mobile developer but it is not a problem that you can wish away. Typically there will be folks who are good on the Server side and they can help you with the development, but if you are familiar with only the mobile client side of things, chances are that you want to get quickly started with it, almost no coding and still get the best of breed server side solution.
This is exactly the spot that mBaaS providers want to address. They want you to focus on your application and its common needs on the Server side like users, authentication, data store to store application data and many such common services. All access of these services will be provided via a REST API or individual client side libraries that will wrap the calls and make it as easy as possible for you to invoke the operations in the cloud. The mBaaS providers also take the pain of hosting and running your site, so that is a great plus.
So to summarize, what we want to do with Kinvey at a high level is as follows:
- Create an Application. Lets call it RandomQuotes
- Use the Kinvey Datastore to create 2 Collections: Authors and Quotes. The Authors will contain the names of the famous personalities. And the Quotes will contain 2 key attributes, who said it and what they said. The who will be the Author name from the Authors collection.
- Load some sample data into the Kinvey Collections: Authors and Quotes.
The rest of the stuff is simply your client side functionality.
One point to note is that we have used Kinvey in the article but if you try out other mBaaS solutions, you will find that at a conceptual level, they do the same thing. I am not going to pit one against the other and which one is better. I just haven’t done detailed research to give that kind of data here. I signed up for Kinvey, found its process super smooth and everything worked as documented. That is what I look for in any external public facing API. The rest is just your functionality.
Setup Random Quotes on Kinvey
In this section, I am going to do my best to explain to you the process of signing up for Kinvey, creating your application and all the steps that we identified in the previous section.
The first thing you will need to do is sign up for Kinvey. Visit https://console.kinvey.com/ and sign up for the Service. You can go with the Free plan for the moment.
Once you have signed up successfully, you will be asked to create a new application. Go ahead and create it. My new application screen is shown below and you can use the same thing.
We shall be seeing this later on in the article, where the code will be explained in detail – so you need to worry about this for now.
Great – so we have signed up for Kinvey and we have created our application. The next thing we need to do is access the Datastore service of Kinvey and defined our two collections: Authors and Quotes. Along the way, we shall populate it also with some sample data.
Make sure that you are logged in to Kinvey. You will notice an icon in the corner and if you tap on it, it will show the list of applications. The RandomQuotes application should be visible in the list as shown below.
Just click on it and you will be led to the Application details. Now click on the Addons in the left top corner and you will see the different service shown to you as below.
Observe carefully and you should see the Data & Storage section as shown. Click on the Data Store on the right side. This will lead you to the Data Store Collections section. You will notice that at the start there are no collections defined and which is as expected. So we are going to define the collections: Quotes and Authors now.
Click on the +New button on the left pane and this will bring up a form where you will asked to define the New Collection as shown below. Notice that I fill it the name Quotes for the collection name. Click on Create Collection button. Similarly, create another collection named Authors that will contain records for the authors.
By default, the model for any collection that you define will contain standard meta-data that Kinvey defined like ID, etc. But we need to provide our own attributes to hold the application information.
So for Quotes, we want to create two additional attributes named who and what. The who will contain values for the Author name and the what will contain the value for the quote that they gave.
So, we have to define new columns for our collection. And this is done by visiting the Collections, click on the Quotes collection and you will see a +Col and a +Row button. Go ahead and click the +Col button in the screen below.
Once the fields are defined , we can enter some data for the Quotes. Simply tap on the +Row as shown below and enter some data for who and what. The other fields like ID, etc will be filled automatically.
Shown below is a screen that I populated for Quotes collection. I put in some 6 records. Do note that if you have large amounts of data, you do not need to populate the data manually. You can do it via the Bulk Operations button that you see on the right side. Via this operation, you can import comma separated files that you can export from your master system.
Once you have populated the records for Quotes, you should do the same for Authors also.
So – do the following steps:
- Define a new Collection named Authors
- Define an additional column for Authors named name. This will contain the name of the author and should match the different values that you have put in the who column in the Quotes collection.
- Enter some sample data for Authors in the same way.
This ensures that we have completed defining the Data Models for our applications and even populated them with some sample data.
Now, lets check if the data models are ready and that we can exercise some web based REST like API to retrieve our content. Kinvey makes this simple via the API Console.
To access the API Console, visit the Developer Tools link from your application as shown below. You will see the API Console link on the right pane.
This will bring up the API Console as shown below. And you can exercise your API right from here. For example, check out the screen below for the Quotes collection. You can simply tap on the Send Request button and a client side call will be made to your service. Notice the HTTP GET method getting fired.
Cool. We have everything in place now and have tested out our data service too. This means that all is set from Kinvey’s side and our server side application is up and running. Simple isn’t it? Now, all we need to do is write our client side Firefox OS application and access the data from the cloud. That is exactly what we shall cover next.
One thing to note is that you will need your APP_KEY and APP_SECRET, since that is how Kinvey will initialize connection to your application. Each of the applications created on Kinvey will be provided with the APP_KEY and APP_SECRET. You can access it from your Dashboard Setting as shown below:
This will lead you to a page that contains your APP_KEY and APP_SECRET. Copy them since you will need it in the next section.
Adding more data
Remember, anytime that you want to add more data to your Authors and Quotes collections, you can simply login to Kinvey, visit your App , visit the Data store service and manipulate your Data Models by entering the data manually or even importing exported files if you want.
OK. Lets get going with understanding the code and how we can integrate our RandomQuotes Application and access the data directly from the Kinvey powered Server side application.
FirefoxOS-mBaaS Application – manifest.webapp
The first thing we should discuss is the manifest file. This should be familiar now and it has the standard attributes like name, version, etc. There is nothing special happening here.
Note that since we will be making external calls to the Kinvey service, we need to mark the application as privileged and also to mention the permission for systemXHR so that outbound HTTP calls are permitted.
FirefoxOS-mBaaS Application – index.html
Next up is the index.html page and it is a simple jQuery Mobile page.
Let us discuss the index.html page in detail now:
- Next, we have included the our application script : app.js file. #Line 11
- We have 2 pages in the mobile application. The first page is the home (Line # 15) and the second page is quotespage (Line #28)
- The home page will show a list of Authors that will be retrieved from our backend service.
- A click on any Author will invoke the next service to retrieve the quotations that the Author has made and the results will be shown in #quoteslist unordered list element (#Line 34).
FirefoxOS-mBaaS Application – app.js
Let us discuss the source code in detail now.
- First thing to note is the standard jQuery Mobile pageinit function on Line#44. So when the index page is ready, we first just clear up the author List i.e. the list of authors.
- Next , we initialize the connection to the Kinvey service by invoking the mBaasInit() method on Line #48. We will come to the rest of the code in a while.
- The mBaasInit() method is defined on Line #4. It is standard boilerplate code that Kinvey provides. Basically what we are doing here is initialization the Kinvey connection via the Kinvey.init() method. Notice that you will need to substitute the value of YOUR_APP_KEY and YOUR_APP_SECRET with the respective values for your application. Once the initialization is good, we invoke the populateAuthors() method on Line #11.
- The populateAuthors() method is defined on Line #16. The key thing to note here is the Kinvey.DataStore.find method that we are using. The first parameter is the name of our Collection (in our case it is Authors). The second parameter is an optional Query parameter which we are not using here but will do later on. The Query parameter can be used to filter the results. The 3rd parameter is the success callback function that is provided the result. The result is an error of all the models in the Collection. And we simply iterate through it, extract out the information and display the authors in an unordered list element.
- Now, visit Line # 51, where we are enabling a click function on any of the list elements in the authorList unordered list. If there is a click, it will invoke the populateQuotes method and pass the label, which will contain the Author name.
- The populateQuotes method is defined on Line #28. It utilizes the Kinvey.Query object first and passes the criteria for filtering the Quotes by the who attribute. The value passed is that of the Author name, since we need to now retrieve only the quotes of that Author.
- The next call should be familiar now and the Kinvey.DataStore.find method is invoked. This time it is invoked on the Quotes collection, the Query filter is provided, which will give only those models whose who attribute has the value of the Author name selected. The 3rd parameter is once again the success callback method, where we iterate through the Quote records and populate it in the quotes variable. We then switch the page to the quotespage on Line #39.
- Finally, Lines # 55 – 60 iterate through the quotes global variable and populates the quotesList unordered list.
Local Installation and Testing
This completes our discussion of writing Firefox OS applications that is powered by a mBaaS. Now comes the part of seeing it actually work. All we need to test out this application is:
- You should have installed the Firefox OS Simulator add-on in your Firefox Browser.
- A working internet connection from your machine.
- You should have downloaded/written the application as described above. We will assume that the index.html and manifest.webapp file are present in a folder named FirefoxOS-mBaaS. You should navigate to your own directory structure when called to later.
Steps to install the application in your Firefox OS Simulator should be familiar to you now. Simply launch the Firefox OS Simulator in your Firefox Browser. From the Dashboard, click on the Add Directory button and point it to the manifest.webapp file for the FirefoxOS-mBaaS application. On successful validation, the application will be installed and it will come up in your OS Simulator. For sample screenshots, refer to the section at the beginning of this blog post for Episode 10 in Action.
Till the next episode, stay tuned and give me feedback.
Complete Firefox OS Tutorial
- Episode 1 : Setting up your Development Environment
- Episode 2 : Hello World
- Episode 3 : Working with the OS Simulator
- Episode 4 : Submitting your Application to the Firefox Marketplace
- Episode 5 : Location, Location, Location
- Episode 6 : Enabling Storage
- Episode 7 : Storage using IndexedDB
- Episode 8 : Using Web Activities
- Episode 9 : Device Storage
- Episode 10 : Using mBaaS
I would love to hear your feedback on the series so far. Do put your feedback in the comments. If you are facing issues, use the comments to let me know about it, I will do my best to answer your queries. And by putting in your issues within this thread itself, it will help build collective knowledge that could help other readers.