Practical guides, tutorials, and insights from years of building web and desktop applications. Check out code examples you can actually use!
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).
...
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.
...
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.
...
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.
...
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.
...
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 -
...
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
...
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) -
...
Spoiler alert: I am.
What is recursion anyway? A program calling itself.
How does it look? conquerPlanet() { // infinite loop - there are too many planets to conquer conquerPlanet(); } OK.. how about a practical use case? Well, I am not quite a ’theory’ guy. But here you go with the age old problem of calculating factorial.
function getFacty(num) { if (num > 0) return num * getFacty(num - 1); else return 1; } const result = getFacty(10); console.log("result", result); Why use recursion? The program looks elegant, doesn’t it?
...
Most of my coding a few years back consisted of the following actions -
Type slowly Type (a lot of) mistakes Use spaces and tabs to format. Get confused about loops and add ad-hoc spaces and tabs Curse my typing skills and the soul who invented spaces and tabs While formatting code was also becoming an interim ’thought provoker’, it was simply too much typing.
Enter prettier.
Although my typing is only half as bad, I now have far less stuff to worry about.
...