Posted on by

Welcome back to the new blog from our “Learn Firebase: The Data Engineer Way” series !! Hope you were looking forward to this. Happy Learning…

In previous blog, we have learned basic CRUD operations on Firebase using Angular4. In this latest blog, we will cover some important aspects of Firebase like Firebase joins and corresponding data model for joins. We will also cover transactions so as to run atomic update on data fields.

In this blog post, we will learn to develop two features of our inventory app – Request & Approve.

Mockups

Request Item

Approve Item

Data Model

Request page will be rendered from items. When user will request a particular item, we have to keep an entry. As Firebase is NoSQL database, there could be more than one way to store request entry.

One option could be to add request json under requested item itself. This would make

our item object larger if there are many request for a particular item and also it will add one level of nesting which is not recommended in Firebase.

Other option could be to add request json in separate $ref and embed item object. In this

approach, we have to duplicate item object in every request and if admin edits metadata of any item then changes have to be propagated to every request object.

Another option could be similar to option 2 except instead of embedding whole object, we only embed itemId($key) in request object. With this, even if admin makes an update in item metadata we don’t have to change anything in request objects. In first two approaches, we don’t have to join/lookup value but this approach has introduced join. Let’s look at data model for this approach.

itemId: string #$key

email: string #emailid of requested user

quantity: number #for now, it will be default 1

status: string #{new,approved}

When user makes a request for an item, entry should be added in request $ref and status would be new. If admin approves the request status should become ‘approved’ and in case of decline, entry should be removed from database.

Typescript Object

Below is typescript object based on data model.

export class Request { public $key: string; constructor(public email:string, public itemId:string, public quantity: number, public status: string){} }

Request Page

Let’s implement request page first.

request.component.html

<div class="container"> <div class="row" > <table class="table table-stripped table-hover"> <thead> <th>Key</th> <th>Name</th> <th>Serial Number</th> <th>Available Items</th> </thead> <tbody> <tr *ngFor="let item of itemList; let i=index"> <td>{{ item.$key }}</td> <td>{{ item.name }} </td> <td>{{ item.serialNum }}</td> <td>{{ item.totalItems }}</td> <td><button type="button" class="btn btn-warning" (click)="onRequestItem(item.$key)">Request</button> </tr> </tbody> </table> </div> </div>

Just a html boilerplate code.

request.component.ts

export class RequestComponent implements OnInit { itemList: Item[] = []; constructor(private inventoryService: InventoryService, private authService: AuthService) { inventoryService.getAllItems().subscribe( data => this.itemList = data ) } ngOnInit() { } onRequestItem($key: string) { let request = new Request(this.authService.getEmail(),$key,1,'new'); this.inventoryService.requestItem(request); } }

inventory.service.ts

requestItem(request: Request) { this.requests.push(request); }

Lets run the updated app using angular-cli command ng-serve.

Go to request screen and request any item.

Once you click on request, request entry will be added in request $ref. You can check that from Firebase console.



Approve Page

Implementation of this page will be little bit tricky because to show data on page we have to join items $ref and requests $ref. As there is no inbuilt join functionality available in Firebase like traditional databases such as MySQL, we have to implement it at application level.

First we will implement service and then html and associated typescript code.

inventory.service.ts

getItemsByStatus(status: string) { const queryList$ = this.db.list('/requests', { query: { orderByChild: 'status', equalTo: status } }) return queryList$.map( requestList => requestList.map(request => this.db.object('items/' + request.itemId) .map((item) => { return new RequestItem(request as Request, item as Item) } ))) .flatMap(fobjs => Observable.combineLatest(fobjs)); }

Above code will first fetch all request with given status (e.g. ‘new’) and then for every return request, look for corresponding item object from $ref using $key of item and create a new joined object RequestItem. Finally it packages result using flatmap.

approve.component.ts

export class ApproveComponent implements OnInit { requests$: Observable<RequestItem[]> ; constructor(private inventoryService: InventoryService) { this.requests$ = inventoryService.getItemsByStatus('new'); } ngOnInit() { } }

approve.component.html

<div class="container"> <div class="row" > <table class="table table-stripped table-hover"> <thead> <th>Key</th> <th>Name</th> <th>Available Items</th> <th>Requested Quantity</th> <th>Requested By</th> </thead> <tbody> <tr *ngFor="let req of (requests$ | async)"> <td>{{ req.item.$key }}</td> <td>{{ req.item.name }} </td> <td>{{ req.item.totalItems }}</td> <td>{{ req.request.quantity }} </td> <td>{{ req.request.email }} </td> <td><button type="button" class="btn btn-primary" (click)="inventoryService.approveItem(req)">Approve</button> <td><button type="button" class="btn btn-danger" (click)="inventoryService.declineItem(req.request.$key)">Decline</button> </tr> </tbody> </table> </div> </div>

Refresh the app, you will see approve page.

Let’s implement approveItem and declineItem methods in inventory service.

invenntory.service.ts

approveItem(req: RequestItem) { this.db.object('requests/' + req.request.$key + '/status').set('approved').then this.db.object('items/' + req.item.$key + '/totalItems').$ref .transaction(quantity => { return quantity-req.request.quantity } ); } declineItem($key: string) { this.requests.remove($key); }

Logic for approve item would be to first make status of request from ‘new’ to ‘approved’ and then reduce quantity by requested quantity. We have used transaction so that quantity should be updated atomic way in case of many user approving request referring to same item.

That’s it, we have implemented all needed features. There is still some work to be done to make our app robust.

Hope this blog help you understand Firebase joins and implement it. Please do write to us in below comment section in case of any queries.

In next blog we will explore security rules and indexes.