Let’s start AdonisJS Group routing and controller management in the code now by creating some routes and controllers.
For anyone unaware of the term routing in terms of web development, it is a mapping of URLs and their handlers that you want to handle your app.
Now, we have the AdonisJS Router pretty well covered, and let’s go ahead and move into cleaning up our route files by extracting our route definition’s route handlers into what’s called a controller and out of the route definition itself.
What is a Controller
Controllers are a JavaScript Class that is the default export of its file. By default, AdonisJS controllers reside within the app/Controllers/HTTP directory. A specific Http directory exists because we can have different types of controllers, such as WebSocket controllers.
// app/Controllers/Http/PostsController.ts export default class PostsController { }
Firstly, within AdonisJS it’s common to have a Controller per resource, for example for a Post model we did have a PostsController, for a Series model we’d have a SeriesController, and for a Topic model we did have a TopicsController.
So now, for the following route definition like below
Route.get('/posts', async ({ view }) { return view.render('posts/index') })
Also, we did move the route handler from the route definition below
Route.get('/posts', /* Goodbye route handler */)
Let’s see to the PostsController below
// app/Controllers/Http/PostsController.ts export default class PostsController { public async index({ view }) { return view.render('posts/index') } }
You can purchase your hosting from Cloudsurph.com, Cloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.
After then, to say the route definition to use the PostsController and specifically and it is index method, we did provide an object path string as the second argument in our route definition but of the handler itself instead.
Route.get('/posts', 'PostsController.index')
Creating A Controller
When you need to create a controller, as with most things in AdonisJS, here we have two options. We can create the file and I always prefer to create my controllers.
node ace make:controller --help ------------------------------- Make a new HTTP controller Usage: make:controller <name> Arguments name Name of the controller class Flags -r, --resource Add resourceful methods to the controller class -e, --exact Create the controller with the exact name as provid So, based on the above code, in order to create our posts controller, now we want to run the following command node ace make:controller Post ----------------------------- CREATE: app/Controllers/Http/PostsController.ts
TypeScript and the HttpContext
At present, one thing you may consider is that AdonisJS provides a commented-out line importing the type HttpContextContract when you create a new non-resource controller.
Since this is the TypeScript type for our HttpContext object. When we define our route handlers directly in the route definition for AdonisJS has the ability to provide the type for the HttpContext object that is provided as the argument for our callback function.
// ↓ AdonisJS can provide the type automatically Route.get('/posts', async ({ view }) => { return view.render('posts/index') })
Default Controllers
Therefore, when you create a new controller without any resource flag, this is what AdonisJS will start you with, and note the HttpContextContract import that is commented out for your convenience.
// import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' export default class PostsController { }
Love to Code? We’re Your Helping Partner, click here for Buy Our Service
After then, when you create a new controller with the resource flag, this is what AdonisJS will start you with.
And you can note the HttpContextContract is imported and set as the type for each of the parameters of the method.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' export default class PostsController { public async index ({}: HttpContextContract) { } public async create ({}: HttpContextContract) { } public async store ({}: HttpContextContract) { } public async show ({}: HttpContextContract) { } public async edit ({}: HttpContextContract) { } public async update ({}: HttpContextContract) { } public async destroy ({}: HttpContextContract) { } }
Namespacing Controllers and Routes
Namespacing is a way to group files and code based on permissions, functionality, or really any other reason that you need to group files and code together for your application.
Now we could say our HTTP Controllers are namespaced to App/Controllers/Http.
And we could say our Websocket controllers are namespaced to App/Controllers/Websocket.
Creating A Controller Namespace
Here we give some Controller Namespace that usages are common:
App/{namespace}/Controllers/Http App/Controllers/Http/{namespace} App/Modules/{namespace}/Controllers/Http
So now, we want a new PostsController within the Namespace Admin and we could run the following Ace CLI command to create that Namespace and Controller like the below command
node ace make:controller Admin/Post --resource ---------------------------------------------- CREATE: app/Controllers/Http/Admin/PostsController.ts
Pointing A Route to A Namespace
AdonisJS provides a method that we can chain off our route definition called namespace and that we can use to define the Namespace to use for the Controller in our application
Route.group(() => { // this will use the controller at: // app/Controllers/Http/Admin/PostsController.ts Route.get('/posts', 'PostsController.index') // ↓ informs all inner routes to use controllers defined here }).namespace('App/Controllers/Http/Admin').prefix('admin')
You can check our previous article: AdonisJS: REST API simple CRUD Operation. IF you want then buy a good, reliable, secure web hosting service from here: click here
Finally, we have got our route definitions all cleaned up.
And using Controllers and we are already starting to discuss resources.
Now would be a great time to dive into resources further and fully learn them.
If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.