Build a Twitter Clone With Adonis and Vue

Replying Tweet

Now, let's allow users to reply to tweets. Add the line below in start/routes.js:

// start/routes.js

Route.post('/tweets/reply/:id', 'TweetController.reply').middleware(['auth:jwt']);

This route takes the ID of the tweet a user wants to reply to.

Next, let's create the reply method. Add the code below in TweetController:

// app/Controllers/Http/TweetController.js

// add this at the top of the file
const Reply = use('App/Models/Reply')

async reply ({ request, auth, params, response }) {
    // get currently authenticated user
    const user = auth.current.user

    // get tweet with the specified ID
    const tweet = await Tweet.find(params.id)

    // persist to database
    const reply = await Reply.create({
        user_id: user.id,
        tweet_id: tweet.id,
        reply: request.input('reply')
    })

    // fetch user that made the reply
    await reply.load('user')

    return response.json({
        status: 'success',
        message: 'Reply posted!',
        data: reply
    })
}

Then we fetch the tweet with the specified ID. Using the authenticated user's ID, tweet ID and the reply message entered by the user, we create and persist the reply in the database. We eager load the user that made the reply and finally return a JSON object containing a message and the newly created reply.