Adonis.js Overview
Adonis.js Overview.
Introduction
Adonis.js is a Node.js framework that allows developers to build scalable and efficient web applications. It follows the MVC (Model-View-Controller) pattern and provides a robust set of features to simplify the development process. In this tutorial, we will explore the history, features, and examples of Adonis.js.
History
Adonis.js was created by ace, a software development company based in Romania. It was first released in 2016 and has gained popularity among developers due to its simplicity and performance. The framework was inspired by Laravel, a popular PHP framework, and borrows many concepts from it.
Features
Let's take a look at some of the key features of Adonis.js:
1. Routing
Adonis.js provides a powerful routing system that allows developers to define routes for their application. Here's an example of how to define a simple route:
Route.get('/', ({ response }) => {
return response.send('Hello World');
});
In this example, we define a GET route for the root URL ("/") which returns a "Hello World" message.
2. Middleware
Middleware in Adonis.js provides a way to handle request/response before or after it reaches the route handler. It helps in implementing cross-cutting concerns such as authentication, validation, etc. Here's an example of a middleware that logs the request URL:
class LogRequest {
async handle({ request }, next) {
console.log(`Request URL: ${request.url()}`);
await next();
}
}
To use this middleware, we can register it in the start/kernel.js file:
const namedMiddleware = {
log: 'App/Middleware/LogRequest',
};
And then apply it to a route:
Route.get('/', ({ response }) => {
return response.send('Hello World');
}).middleware(['log']);
3. Database Integration
Adonis.js comes with a built-in ORM (Object Relational Mapper) called Lucid. It supports multiple databases such as MySQL, PostgreSQL, SQLite, and Oracle. Here's an example of creating a model and querying the database:
class User extends Model {
static get table() {
return 'users';
}
}
const users = await User.query().where('age', '>', 18).fetch();
In this example, we define a User model that represents the users table in the database. We then use the query() method to fetch all users who are above 18 years old.
4. Authentication
Adonis.js provides a simple and secure authentication system out of the box. It includes features like registration, login, and password reset. Here's an example of how to authenticate a user:
const auth = await auth.attempt(email, password);
In this example, we use the attempt() method to authenticate a user with their email and password.
Examples
Let's explore a couple of examples to demonstrate the power and flexibility of Adonis.js:
Example 1: Creating a Todo List Application
We will create a simple Todo List application using Adonis.js. The application will allow users to create, update, and delete tasks.
Install Adonis.js globally:
npm install -g @adonisjs/cliCreate a new Adonis.js project:
adonis new todo-listGenerate a Todo model and migration:
adonis make:model Todo -mRun the migration to create the
todostable:adonis migration:runDefine routes for creating, updating, and deleting tasks in
start/routes.js:Route.post('/todos', 'TodoController.create');
Route.put('/todos/:id', 'TodoController.update');
Route.delete('/todos/:id', 'TodoController.delete');Implement the methods in
app/Controllers/Http/TodoController.js:class TodoController {
async create({ request }) {
const { title } = request.body;
const todo = new Todo();
todo.title = title;
await todo.save();
return todo;
}
async update({ params, request }) {
const { title } = request.body;
const todo = await Todo.findOrFail(params.id);
todo.title = title;
await todo.save();
return todo;
}
async delete({ params }) {
const todo = await Todo.findOrFail(params.id);
await todo.delete();
return { message: 'Task deleted successfully' };
}
}Start the development server:
adonis serve --dev
Now you can use tools like Postman to test the API endpoints for creating, updating, and deleting tasks.
Example 2: Real-time Chat Application
Adonis.js integrates seamlessly with WebSocket protocols like WebSocket and Socket.io, making it ideal for building real-time applications. Here's an example of a real-time chat application:
Install the Adonis.js WebSockets package:
npm install @adonisjs/websocketCreate a new channel for the chat application:
adonis make:channel ChatImplement the logic for handling chat messages in
app/Channels/Chat.js:class Chat {
onMessage({ socket, request }, message) {
socket.broadcastToAll('message', message);
}
}Register the channel in
start/socket.js:const namedChannels = {
chat: 'App/Channels/Chat',
};Create a WebSocket route in
start/routes.js:Route.ws('/chat', 'ChatController.index').middleware(['auth']);Implement the methods in
app/Controllers/Http/ChatController.js:class ChatController {
async index({ auth, view }) {
await auth.check();
return view.render('chat');
}
}Create a view for the chat interface in
resources/views/chat.edge:<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<input type="text" id="message" placeholder="Type your message">
<button id="send">Send</button>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
document.getElementById('send').addEventListener('click', () => {
const message = document.getElementById('message').value;
socket.emit('message', message);
});
socket.on('message', (message) => {
console.log(`Received message: ${message}`);
});
</script>
</body>
</html>Start the development server:
adonis serve --dev
Now you can open the chat interface in a web browser and start sending messages in real-time.
Conclusion
In this tutorial, we explored the introduction, history, features, and examples of Adonis.js. We learned about its powerful routing system, middleware support, database integration, and authentication system. We also saw two examples of building a Todo List application and a real-time chat application using Adonis.js.
To learn more about Adonis.js, you can visit the official website.