AdonisJS Legacy Documentation
repository·4.1·Indexed 41 days ago
https://github.com/adonisjs/legacy-docsDocumentation for AdonisJS, a Node.js MVC framework for building full-stack web applications and micro API servers. This legacy set covers core concepts including the IoC container, Service Providers, the HTTP request lifecycle, and upgrade guides for version 4.1.
What's inside AdonisJS
- AdonisJs is a Node.js MVC (Model-View-Controller) framework designed for building full-stack web applications or micro API servers. It provides a stable, opinionated ecosystem with consistent and expressive APIs, allowing developers to focus on business logic rather than package selection. It is built to be modular and follows standardized conventions to improve maintainability and developer onboarding.
Overview of AdonisJS Documentation
4.1The AdonisJS documentation is written using Asciidoc. The source files are maintained in this repository, but they are compiled and rendered by the
adonisjs/adonisjs.comrepository, which is itself an AdonisJS application.To view the live documentation, visit http://adonisjs.com/docs.
Understand the AdonisJs directory structure
4.1A standard AdonisJs installation organizes code into specific directories to separate concerns and maintainability. The root structure typically includes:
app/: Application logic, autoloaded under theAppnamespace.config/: Application configuration files.database/: Database-related files (migrations, seeds, factories).public/: Static assets served over HTTP (mapped to the website root).resources/: Presentational files (view templates, uncompiled assets like SASS/LESS, images).start/: Files loaded during application boot (e.g.,app.js,kernel.js,routes.js).test/: Application tests.ace: The AdonisJs CLI executable.server.js: The entry point for the HTTP server.package.json: Node.js dependencies and scripts.
. ├── app/ ├── config/ ├── database/ ├── public/ ├── resources/ ├── storage/ ├── start/ ├── test/ ├── ace ├── server.js └── package.jsonAdonisJs community communication channels
4.1You can interact with the AdonisJs team and community through the following channels:
- GitHub Repositories: Share bugs or create feature requests.
- Forum: Ask questions, showcase projects, and participate in framework discussions.
- Discord: Join the server for instant chat with the community.
- Twitter: Stay informed about progress and community projects.
Introduction to Lucid ORM
4.1Lucid is the AdonisJS implementation of the Active Record pattern. It provides an expressive API for managing database data, relationships, and lifecycles. Lucid models are stored in the
app/Modelsdirectory, where each model typically represents a database table (e.g., aUsermodel maps to auserstable).Key features include:
- Transparent fetching and persisting of data.
- Relationship management (e.g.,
hasOne,hasMany). - Lifecycle hooks and Getters/Setters.
- Data serialization and date management.
Introduction to the Query Builder
4.1The AdonisJs Query Builder provides a unified JavaScript syntax to interact with SQL databases. It abstracts away connection-specific syntax, allowing you to write code that is compatible across different SQL dialects (e.g., migrating from MySQL to PostgreSQL) without rewriting queries. It also facilitates building incremental, conditional queries more cleanly than raw string concatenation.
const Database = use('Database') class UserController { async index (request, response) { return await Database .table('users') .where('username', 'john') .first() } }Close database connections in Ace commands
4.1When using a database (e.g., via Lucid) inside an Ace command, you must manually close the connection before the command finishes. If you do not, the process will not exit.
const Database = use('Database') async handle (args, options) { // ... database logic ... // Crucial: prevent the command from hanging Database.close() }const Database = use('Database') class Quote extends Command { async handle (args, options) { let quote = await Quote.query().orderByRaw('rand()').first() console.log(quote.content) Database.close() } }Manage application logic in the app directory
4.1The
appdirectory contains the core business logic of your application and is autoloaded under theAppnamespace. It is subdivided into several functional directories, most of which are automatically created via AdonisJs CLI commands:app/Commands: CLI commands (created viaadonis make:command <name>).app/Controllers: HTTP and WebSocket controllers (created viaadonis make:controller <name>).app/Exceptions: Global exception handler and custom exceptions (created viaadonis make:ehandleroradonis make:exception <name>).app/Listeners: Event listeners (created viaadonis make:listener <name>).app/Middleware: Middleware (created viaadonis make:middleware <name>).app/Models: Data models (created viaadonis make:model <name>).app/Validators: Route validators (created viaadonis make:validator <name>; requires the Validator Provider).
How Controllers work in AdonisJS
4.1Controllers are classes used to group related request handling logic. They act as the interaction point between models, views, and other services.
Key Principles:
- Single Responsibility: A controller's only job is to respond to an HTTP request.
- No Internal Usage: Do not
requirecontrollers inside other files to use them internally; they should only be accessed via routes. - Context Injection: Controller methods act as route handlers and automatically receive the
HTTP Contextas an argument, providing access torequest,response, and other lifecycle objects.
'use strict' class UserController { index ({ request, response }) { // Access request and response from the HTTP Context } } module.exports = UserControllerHow CSRF Protection works in AdonisJS
4.1- AdonisJS creates a CSRF secret for each user.
- A token is generated for each request and passed to views via
csrfTokenandcsrfField()globals. - The same token is set in a cookie named
XSRF-TOKEN. Frontend frameworks (like AngularJS) can read this cookie and send it back in theX-XSRF-TOKENheader. - For
POST,PUT, orDELETErequests, the middleware verifies the submitted token against the secret.
Use form method spoofing for PUT and DELETE requests
4.1Since HTML forms only support
GETandPOSTmethods, AdonisJs allows you to perform resourceful operations (likePUTorDELETE) by using form method spoofing.To use this, append
?_method=METHODto the form'sactionURL. AdonisJs will only spoof the method if the original request is aPOST.To disable this feature, set
allowMethodSpoofing: falseinconfig/app.jsunder thehttpkey.// Route definition Route.put('/users/:id', 'UserController.update') // HTML View <form action="/users/1?_method=PUT" method="POST"> </form>Use Query Scopes for Reusable Constraints
4.1Query scopes allow you to extract query constraints into reusable methods. Define them using the
scopeprefix in your model.Definition:
class User extends Model { static scopeHasProfile (query) { return query.has('profile') } }Usage: When calling the scope, drop the
scopeprefix and usecamelCase.const users = await User.query().hasProfile().fetch()