Firebase firestore in the forum application #7: Store user data in forums and Firebase admin

in #utopian-io5 years ago

Repository

https://github.com/firebase

What Will I Learn?

  • Store user data in forums
  • Firebase admin( setting in Node.js and Get data from forums)

Requirements

  • Basic Javascript
  • Install Firebase

Resources

Difficulty

Basic

Tutorial Content

Hi everyone, I will still continue with the previous firebase tutorial series on forum applications. In this tutorial, we will complete the features that we have made before. as you have seen before, we have created some auth with social media and learned the Cloud firestore. In this tutorial we will learn what is meant by firebase admin. so for those of you who are just following this tutorial, you should follow the curriculum below.

Access user data

In the previous tutorial, We have created a forums collection that we use to store forum data well from the data that we store in the forum there is still incomplete data. The data is the data of the user who created the forum. for more details, we can look at the database in our cloud firestore. like the picture below:

Screenshot_3.png

As I said above on our database, it doesn't have data on the user who created the forum, so we can use the onAuthStateChanged ()function.

  • Use onAuthStateChanged to store user data

We can use the functions provided by firebase.auth(). The function is onAuthStateChanged (). This function will automatically be triggered when data changes on auth. We can see examples of its use in the application that we are making like the following:

auth.js

var currentUser = null; // defined a variable as null
auth.onAuthStateChanged(function(user){ //get user data in parameter user
    if (user) {
        currentUser = user // store user data to variable currentUser
    }
});

The use of this function is quite easy, we can call it by creating a firebase.auth () instance first. I have made the installation like the following var auth = firebase.auth();. I save it on an auth variable, so you can use that variable as an instance.

onAuthStateChanged() This function will respond to restore the data of the user who is currently logged in. to test it we can do console.log (user) and we can see the results as shown below:

ezgif.com-video-to-gif.gif

As we saw in the picture above we have succeeded in getting user data. Now we can store user data in our collection of forums. The user data that will be stored is an object. For more details we can see in the example below:

  • Store user data

In this section we will add user data to the collection forums, where the user data that we will store is in the form of an object. For more details, we can see in the example below:

auth.js

var currentUser = null;
auth.onAuthStateChanged(function(user){
    if (user) {
        currentUser = user
        console.log(currentUser)
    }
});

function addTopic() {
    var title  = document.getElementById('title').value
    var desc = document.getElementById('desc').value
    var slug = title.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g,'-')

    db.collection('forums').add({
        title       : title,
        slug        : slug,
        desc        : desc.replace("<br />", "\n"),
        created_at  : new Date(),
        updated_at  : new Date(),
        user : {
            user_id : currentUser.uid,
            username : currentUser.displayName
        }
    }).then(function(docRef){
        alert("The forum was successfully created")
    }).catch(function(err){
        alert("There was an error adding the forum")
    })
}

The data that will be stored is an object with the user key and in that object, we will store have two data, namely uid and displayName. As we discussed above, the data user who is currently logged in can access the var currentUser.

On the object user, we will save uid currentUser.uid and displayName currentUser.displayName. For more details, we can see the results through the demonstration below:

ezgif.com-video-to-gif (1).gif

Screenshot_4.png

We can see in the picture above we have managed to save the user data and now we know who made the forums. uid is data that has been saved and recognized on auth.


Firebase admin

Now we will enter the next part of this tutorial series. In this section, we will use firebase admin. We will use firebase admin as a backend from our forum application. So with firebase admin, we can set the data that we will display on the frontend. Because firebase is made with javascript, the backend we will use is Node.js. For those of you who don't know what is Node.js?, you can visit the documentation in the following page https://nodejs.org/en/docs/ and after that, you can install it. After you install it you can continue this tutorial.

  • Set up firebase Admin

After you install Node.js automatically you will also install NPM. Well, using NPM we will install the package from firebase-admin. You can see examples like the following:

Install firebase admin

npm install firebase-admin --save

After we install we can use the package in the backend function that we have:

functions/index.js

// Require firebase-admin
const admin = require('firebase-admin');
const db = admin.firestore();

We can import packages from firebase admin like the following require('firebase-admin');. to access the database we can use firebase-admin instances that we imported earlier const db = admin.firestore();.

  • Credential settings

Now we have imported the firebase-admin package on our application. But to use it we need to do some settings. There are several credentials that we must install on our application, to see it we can enter the firebase console and we can choose project settings -> service accounts. for more details, we can see in the picture below

Screenshot_5.png

After that, you can download the private key in the JSON form that we can generate in this section.

Screenshot_6.png

After you have successfully downloaded you can configure it as you can see in the image above we will use Node.js as the server backend. For more details we can see in the example below:

functions/index.js

// Require firebase-admin
const admin = require('firebase-admin');

var serviceAccount = require("private-key.json"); // require private-key

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://forum-firebase-b3205.firebaseio.com"
});
// end setting

We can see in the section above we use the private key that we downloaded in the previous section, I put the private-key.json in the functions folder. You can adjust your file directory:

Screenshot_7.png

We can initialize our project by using initializeApp () and in this function, we need objects with key credential and databaseURL. we get the credential from the private-key.json that we downloaded earlier and we can get databaseURL in the firebase console like this picture:

Screenshot_8.png

If you follow the steps above, then we have successfully set up the Firebase admin. now we will start using firebase-admin as a backend to access the data that is our application.

  • Get data with firebase-admin

to access the database in our firebase application, we must use the firestore database instance and we can get the instance from const db = admin.firestore ();. to retrieve data in a collection we need a special rule, we need to know that the database type in Firestore is a horizontal, not a vertical database. You can find out the differences related to MySql and NoSql. For more details, we can see the example below:

functions/auth.js

var forums = [];
db.collection('forums').orderBy('updated_at', 'desc').get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            forums.push(doc.data())
        })
    }).catch(err => {
        console.log(err)
    })

To retrieve the data forums we need to extract data and store the data one by one in an array, in other words, we have to arrange the data into an array object which we will loop one by one on the frontend.

So every time we want to get data from the collection we have to provide an empty array var forums = []; for the container and then you can use the get () function to retrieve the data. then you can combine it with the promise function.

snapshot.forEach(doc => {
            forums.push(doc.data())
        })

And we have to issue data one by one by going over it and then push forums.push(doc.data()) it into the array that we provided before.

That's the way that we can access collections on the Firestore database, hopefully until here you understand what we learned in this tutorial, hopefully, you can take advantage of this tutorial, thanks

Curriculum

  • Forum app

Firebase app#1, [Firebase app#2](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-2-local-server-routing-and-template-login-gmail, Firebase app#3, Firebase app#4, Firebase app#5

Proof of work done

https://github.com/milleaduski/firebase-forum

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

  • Use the third person in your entire tutorial. It becomes more professional to be consistent during the whole contribution.

  • Good explanation of your code, but in some sections of code it would be important to have comments.

  • Your print screens are quite professional. Good job!

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!