Firebase Part IX: Adding and Viewing Comments

7th Oct 19
Thumbnail

I am adding the ability for users to comment on topics posted.

I want registered users to be able to comment on topics: 

app.post('/forum/:topicId/comment', FBAuth, commentOnTopic)

The commentOnTopic function required authentication and user data such as profile image and user id is extracted from the middleware function:

exports.commentOnTopic = (req, res) => {
    if(req.body.body.trim() == '') return res.status(400).json({error: 'Must not be empty'});

    const newComment = {
        body: req.body.body,
        createdAt: new Date().toISOString(),
        topicId: req.params.topicId,
        userHandle: req.user.handle,
        userImage: req.user.imageUrl
    }

    db.doc(`/topics/${req.params.topicId}`).get()
        .then(doc => {
            if(!doc.exists) return res.status(404).json({error: 'Topic not found'});
            return db.collection('comments').add(newComment)
        })
        .then(() => {
            return res.json(newComment);
        })
        .catch(err => {
            res.status(500).json({error: 'Something went wrong'});
            console.error(err);
        })
}

The topic id is retrieved from the url.  Note that I had make some amends to FBAuth by extracting the user's imageUrl so that I could add the profile image to the comments.

 

Viewing Comments

For retrieving the comments I firstly extract the topic then from the topic data I retrieve the associated comments.  The topicId is extracted from the url.

exports.getTopic = (req, res) => {
    let topicData = {};
    db.doc(`/topics/${req.params.topicId}`)
        .get()
        .then(doc => {
            if(!doc.exists){
                return res.status(404).json({error: 'Topic not found'})
            }
            topicData = doc.data();
            topicData.topicId = doc.id;
            return db
                .collection('comments')
                .orderBy('createdAt', 'desc')
                .where('topicId', '==', req.params.topicId)
                .get();
        })
        .then(data => {
            topicData.comments = [];
            data.forEach( doc => {
                topicData.comments.push(doc.data())
            });
            return res.json(topicData)
        })
        .catch(err =>{
            res.status(500).json({error: err.code});
            console.error(err);
        })
}

 

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.