To start off building the user functionality, we'll give users ability to sign up to the app. To do this, let's create a /signup route. Open start/routes.js and add the line below to it:

// start/routes.js

Route.post('/signup', 'UserController.signup')

When the /signup route is accessed, the signup method of UserController will be executed. This method handles signing up users.

Next, let's create the UserController called above. AdonisJS controllers can be of 2 types:

Table of Contents

    • HTTP controllers: typical HTTP request/response controller.
    • WebSocket controllers: for building real-time applications in AdonisJs.
    adonis make:controller User --type=http

    Assigning http to the --type flag indicates we want an HTTP controller. This will create a UserController.js within app/Controllers/Http.

    Tips: The app/Controllers/Http directory wasn't present before. Running the make:controller command will create the appropriate directories.

    Open app/Controllers/Http/UserController.js and add the code below to it:

    // app/Controllers/Http/UserController.js
    
    // add to the top of the file
    const User = use('App/Models/User')
    
    async signup ({ request, auth, response }) {
        // get user data from signup form
        const userData = request.only(['name', 'username', 'email', 'password'])
    
        try {
            // save user to database
            const user = await User.create(userData)
            // generate JWT token for user
            const token = await auth.generate(user)
    
            return response.json({
                status: 'success',
                data: token
            })
        } catch (error) {
            return response.status(400).json({
                status: 'error',
                message: 'There was a problem creating the user, please try again later.'
            })
        }
    }

    We define signup as an async method leveraging async/await which is now fully supported in Node.js. First, we get the data user entered in signup form then we try to save the data in the database. If all went well, we generate a JWT token for the newly signed up user, and then we return a JSON object with the generated token. If there was problem saving the user data to the database, we return a JSON object with an appropriate message.

    Tips: AdonisJS makes extensive use of async/await.

    Note: We are not handling form validation here as all form validations will be handled on the client-side.

    Chimezie Enyinnaya

    16 posts

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