Firebase Part VII: Adding Topics with authentication

7th Oct 19
computer with code displayed

I am creating topics users can post in relation to their Bonsais for my bonsai website.

I create the routes and associated functions, similar to my Bonsai route for getting and posting data:

exports.getAllTopics = (req, res) => {
    db.collection('topics')
        .get()
        .then(data => {
            let topics = [];
            data.forEach(doc => {
                topics.push(doc.data());
            });
            return res.json(topics);
        })
        .catch(err => {
            console.error(err);
            }
        )
}

exports.postOneTopic = (req, res) => {
    const newTopic = {
        subject: req.body.subject,
        category: req.body.category,
        message: req.body.message,
        userHandle: req.body.userHandle,
        createdAt: new Date()
    }

    db.collection('topics')
        .add(newTopic)
        .then(doc => {
            res.json({message: `document ${doc.id} created successfully`})
        })
        .catch(err => {
            res.status(500).json({error: err.code});
            console.error(err);
        })

}

 

I add my user authentication middleware to the post topic route: 

app.post('/forum/post', FBAuth, postOneTopic)

 And we can access the user object through the authentication middleware, within the newTopic object I alter the userHandle:

userHandle: req.user.handle,

 

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