- Since Adonis follows MVC design pattern, controllers are there to handle requests and responses. Controllers collect requests & run lucid query builders to communicate with the database and send the response back. You can create a controller for the corresponding model by
adonis make:controller <Model_name> --type http
- For a CRUD operation, there are mainly 5 types of requests. For example, in the projects table we will have,
GET: projects - request to return all projects
GET: projects/:id - request to return a particular project (id given in params)
PUT: projects - request for creating a project (payload to be provided in the request body)
PATCH: projects/:id - request for updating a project (payload to be provided in the request body, id given in params)
DELETE: projects/:id - request for deleting a project
So the project controller should have functions to handle all these requests and should be routed through created endpoints.
- Create controllers for projects and tasks similarly to handle the CRUD operations and return applicable responses. Write the lucid query builders to communicate with the database. Use Lucid query builders like below:
/**
* Create/save a new project.
* POST projects
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store({ request, auth, response }) {
try {
const user = await auth.getUser();
const { title } = request.post();
const project = new Project();
project.fill({
title,
});
await user.projects().save(project);
return response.status(200).send({
project,
message: 'Successfully Added project'
})
} catch (error) {
return response.status(error.status | 500).send(error);
}
}
- For users table, you don't need CRUD endpoints. Hence you only need -
POST: auth/register
POST: auth/login
So write functions to register a user and implement login facilities. Use auth functions like below:
async login({request, auth, response}){
try {
const { email, password } = request.post();
const token = await auth.attempt(email, password);
return token;
} catch (error) {
return response.status(error.status | 500).send(error);
}
}
- Route the endpoints towards correct controller functions by editing the
route.js
file. In the route.js
file specify the mapping between urls & corresponding function to handle like below
Route.group(()=>{
Route.get('/', 'ProjectController.index').middleware('auth');
Route.put('/', 'ProjectController.store').middleware('auth');
Route.get('/:id', 'ProjectController.show').middleware('auth');
Route.post('/:id', 'ProjectController.update').middleware('auth');
Route.delete('/:id', 'ProjectController.destroy').middleware('auth');
}).prefix('v1/project')
Tip
- Use --resource while creating a controller to have the standard function structures present already.