How data is structured in a JSON tree

In Firebase Realtime Database, all data is stored as JSON objects, which is a cloud-hosted JSON tree. When we add data to the database, it becomes a node in the existing JSON structure with an associated key, which is autogenerated by Firebase. We can also provide our own custom keys, such as user IDs or any semantic names, or they can be provided using the push() method.

For example, in our Helpdesk Application, we are storing the tickets at a path, such as /helpdesk/tickets; now we'll replace this with /helpdesk/tickets/$uid/$ticketKey. Take a look at the following code:

var newTicketKey = firebase.database().ref('/helpdesk').child('tickets').push().key;
// Write the new ticket data simultaneously in the tickets list and the user's ticket list.
var updates = {};
updates['/helpdesk/tickets/' + userId + '/' + newTicketKey] = data;
updates['/helpdesk/tickets/all/'+ newTicketKey] = data;

This is how data structure looks for creating and retrieving the tickets from the database:

In the preceding image, the highlighted node is $uid, which belongs to the user who has submitted the ticket.

This is how our full code looks:

var newTicketKey = firebase.database().ref('/helpdesk').child('tickets').push().key;
// Write the new ticket data simultaneously in the tickets list and the user's ticket list.
var updates = {};
updates['/helpdesk/tickets/' + userId + '/' + newTicketKey] = data;
updates['/helpdesk/tickets/all/'+ newTicketKey] = data;

return firebase.database().ref().update(updates).then(()=>{
ToastSuccess("Saved Successfully!!");
this.setState({
issueType:"",
department:"",
comment:""
});
}).catch((error)=>{
ToastDanger(error.message);
});

Open the browser and submit the ticket again; now look at the ticket dashboard:

It looks great! Now the user can only see the tickets they have submitted. In the next chapter, we'll see how we can apply security rules and common security threats in our data in the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset