AdonisJS Legacy Documentation

repository·4.1·Indexed 41 days ago

https://github.com/adonisjs/legacy-docs

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

Tokens
69.2K
Snippets
292
Records
335
Agent score
50%

What's inside AdonisJS

  1. What is AdonisJs

    4.1
    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.
  2. Understand the AdonisJs directory structure

    4.1

    A standard AdonisJs installation organizes code into specific directories to separate concerns and maintainability. The root structure typically includes:

    • app/: Application logic, autoloaded under the App namespace.
    • 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.json
  3. AdonisJs community communication channels

    4.1

    You 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.
  4. Introduction to Lucid ORM

    4.1

    Lucid 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/Models directory, where each model typically represents a database table (e.g., a User model maps to a users table).

    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.
  5. Introduction to the Query Builder

    4.1

    The 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()
      }
    }
  6. Close database connections in Ace commands

    4.1

    When 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()
      }
    }
  7. Manage application logic in the app directory

    4.1

    The app directory contains the core business logic of your application and is autoloaded under the App namespace. It is subdivided into several functional directories, most of which are automatically created via AdonisJs CLI commands:

    • app/Commands: CLI commands (created via adonis make:command <name>).
    • app/Controllers: HTTP and WebSocket controllers (created via adonis make:controller <name>).
    • app/Exceptions: Global exception handler and custom exceptions (created via adonis make:ehandler or adonis make:exception <name>).
    • app/Listeners: Event listeners (created via adonis make:listener <name>).
    • app/Middleware: Middleware (created via adonis make:middleware <name>).
    • app/Models: Data models (created via adonis make:model <name>).
    • app/Validators: Route validators (created via adonis make:validator <name>; requires the Validator Provider).
  8. How Controllers work in AdonisJS

    4.1

    Controllers 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 require controllers 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 Context as an argument, providing access to request, response, and other lifecycle objects.
    'use strict'
    
    class UserController {
      index ({ request, response }) {
        // Access request and response from the HTTP Context
      }
    }
    
    module.exports = UserController
  9. How CSRF Protection works in AdonisJS

    4.1
    1. AdonisJS creates a CSRF secret for each user.
    2. A token is generated for each request and passed to views via csrfToken and csrfField() globals.
    3. The same token is set in a cookie named XSRF-TOKEN. Frontend frameworks (like AngularJS) can read this cookie and send it back in the X-XSRF-TOKEN header.
    4. For POST, PUT, or DELETE requests, the middleware verifies the submitted token against the secret.
  10. Use form method spoofing for PUT and DELETE requests

    4.1

    Since HTML forms only support GET and POST methods, AdonisJs allows you to perform resourceful operations (like PUT or DELETE) by using form method spoofing.

    To use this, append ?_method=METHOD to the form's action URL. AdonisJs will only spoof the method if the original request is a POST.

    To disable this feature, set allowMethodSpoofing: false in config/app.js under the http key.

    // Route definition
    Route.put('/users/:id', 'UserController.update')
    
    // HTML View
    <form action="/users/1?_method=PUT" method="POST">
    </form>
  11. Use Query Scopes for Reusable Constraints

    4.1

    Query scopes allow you to extract query constraints into reusable methods. Define them using the scope prefix in your model.

    Definition:

    class User extends Model {
      static scopeHasProfile (query) {
        return query.has('profile')
      }
    }

    Usage: When calling the scope, drop the scope prefix and use camelCase.

    const users = await User.query().hasProfile().fetch()