Firebase firestore in the forum application #12: Add comment feature and Add a collection in the document

in #utopian-io5 years ago

Repository

https://github.com/firebase

What Will I Learn?

  • Add comment feature
  • Add a collection in the document

Requirements

  • Basic Javascript
  • Install Firebase

Resources

Difficulty

Basic

Tutorial Content

This tutorial is an advanced series of firebase tutorials, in this series we will continue the previous tutorial, in the previous tutorial we have successfully edited the forum with access to forum ownership. we have limited the user to make changes to the data on the forum that is not theirs. here we will learn new things, we will add a comment feature. I suggest you follow my tutorial beforehand so that you are not confused with the codes that we have made in the previous tutorial. for that, we just start this tutorial.

Add comment feature

In this section we will add very important features to the application forum with the forum comments that we will make more interactive, so the idea is that we will create this comment system in each forum and other users can comment on the forum that we created.

  • Make comment input

We will start making the comment feature, now the first part that I will make is to make an input display for the comments, I will use the input component from the bootstrap to accelerate us in the development process in the frontend section. We will add input comments to the forum-details.hbs template:

forum-details.hbs

<div class="is-hidden" id="editForm">
    <div class="row">
        <div class="container">
            <form>
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" class="form-control" id="title" value="{{forum.title}}" placeholder="Your tittle">
                </div>
                <div class="form-group">
                    <label for="desc">Desciptions</label>
                    <textarea class="form-control" id="desc" rows="3">{{forum.desc}}</textarea>
                </div>
                <button class="btn btn-info" type="button" name="button" id="update-btn" onclick="updateForum('{{forum.id}}')">Update</button>
            </form>
        </div>
    </div>
</div>
<br>
<div class="form-group">
    <textarea class="form-control" id="desc" rows="3" placeholder="Your comment"></textarea>
    <button type="button" onclick="addComment('{{forum.id}}')">Add comment</button>
</div>

Here I will use the input text area <textarea> because my comment might be long. Well after we provide comment input, don't forget to give a button for the user interface when adding comments.

In the interface button that we provide, we will add a function that will be executed when the button is clicked onclick="addComment('{{forum.id}}')". We will use the addComment () function. In this function we will passed the forum id that we get from the object forum. We get forum.id from the name of the document in the collection forums. For more details you can read in my previous tutorial.

The following is a display of the comments interface of each forum:

Screenshot_9.png

We can see in the picture above we have an interface for input comments to users. Now we will create a function to add comments to our database.

Create a function to add comment

We already have the interface now what we will do is how to add data to our firebase. We have rendered the template with the addComment () function. So comments are part of the forums collection. So the data we will create is still in the forum document. So later we will create a new collection in the forum document. This is what is called a collection in a collection. For more details, we can see the code below:

function addComment(forumId) {
    var newComment = document.getElementById('comment').value
    var forumsRef = db.collection('forums').doc(forumId)

    forumsRef.collection('replies').add({ // add new collection
        desc : newComment.replace("<br />", "\n"),
        created_at : new Date(),
        updated_at : new Date(),
        user: {
            user_id : currentUser.uid,
            name : currentUser.displayName
        }
    })
}

In the addComment () function we pass the id document that is in the forumId parameter. Now this id will reference the document from the forums collection.

Here I will receive the comment value from the user in the following way document.getElementById('comment').value. We give id = "comment" in the input text area.

After that, as I said we will make a collection in the collection. To make this we need a document to add a new collection. As we have done above we have passed the forum ID. Now we can define it in a variable to make it easier to use it var forumsRef = db.collection('forums').doc(forumId). Now we have access to the collection document, access is on the forumsRef variable.

  • Add a collection in document

Now we can add our new collection to the forum document, Please note that a collection can only be saved in a document, because we have got the ID document now we can save the new collection as shown below:

forumsRef.collection('replies').add({ })

We will create a new collection called replies, a collection must be in the form of an object. Therefore we can fill in the object as follows:

    forumsRef.collection('replies').add({ // add new collection
        desc : newComment.replace("<br />", "\n"),
        created_at : new Date(),
        updated_at : new Date(),
        user: {
            user_id : currentUser.uid,
            name : currentUser.displayName
        }
    })

As we saw in the example above. I will fill the object with desc, created_at, updated_at, and an object user that will be filled with useful information that adds comments.

We can get the data of the user who is logged in by accessing the currentUser object. This object is made when the user successfully logs in, you can follow my previous tutorial for a more detailed explanation.

  • Add Rules for replies collection

We have added a function to add new collections to documents in the collection forums. now we will create new rules in the database settings that we have:

Rules in firestore

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{document=**} {
      allow read, create: if request.auth != null;
    }
    match /forums/{slug} {
      allow read;
      allow create: if request.auth != null 
                                && request.resource.data.title.size() > 10
      allow update: if request.auth.uid == resource.data.user.user_id
                                && request.resource.data.title.size() > 10
                // Rules for replies collection
        match /replies/{reply} {
            allow read;
          allow create: if request.auth != null 
                                && request.resource.data.desc.size() > 20
        }
    }
  }
}

We can see in the picture above we created a new rule that is still in PATH from the collection forums. For more details, we can see in the picture below:

Screenshot_11.png

rules for the collection of replies are still in the PATH forums and the rules made are allow read; and allow create:. In the allow created we will make the rule that the user must login first if request.auth != null and the minimum characters in the comment description are 20 && request.resource.data.desc.size() > 20.

  • Add the promise function

We will add a promise to get a response when we successfully add a collection of replies in the forum document, the way is as follows:

forumsRef.collection('replies').add({
        desc : newComment.replace("<br />", "\n"),
        created_at : new Date(),
        updated_at : new Date(),
        user: {
            user_id : currentUser.uid,
            name : currentUser.displayName
        }
    }).then(function(docRef){
        console.log("Comments have been added successfully")
        window.location = window.location.href + '/' + slug
    }).catch(function(error){
        console.log(error)
    })

The response we get when we can get it successfully on docRef and the failed response we can catch if an error occurs.

Now that we have succeeded in making the rules, it is time to test whether the program we have made is going well.

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

Screenshot_12.png

We can see in the demonstration above we have succeeded in adding a collection to the forum document that we commented on. this means the function that we have made goes well. enough here until this tutorial. hopefully, it will be useful for you, thank you

Curriculum

  • Forum app

Firebase app#1, Firebase app#2, Firebase app#3, Firebase app#4, Firebase app#5, Firebase app#6, Firebase app#7, Firebase app#8, Firebase app#9, Firebase app#10,

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:

  • In your next tutorial put comments in the code sections. Users with less experience have more difficulty interpreting code and a brief explanation in more complicated code lines helps always.

  • Use only the third person in the text of your tutorial.

  • Try to improve the structure of your tutorial.

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!

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.029
BTC 76114.36
ETH 2937.56
USDT 1.00
SBD 2.64