Role-based Access to Routes in AdonisJS

AdonisJS provides a standard way to define a middleware and enable access to routes based on defined validation rules. This middleware is leveraged to allow role-based access to routes. Your start | routes.js file will have something akin to below - const Route = use("Route"); Route.get("/", () => { return { greeting: "Hello world!" }; }); First, we will group routes for the different roles and introduce the middleware. // start | Routes.js Route.group(() => { Route.post("/user-register", "UserController.register"); Route.post("/user-login", "UserController.login"); }); Route.group(() => { Route.get("/todo", "TodoController.index"); Route.post("/todo", "TodoController.create"); }).middleware("auth"); Route.group(() => { Route.delete("/todo", "TodoController.delete"); }).middleware(["auth", "admin"]); register and login methods are available to unauthenticated and authenticated users To do create and index are available only to authenticated users. auth is provided by AdonisJS Deleting to do is allowed only for admin Now, we write the actual middleware for admin. ...

Change Date Formats in AdonisJS

AdonisJS internally uses moment.js and processes all dates in YYYY-MM-DD format. The format, being an international standard, should have been the standard everywhere. Since it is not, let us see how we can modify the date format. Consider an example - Todo has a end_date field against every record. Your model will look like the below - const Model = use("Model"); class Todo extends Model { /* model code */ } module.exports = Todo; First, inform Adonis that end_date is a valid date field. This is done by using a super that is applicable for all fields. Else, the value will not be serialized as date (not even in the international format). ...

Return Related Record Post Saving Record in AdonisJS

AdonisJS automatically returns the base/parent record to the caller from the controller. However, you may have to custom code all of one statement to return a related record after the parent record is committed to the database. Consider an example - // TodoController.js async create({ request, auth }) { const user = await auth.getUser(); const data = request.all(); const todo = new Todo(); todo.fill(data); // commit todo and any related entities sent // through data to the database await todo.save(); // this will populate any changes made by Adonis/DB await todo.load("user"); // user is related entity // query and popular user entity within todo // follows same serializer as rest of the application return todo; } When you create a Todo, the controller takes the data sent in the request and commits that to the database. Post commit todo variable will have the data from database after committing the data. ...

Simple Role-based Validation Techniques for AdonisJS

AdonisJS does not provide an access control list (ACL) feature out of the box. Here’s are a few simple ways to provide the right access to the right user when using AdonisJS. Use ACL plugins There are two plugins available for AdonisJS - Adonis ACL Advanced Adonis ACL The usage is pretty simple. Follow the instructions in the package to install package as a provider. Create a view based the role/permission data structure for ease-of-use. You could now create specific roles and permissions. ...

Custom Exceptions in AdonisJS

AdonisJS provides streamlined ways to raise exceptions in your controller or service code, and raise them in a controlled way to the caller. To create a custom exception - adonis make:exception RecordNotFoundException This will create - √ create app\Exceptions\RecordNotFoundException.js Edit the exception to introduce your own errors. "use strict"; const { LogicalException } = require("@adonisjs/generic-exceptions"); class RecordNotFoundException extends LogicalException { /** * Handle this exception by itself */ handle(error, { response }) { return response.status(404).json({ error: "Record is not found. Check other universes.", }); } } module.exports = RecordNotFoundException; We are trying to raise a 404 with a specific exception message in the above code block. ...

Track Created By / Modified By for Records in AdonisJS

AdonisJS provided a quick way to track created and updated times, but does not provide shortcuts to track the user who created or last updated the record. Doing so is quite easy. Modify the migration script to include created_by_id and updated_by_id. // todoschema.js class TodoSchema extends Schema { up() { this.create("todos", (table) => { table.increments(); // id table.timestamps(); // created_at and updated_at columns table .integer("created_by_id") .unsigned() .references("id") .inTable("users"); table .integer("updated_by_id") .unsigned() .references("id") .inTable("users"); }); } down() { this.drop("todos"); } } module.exports = TodoSchema; Both the user id columns are references to the users table, which is included out of the box in Adonis. ...

The Right Way to Receive Parameters in AdonisJS Controller

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 - ...

Create a functional backend in AdonisJS under 5 minutes

AdonisJS provides a really quick way to scaffold your way to a great back-end application. Let us start creating a simple to-do app called ‘ado’ in this post. We will see how we can create this with simple commands and have your API ready in no time. Install AdonisJS Download and install Node if you don’t have it in your system. Install AdonisJS CLI npm i -g @adonisjs/cli Download and install Insomnia REST client. This will be used to test the back-end APIs that we will be creating in AdonisJS ...

Why should you use AdonisJS framework?

AdonisJS is a great server-side framework built on Express. It’s opinionated way of doing things just makes sense, clears up the initial development problems, and makes development & maintenance easier. I have completed ~3 projects on AdonisJS so far after switching roles to a web application developer last year. After using FeathersJS, Laravel and a bit of .NET, I find myself increasingly becoming comfortable with what AdonisJS can offer. Here’s why you should use AdonisJS (my opinions - I am often wrong) - ...