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

Spread Operators in Javascript

A spread operator (...) provides a quick way to expand a Javascript object or array. Array or object is a collection of values. Accessing individual values within the array will require one to use a loop. const fruits = ["orange", "apple"]; for (let i = 0; i < fruits.length; i++) { console.log("fruit: ", fruits[i]); } /* output fruit: orange fruit: apple */ With the advent of the spread operator, the above operations become easier and more readable. Array can now be ‘destructured’ with a single statement. ...

Variable Scoping in Javascript

Scope of a variable refers to the visibility of that variable. Since the visibility of a variable also determines whether it can be referenced in a valid way, scopes are said to define the ’life time of a variable’. Scopes in Javascript can be global to the program, or local to the specific block and function. Before going further, a couple of lines on the basics Javascript is an interpreted language, but runs code using a compiler + interpreter engine combo. So, this is the normal execution of the program - ...

Operator Precedence in Javascript

Operator precedence includes unary, increment, basic arithmetic, logical and assignment operators - roughly in that order. The precedence can be remembered by BEUDMASLAS. brackets exponent unary & prefixed increment / decrement division multiplication addition subtraction logical assignment suffixed increment / decrement Not quite exciting as BODMAS or PEDMAS (math, anyone?) and as it turns out - you would not even have to remember it :). An outline with examples is below. ...

Javascript New Keyword

New operator is used to initialize objects and create a new instance of the object. You would have seen new used in the object context in an earlier post. The usage is something like the below - let worldExists = new Boolean(false); console.log(worldExists); // [Boolean: false] worldExists is an object that has a value of type ‘boolean’. Refer the post linked above to know the difference. Since everything (almost) is an object, new works very similarly in its use cases. ...

Rest Parameter in Javascript

Rest parameter enables you to signify an ‘infinite’ parameter to a function. ... serves two purposes in Javascript - Spread operator - know what spread operators can do Rest parameter for a function Rest parameter just tells Javscript that there can be zero or infinite parameters for the function. The elements are available as an array within the function. const getSum = (...nums) => { console.log(nums); // [ 2, 3, 6 ] }; getSum(2, 3, 6); Or, you could do partial parameters.. ...

Object Assign Method in Javascript

assign method of an object allows us to merge two objects quickly. const name = { name: "earth" }; const position = { position: 3 }; const planets = Object.assign(name, position); console.log("planets: ", planets); // { name: 'earth', position: 3 } You can also use Object.assign to quickly copy objects. const third = { name: "earth", position: 3 }; const livePlanet = Object.assign({}, third); console.log("livePlanet: ", livePlanet); third.position = 3.14; console.log("third: ", third); // { name: 'earth', position: 3.14 } console.log("livePlanet: ", livePlanet); // { name: 'earth', position: 3 } If you do not provide the empty object to assign, only a reference is copied and not the object itself.