What is a Twitter clone if users can't post tweets? So, let's allow users to post tweets. We'll start by creating the route for this, so add the line below in start/routes.js:

// start/routes.js

Route.post('/tweet', 'TweetController.tweet').middleware(['auth:jwt'])

We add the auth to make sure only authenticated users can post tweets.

Next, let's create the TwitterController:

Table of Contents

    adonis make:controller Tweet --type=http

    Next, open the newly created controller and add the code below into it:

    // app/Controllers/Http/TweetController.js
    
    // add this at the top of the file
    const Tweet = use('App/Models/Tweet')
    
    async tweet ({ request, auth, response }) {
        // get currently authenticated user
        const user = auth.current.user
    
        // Save tweet to database
        const tweet = await Tweet.create({
            user_id: user.id,
            tweet: request.input('tweet')
        })
    
        // fetch tweet's relations
        await tweet.loadMany(['user', 'favorites', 'replies'])
    
        return response.json({
            status: 'success',
            message: 'Tweet posted!',
            data: tweet
        })
    }

    We get the currently authenticated user. Then we create the tweet with the authenticated user's ID and the tweet message entered by the user. Next, we load the relations of the tweet using lazy eager loading so they are available when we return the tweet.

    Chimezie Enyinnaya

    16 posts

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