Quickly and easily pass parameters to controller methods from your request.
See Start creating your backend application in AdonisJS to get started
You can quickly scaffold a controller in Adonis using the following command -
adonis make:controller Todo --type http
If you want to receive parameters from input, you would do the following -
class AccountController {
async create({ request, auth, params, addParams }) {
const data = request.all();
/*
..
..
*/
}
By destructuring assignment to variables within the function argument itself, you are doing two things -
- Provide clarity on the acceptable arguments
- Signal that only specified variables are allowed
In the above example -
request, containsdatathat is passed by the caller. For example: data may be in JSON request for a POST request. This is automatically available to our method in the controller.paramsis also passed to the method by Adonis. This is any parameter passed through URL.routecollects the parameter values and passes it to the controller method. The route may have the following URL, which is processed for params, andidreceived from caller is passed to the controller method.Route.patch("/todo/:id", "TodoController.update");authrefers to authentication. This is a way of Adonis informing your method about the client status. You can now do the below to get logged in user details -const user = auth.getUser();addParamsis a custom parameter that is not provided by Adonis. You would have to pass an object with the same name for Adonis to make any sense of it and process it as ‘addParams’.
However, the rules are not enforced by the framework. Adonis 4.1 does not have types, and does not provide anything out of the box for paramter pre-validations.
You could do something akin to the below in your controller method for validation -
const { id } = params;
if (!id) throw "Id cannot be blank";