The last functionality we will add for users is "user timeline". On a user's timeline his/her tweets will be displayed along with the tweets of those he/she is following.

Add the code below to start/routes.js within the users group routes.

// start/routes.js

Route.get('/timeline', 'UserController.timeline')

Next, define the timeline method. Add the code below to UserController:

Table of Contents

    // app/Controllers/Http/UserController.js
    
    // add this at the top
    const Tweet = use('App/Models/Tweet')
    
    async timeline ({ auth, response }) {
        const user = await User.find(auth.current.user.id)
    
        // get an array of IDs of the user's followers
        const followersIds = await user.following().ids()
    
        // add the user's ID also to the array
        followersIds.push(user.id)
    
        const tweets = await Tweet.query()
            .whereIn('user_id', followersIds)
            .with('user')
            .with('favorites')
            .with('replies')
            .fetch()
    
        return response.json({
            status: 'success',
            data: tweets
        })
    }

    We get the currently authenticated user, and then we get an array of IDs of the user's followers. We also add the authenticated user's ID to the array of IDs. Using whereIn, we filter the tweets to those whose user_id are in the array of IDs (that is, the user and those following). In addition to the tweets, we also eager load the tweet's relations. Finally, we return a JSON object of the tweets.

    Chimezie Enyinnaya

    16 posts

    Software Developer [PHP Laravel JavaScript NodeJS AdonisJS VueJS] | movie lover | run http://openlaravel.com