Users might see tweets they really like and would love to show that by reacting to such tweets. Let's add ability for users to mark tweets as favorites.

Add the code below to start/routes.js:

// start/routes.js

Route.group(() => {
    Route.post('/create', 'FavoriteController.favorite')
})
    .prefix('favorites')
    .middleware(['auth:jwt'])

The route takes a tweet ID as a parameter.

Table of Contents

    Next, create the FavoriteController:

    adonis make:controller Favorite --type=http

    Once the controller is created, let's add the favorite method to it:

    // app/Controllers/Http/FavoriteController.js
    
    // add this to the top of the file
    const Favorite = use('App/Models/Favorite')
    
    async favorite ({ request, auth, response }) {
        // get currently authenticated user
        const user = auth.current.user
    
        const tweetId = request.input('tweet_id')
    
        const favorite = await Favorite.findOrCreate(
            { user_id: user.id, tweet_id: tweetId },
            { user_id: user.id, tweet_id: tweetId }
        )
    
        return response.json({
            status: 'success',
            data: favorite
        })
    }

    First we get the currently authenticated user. Next, we get the tweet the user is trying to like. Using the user's ID and tweet ID, we create a new record on the favorites table. Using findOrCreate will first find a favorite that matches the credential specified. If nothing is found, only then will it create the record in the favorite table. We then return the favorites as JSON object.

    Chimezie Enyinnaya

    20 posts

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