Firebase Part VIII: add user bio and get user details

7th Oct 19
london on a rainy day

I am adding functions to add and display user details.

I want the website to have a page for registered users, where users can add a bit about themselves and so on.  I firstly create a function to post user details (bio and location).

exports.addUserDetails = (req, res) => {
    let userDetails = reduceUserDetails(req.body);
    db.doc(`/users/${req.user.handle}`).update(userDetails)
        .then(() => {
            return res.json({message: 'Details added successfully'})
        })
        .catch(err => {
            console.error(err);
            return res.status(500).json({error: err.code})
        });
}

This is an authenticated route, so I can use the user object from the middleware to retrieve his or her's user data.  The reduceUserDetails simply checks whether the user has added bio and/or location and if so returns an object containing the associated data from the req body.

exports.reduceUserDetails = (data) => {
let userDetails = {};
    if(!isEmpty(data.bio.trim())) userDetails.bio = data.bio;
    if(!isEmpty(data.location.trim())) userDetails.location = data.location;
    return userDetails;
}

 

Get User Details

When I return the user data, the data will eventually hold more data such as likes and notifications.  All the data already stored in the database user document will be held within the credentials object.  Even though I haven't added the functionality to like a topic, I added the functionality to add the likes if any the 'like' array.

exports.getAuthenticatedUser = (req, res) => {
    let userData = {};
    db.doc(`/users/${req.user.handle}`)
        .get()
        .then(doc => {
            if(doc.exists){
                userData.credentials = doc.data();
                return db.collection('likes').where('userHandle', '==', req.user.handle)
                 .get()      
            }
        })
        .then(data => {
            userData.likes = [];
            data.forEach(doc => {
                userData.likes.push(doc.data());
            });
            return res.json(userData)
        })
        .catch(err => {
            console.error(err);
            return res.status(500).json({error: err.code}) 
        })
}

 

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