Firebase tutorial by example – building a mobile application

No Comments

Any mobile application should be able to handle offline situations gracefully. After all, we have all felt the frustration you experience when the E on your phone goes to a G, or that dreaded X. Yet for many application, access to some database is critical. Firebase is an offline-capable general-purpose database for mobile applications. What this means is that even if you lose internet access, the app will still work correctly, unlike one written in a more traditional client/server model. Instead of directly replicating your data to the backend, your local copy of the database will be modified. Once connectivity returns, firebase consolidates your local copy with the cloud. In this firebase tutorial, we build a small app to showcase how to use this database in a simplified real-world scenario.

Our example application is a simple time tracking tool for remote workers. An example would be a carpenter or other craftsmen. These workers need to document their time, but are often faced with shaky or non-existing internet access. We want to implement a mobile app that allows these workers to go on and off duty at the press of a button. Usually, an easy solution to this might be a REST client/server architecture, this fails in offline scenarios. Instead, we devise a schema to store the data using firebase. Firebase offers a very solid, offline capable database that can be used when connectivity is a scarce resource.

Key Firebase features

Firebase structures itself as a tree of collections and documents. A collection contains documents, and a document can contain fields and collections. We can read, write and edit documents by their path. The structure is always strictly alternating – a document always has collection children, and a collection always has document children.

Illustration of a firebase document path

For each element in a firebase database, you can define access control rules. These rules define who can see and alter what parts of the database. The firebase server enforces these rules. Rules can allow reads, modifications or adding new documents to a collection. The rules can depend on request data (such as the user ID), the current contents of the document, and even make queries to other parts of the database.

Finally, it is possible to subscribe to documents and collections in firebase. A subscription means that an application will be notified on every change of that resource. If you subscribe to a collection, you will be notified of new or changed document. Similarly, if you subscribe to a document the subscription notifies you about any changes to its fields.

These three key features allow us to design our firebase tutorial application. There are more features including deep analytics and management functions. They are not part of this tutorial.

The big idea

With these three key features, we are ready to design our firebase tutorial app. Each user will receive a subtree of the overall database to store their data. The worker can not act outside this subtree at all. Inside this subtree, they have some degree of access. Inside the tree, we will collect Booking objects. Each such object defines one time-tracking related event – such as beginning or ending a work period. Such events are write-once. They can be appended to a collection, but never deleted or altered. This means we do not need to handle potential update conflicts – every object eventually ends up in a consolidated collection.

Some users may have multiple devices – so we cannot assume to know the full truth. The data model may change even after the application has loaded and feels in control. Thus, we place the subscription function in the center of our architecture. We subscribe to the booking collection, and display it to the user. Any changes we make will take the form of additional bookings. They are added to the model – which triggers a notification on the subscription. Thus, the UI always represents the most current view of the overall collection.

Since this article is a firebase tutorial focusing on mobile applications, we do not elaborate on the server-side processing a real application would probably include. If you are familiar with NoSQL databases, you are probably not going to find it challenging to imagine how to generate monthly reports, apply legal break requirements and so on.

Data model

We decided to do an event-based data model to leverage the offline capabilities of firebase. For the purpose of our firebase tutorial, we define three entities.

Data model

This model ties three entities together in a subtree of the firebase firestore. The user object itself stores user configuration (such as the current company context). It serves as the user preferences. The bookings collection aggregates all bookings. It allows reads and inserts, but blocks updates. The memberships collection permits user reads, but neither inserts nor modifications – otherwise the user would be able to add itself to any company. A privileged server component manages this collection instead.

When the application starts, it initializes the firebase firestore, and subscribes to the user document itself, and the two component collections. As soon as these resources have been loaded, the application receives notifications that data is available. It can then start to display that data to the user.

Our whole approach focuses on subscriptions. Each subscription is functionally an event source – so a listener-based solution offers itself. We perform all our processing and updates in the form of listeners on an event. Potentially these listeners can emit events of their own. Any change to the data model produces an event cascade that ultimately reaches the UI. We have a simple, well-understood mechanism which (as a side benefit) does not require blocking queries or asynchronous loading.

We can easily apply this pattern to all aspects of the application. The same mechanism powers the user switching their selected company, new events becoming available from another device, and even new companies becoming available for booking.

Firebase Security Rules

In our data model, we laid out some restrictions that the application user needs to obey.

  • Every user may freely read and write their user document (/users/{uid})
  • They may add bookings to their booking collection (/users/{uid}/bookings), and read it.
  • They may read their company memberships (/users/{uid}/memberships), but not alter them.

Firebase offers a comprehensive security rule language. It is relatively straightforward to express these rights and constraints in this language:

Since the database enforces these constraints, we can freely utilize the data on the client – even if a person tried to falsify their local copy of the database, their updates would be rejected.

For developing and flight-testing security rules, the simulation environment provided as part of the firebase admin interface is invaluable. It allows to simulate different access attempts, and gives feedback which rules caused the attempt to succeed or fail respectively. You can find it in the firebase admin console, under the “database” heading.

Firebase console example

Tying our firebase tutorial together

To conclude our firebase tutorial, we briefly touch some other points that need to be addressed. The data model is well and good from a technical point of view. It is, however, not user-friendly. A user probably does not want to deal with individual start and end events. They want to know if the system has correctly identified them as having started working at 08:11 and finished at 17:09. Fortunately, this is relatively easy to accomplish in our event-driven model.

As we tacitly assumed in the security rules section, each user has their own identity when interacting with firebase. Firebase supports a number of providers, such as Google, Apple, and Facebook. Take a look at the list of supported providers, and pick one that works for your project. For this firebase tutorial, we limit ourselves to email/password, but a full app will likely want to support the platform providers at the very least.

A fully-functional version of the example app can be found on github. Please take a look and tell us what you think.

Do you have any experience to share? Please comment and let us know.

Avatar

Elisabeth Schulz turned a lifelong passion for computers into a career. She is most comfortable living beneath the surface, making sure things “work just right”. Her interests include functional programming and microservices.

Comment

Your email address will not be published. Required fields are marked *