### Basic Session Usage Example Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/session.md Demonstrates core session methods for managing a shopping cart, including getting, putting, filtering, and forgetting session data. ```typescript import router from '@adonisjs/core/services/router' import Product from '#models/product' /** * Display items in the cart. * Uses get() with a default value of empty array. */ router.get('/cart', ({ session }) => { const cartItems = session.get('cart', []) return { items: cartItems, total: cartItems.length } }) /** * Add a product to the cart. * Demonstrates put() to store updated cart data. */ router.post('/cart', async ({ request, session }) => { const productId = request.input('product_id') const product = await Product.findOrFail(productId) const cartItems = session.get('cart', []) cartItems.push({ id: product.id, name: product.name, quantity: 1 }) session.put('cart', cartItems) return { message: 'Item added', totalItems: cartItems.length } }) /** * Remove a specific item from the cart. * Shows how to update and store modified data. */ router.delete('/cart/:productId', ({ params, session }) => { const cartItems = session.get('cart', []) const updatedCart = cartItems.filter(item => item.id !== params.productId) session.put('cart', updatedCart) return { message: 'Item removed' } }) /** * Clear the entire cart. * Uses forget() to remove a specific key. */ router.delete('/cart', ({ session }) => { session.forget('cart') return { message: 'Cart cleared' } }) ``` ```typescript router.get('/checkout', ({ session, response }) => { /** * Check if cart exists and has items before proceeding. * The has() method returns true if the key exists. */ if (!session.has('cart')) { return response.redirect('/cart') } const cartItems = session.get('cart') return { items: cartItems } }) ``` -------------------------------- ### Write the configure function for a cache package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/scaffolding.md Implement the configure function to automate package setup. This example registers a provider, defines environment variables, and creates a configuration file using codemods. ```typescript import type Configure from '@adonisjs/core/commands/configure' import { stubsRoot } from './stubs/main.ts' export async function configure(command: Configure) { const codemods = await command.createCodemods() /** * Register the provider and commands in the adonisrc.ts file */ await codemods.updateRcFile((rcFile) => { rcFile .addProvider('@adonisjs/cache/cache_provider') .addCommand('@adonisjs/cache/commands') }) /** * Add environment variables to .env and .env.example files */ await codemods.defineEnvVariables({ CACHE_STORE: 'redis', }) /** * Add validation rules to start/env.ts */ await codemods.defineEnvValidations({ variables: { CACHE_STORE: `Env.schema.string()`, }, }) /** * Create the config/cache.ts file from a stub */ await codemods.makeUsingStub(stubsRoot, 'config.stub', { store: 'redis', }) } ``` -------------------------------- ### Get Start Path Source: https://github.com/adonisjs/v7-docs/blob/main/content/reference/application.md Returns the path to a specific file within the start directory or the start directory itself. ```typescript app.startPath('routes.ts') // /project_root/start/routes.ts app.startPath() // /project_root/start ``` -------------------------------- ### Add Redis Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/session.md Install the Redis package for session storage using the Ace command. Refer to the Redis guide for complete setup instructions. ```sh node ace add @adonisjs/redis ``` -------------------------------- ### Install TanStack Query Integration Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/tanstack_query.md Install the necessary packages for your specific frontend framework. ```bash npm install @tanstack/react-query @tuyau/react-query ``` ```bash npm install @tanstack/vue-query @tuyau/vue-query ``` -------------------------------- ### Run Production Build Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/deployment.md Commands to navigate to the build directory, install only production dependencies, and start the AdonisJS server. ```shell cd build npm ci --omit=dev node bin/server.js ``` -------------------------------- ### Start API kit development server Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/installation.md Starts both backend and frontend development servers in a Turborepo monorepo environment. ```bash npm run dev ``` -------------------------------- ### Install DynamoDB SDK Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/cache.md Install the AWS SDK for DynamoDB to use it as a cache store. ```bash npm i @aws-sdk/client-dynamodb ``` -------------------------------- ### API Call Examples (HTTP Method Functions) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/api_client.md Shows how to make API calls to external or legacy services using direct HTTP method functions like `get`, `post`, and `patch`. This syntax mirrors the fetch API while maintaining type safety. ```typescript const user = await client.get('/users/:id', { params: { id: '123' }, query: { include: 'posts' } }) const post = await client.post('/posts', { body: { title: 'Hello', content: 'World' } }) const updated = await client.patch('/posts/:id', { params: { id: '456' }, body: { title: 'Updated title' } }) ``` -------------------------------- ### Install Auth Package with Basic Auth Guard Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/auth/introduction.md Use this command to install the auth package and configure it for basic HTTP authentication. ```sh node ace add @adonisjs/auth --guard=basic_auth ``` -------------------------------- ### JSON translation file example (French) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/i18n.md Example of a French translation file for the 'greeting' key, demonstrating multi-language support. ```json { "greeting": "Bonjour le monde" } ``` -------------------------------- ### Install Transmit Client Library Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/server_sent_events.md Install the client library for your frontend application to enable communication with the SSE server. ```sh npm install @adonisjs/transmit-client ``` -------------------------------- ### Install Auth Package with Access Tokens Guard Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/auth/introduction.md Use this command to install the auth package and configure it for token-based authentication, recommended for APIs. ```sh node ace add @adonisjs/auth --guard=access_tokens ``` -------------------------------- ### Install Sinon.js dependencies Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/testing/test_doubles.md Install Sinon and its type definitions as development dependencies. ```sh npm install -D sinon @types/sinon ``` -------------------------------- ### Install @adonisjs/ally Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/auth/social_authentication.md Install the Ally package and optionally specify providers during installation. ```sh node ace add @adonisjs/ally ``` ```sh node ace add @adonisjs/ally --providers=github --providers=google ``` -------------------------------- ### Install Auth Package with Session Guard Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/auth/introduction.md Use this command to install the auth package and configure it for session-based authentication, recommended for web applications. ```sh node ace add @adonisjs/auth --guard=session ``` -------------------------------- ### Example .env.example File Structure Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/configuration.md The .env.example file serves as a template for required environment variables, with placeholder values. It should be committed to version control to document setup requirements for developers. This file helps new team members configure their local environments. ```bash HOST=0.0.0.0 PORT=3333 APP_KEY= DATABASE_URL=postgresql://user:password@localhost:5432/myapp RESEND_API_KEY= ``` -------------------------------- ### Install AWS SDK for DynamoDB Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/session.md Install the AWS SDK client for DynamoDB before configuring the DynamoDB session driver. ```sh npm install @aws-sdk/client-dynamodb ``` -------------------------------- ### Getting Help for Specific Commands Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/ace/introduction.md Access detailed help documentation for any Ace command, including its arguments, flags, and usage examples, by appending the `--help` flag. This provides a comprehensive overview of how to use the command. ```shell node ace make:controller --help ``` -------------------------------- ### Install Hashing Drivers Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/security/hashing.md Install the necessary npm packages for Argon2 or Bcrypt support. ```sh # For Argon2 (recommended for new applications) npm i argon2 # For Bcrypt npm i bcrypt ``` -------------------------------- ### Install AdonisJS Limiter Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/security/rate_limiting.md Command to install and configure the rate limiter package. ```sh node ace add @adonisjs/limiter ``` -------------------------------- ### Install @adonisjs/mail Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/mail.md Install the @adonisjs/mail package and configure it for your project. ```sh node ace add @adonisjs/mail ``` -------------------------------- ### Install @adonisjs/i18n Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/i18n.md Install and configure the @adonisjs/i18n package using the ace command. ```bash node ace add @adonisjs/i18n ``` -------------------------------- ### Install Redis Transport Dependency Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/server_sent_events.md Install the `ioredis` package to enable Redis as the transport layer for multi-instance synchronization. ```shell npm install ioredis ``` -------------------------------- ### Install MJML package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/mail.md Command to install the MJML package, which is used for creating responsive HTML emails. ```bash npm i mjml ``` -------------------------------- ### Install PostgreSQL Driver and Uninstall SQLite Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/tutorial/hypermedia/deployment.md Installs the 'pg' package for PostgreSQL support and removes the 'better-sqlite3' package. This is the first step in migrating the database connection. ```bash npm install pg npm uninstall better-sqlite3 ``` -------------------------------- ### Install Packages Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/scaffolding.md Installs npm packages using the project's detected package manager. ```ts await codemods.installPackages([ { name: 'vinejs', isDevDependency: false }, { name: '@types/lodash', isDevDependency: true } ]) ``` -------------------------------- ### Install Tuyau package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/api_client.md Install the core Tuyau package using npm. This is the first step for integrating Tuyau into your project. ```bash npm install @tuyau/core ``` -------------------------------- ### Install CORS Middleware in AdonisJS Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/security/cors.md Installs the @adonisjs/cors package and registers its service provider and middleware. This command automates the setup process for CORS in your AdonisJS application. ```sh node ace add @adonisjs/cors ``` -------------------------------- ### Create a new application with a specific starter kit Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/installation.md Use the --kit flag to select a specific starter kit during the project initialization process. ```sh npm create adonisjs@latest [project-name] -- --kit=hypermedia ``` ```sh npm create adonisjs@latest [project-name] -- --kit=react ``` ```sh npm create adonisjs@latest [project-name] -- --kit=vue ``` ```sh npm create adonisjs@latest [project-name] -- --kit=api ``` -------------------------------- ### Install Session Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/session.md Use the Ace command to install and configure the session package in an AdonisJS project. ```sh node ace add @adonisjs/session ``` -------------------------------- ### Install Tuyau in Backend Package.json Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/api_client.md Install `@tuyau/core` in your backend workspace. It handles both the assembler hook (registry generation) and exposes the client for your frontend to import. ```json { "name": "@my-app/backend", "private": true, "type": "module", "dependencies": { "@tuyau/core": "^1.0.0" // [!code highlight] } } ``` -------------------------------- ### Start Development Server Source: https://github.com/adonisjs/v7-docs/blob/main/README.md Starts the development server for the AdonisJS documentation website. The site will be accessible at `http://localhost:3333`. ```shell npm run dev ``` -------------------------------- ### Install @adonisjs/otel Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/opentelemetry.md Installs the OpenTelemetry package for AdonisJS using the Ace command-line tool. This command also handles initial configuration and setup. ```bash node ace add @adonisjs/otel ``` -------------------------------- ### Start Hypermedia/Inertia development server Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/installation.md Use the --hmr flag to enable Hot Module Replacement for faster development feedback. ```bash node ace serve --hmr ``` -------------------------------- ### Install @adonisjs/lock Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/locks.md Installs the @adonisjs/lock package and registers its service provider. This command also creates configuration files and environment variable definitions. ```sh node ace add @adonisjs/lock ``` -------------------------------- ### Install FlyDrive for File Storage Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/file_uploads.md Install the `@adonisjs/drive` package to manage file storage. This command also generates the `config/drive.ts` configuration file. ```bash node ace add @adonisjs/drive ``` -------------------------------- ### Install Vite Integration in AdonisJS Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/vite.md Installs the `@adonisjs/vite` package and `vite` itself, along with creating necessary configuration files. This command streamlines the setup process for frontend asset bundling. ```sh node ace add @adonisjs/vite ``` -------------------------------- ### Start Development Server with HMR Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/tutorial/react/routes_controllers_and_views.md Use this command to start the AdonisJS development server with Hot Module Replacement enabled for faster development cycles. ```bash node ace serve --hmr ``` -------------------------------- ### Install Dependencies for Build Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/deployment.md In CI/CD or fresh environments, set NODE_ENV to development before installing dependencies to ensure all build tools are available. Then, run the build command. ```sh NODE_ENV=development npm install npm run build ``` -------------------------------- ### Install Redis Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/database/redis.md Install the @adonisjs/redis package using the Ace command. This command also registers the service provider and creates the configuration file. ```sh node ace add @adonisjs/redis ``` -------------------------------- ### API Call Examples (Proxy Syntax) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/api_client.md Demonstrates making API calls using route names with proxy syntax. Route segments map to method chains on the client, providing autocomplete and type safety. ```typescript // Route: router.post('register', [controllers.Auth, 'register']) const result = await client.api.auth.register({ body: { email: 'foo@ok.com', password: 'password123' } }) // Route: router.get('users/:id', [controllers.Users, 'show']) const user = await client.api.users.show({ params: { id: '1' }, query: { include: 'posts' } }) ``` -------------------------------- ### Start and Load Models in AdonisJS REPL Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/tutorial/hypermedia/database_and_models.md This demonstrates how to start the AdonisJS REPL and load all application models. The REPL provides an interactive environment to test and query your database models directly. ```typescript await loadModels() ``` -------------------------------- ### Start the AdonisJS development server Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Starts the AdonisJS development server with hot module replacement enabled, allowing for live updates during development. This command is used to test the implemented routes and controllers. ```bash node ace serve --hmr ``` -------------------------------- ### GET /health/ready Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/health_checks.md Retrieves a detailed JSON report of all registered health checks. This endpoint can be protected by a secret header. ```APIDOC ## GET /health/ready ### Description Returns a detailed JSON report containing the results of all registered checks. This endpoint can be protected using a secret header to prevent unauthorized access. ### Method GET ### Endpoint /health/ready ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```http GET /health/ready HTTP/1.1 Host: example.com X-Monitoring-Secret: some_secret_value ``` ### Response #### Success Response (200) - **isHealthy** (boolean) - Indicates whether all checks passed. Set to `false` if one or more checks fail. - **status** (string) - Overall status: `ok` (all passed), `warning` (warnings present), or `error` (failures present). - **finishedAt** (string) - Timestamp when the checks completed. - **debugInfo** (object) - Process information including PID, platform, uptime in seconds, and Node.js version. - **checks** (array) - Array containing the detailed result of each registered check. #### Response Example ```json { "isHealthy": true, "status": "warning", "finishedAt": "2024-06-20T07:09:35.275Z", "debugInfo": { "pid": 16250, "ppid": 16051, "platform": "darwin", "uptime": 16.271809083, "version": "v21.7.3" }, "checks": [ { "name": "Disk space check", "isCached": false, "message": "Disk usage is 76%, which is above the threshold of 75%", "status": "warning", "finishedAt": "2024-06-20T07:09:35.275Z", "meta": { "sizeInPercentage": { "used": 76, "failureThreshold": 80, "warningThreshold": 75 } } }, { "name": "Memory heap check", "isCached": false, "message": "Heap usage is under defined thresholds", "status": "ok", "finishedAt": "2024-06-20T07:09:35.265Z", "meta": { "memoryInBytes": { "used": 41821592, "failureThreshold": 314572800, "warningThreshold": 262144000 } } } ] } ``` #### Error Response (401) - **message** (string) - "Unauthorized access" if the `x-monitoring-secret` header is missing or invalid. ``` -------------------------------- ### Register Preload File for All Environments Source: https://github.com/adonisjs/v7-docs/blob/main/content/reference/adonisrc_file.md Specify files to import during application boot. This example registers a file to run in all environments. ```ts { preloads: [ () => import('#start/view') ] } ``` -------------------------------- ### Create a Docker entrypoint script for migrations Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/deployment.md A script to conditionally run migrations based on an environment variable before starting the server. ```js import { execSync } from 'node:child_process' /** * Run migrations before starting the server * when the MIGRATE environment variable is set. */ if (process.env.MIGRATE === 'true') { console.log('Running migrations...') execSync('node ace migration:run --force', { stdio: 'inherit' }) } /** * Start the server */ console.log('Starting server...') await import('./bin/server.js') ``` -------------------------------- ### Example JSON response from controller Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Illustrates the expected JSON output when accessing the '/posts' route after connecting the PostsController. This confirms the successful execution of the 'index' action. ```json { "posts": [ { "id": 1, "title": "Getting started with AdonisJS" }, { "id": 2, "title": "Understanding controllers" } ] } ``` -------------------------------- ### Add Macro to HttpContext Class Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/extending_adonisjs.md Extend the HttpContext class to add context-level utilities that combine request and response logic. This example adds a method to get the current authenticated user or throw an error. ```typescript import { HttpContext } from '@adonisjs/core/http' HttpContext.macro('getCurrentUser', async function (this: HttpContext) { return await this.auth.getUserOrFail() }) ``` -------------------------------- ### Define complete CORS configuration scenarios Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/security/cors.md Provides full configuration examples for common use cases including SPAs, local development environments, and public APIs. ```typescript import { defineConfig } from '@adonisjs/cors' const corsConfig = defineConfig({ enabled: true, origin: ['https://app.example.com'], methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], headers: true, credentials: true, maxAge: 90, }) export default corsConfig ``` ```typescript import { defineConfig } from '@adonisjs/cors' const corsConfig = defineConfig({ enabled: true, origin: (requestOrigin) => { return requestOrigin.startsWith('http://localhost') }, methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], headers: true, credentials: true, maxAge: 90, }) export default corsConfig ``` ```typescript import { defineConfig } from '@adonisjs/cors' const corsConfig = defineConfig({ enabled: true, origin: '*', methods: ['GET', 'HEAD', 'POST'], headers: true, credentials: false, maxAge: 86400, }) export default corsConfig ``` -------------------------------- ### AdonisJS Post Controller Implementation Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md An example of an AdonisJS controller class for handling post-related requests. It includes methods for indexing, showing, and storing posts, utilizing HttpContext for request and serialization. ```typescript import type { HttpContext } from '@adonisjs/core/http' export default class PostsController { async index({ serialize }: HttpContext) { // Logic to fetch all posts return serialize({ posts: [] }) } async show({ params, serialize }: HttpContext) { // Logic to fetch a single post return serialize({ post: {} }) } async store({ request, serialize }: HttpContext) { // Logic to create a post return serialize({ post: {} }) } } ``` -------------------------------- ### HTML Form Example with Method Spoofing Source: https://github.com/adonisjs/v7-docs/blob/main/content/reference/config/app.md Demonstrates how to use the `_method` query parameter in an HTML form to specify non-POST HTTP methods. ```html
``` -------------------------------- ### Start AdonisJS REPL Session Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/ace/repl.md Initiates an interactive REPL session for your AdonisJS application. This command boots the application, making its services and modules available for direct interaction from the command line. ```shell node ace repl ``` -------------------------------- ### Configure Redis Store for Atomic Locks Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/locks.md Configures the Redis store for atomic locks, optionally specifying a custom Redis connection name. This requires the @adonisjs/redis package to be installed and configured. ```typescript { redis: stores.redis({ connectionName: 'main', }), } ``` -------------------------------- ### Build and run the Docker container Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/deployment.md Commands to build the image from the Dockerfile and start the container with environment variables. ```sh docker build -t my-adonis-app . docker run -p 3333:3333 --env-file .env my-adonis-app ``` -------------------------------- ### Scaffold a new controller in AdonisJS Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md This command generates a new controller file with a plain JavaScript class and a default export. It's the starting point for creating controller logic in your AdonisJS application. ```bash node ace make:controller PostsController ``` -------------------------------- ### Example service structure Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/container_services.md A pattern for creating a custom service that resolves a container binding after the application has booted. ```ts import app from '@adonisjs/core/services/app' let drive: DriveManager await app.booted(async () => { drive = await app.container.make('drive') }) export { drive as default } ``` -------------------------------- ### Client-Side Direct Upload with Fetch API Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/file_uploads.md Example of uploading a file directly to cloud storage using a signed URL obtained from the server. This involves two fetch requests: one to get the URL and another to perform the upload. ```javascript async function uploadFile(file) { // Step 1: Request a signed URL from your server const response = await fetch('/signed-upload-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ file_name: file.name }) }) const { signedUrl } = await response.json() // Step 2: Upload directly to cloud storage using the signed URL await fetch(signedUrl, { method: 'PUT', body: file, headers: { 'Content-Type': file.type } }) console.log('File uploaded successfully!') } ``` -------------------------------- ### Load Dynamic Routes in Start Hook Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/service_providers.md The `start` hook is suitable for loading dynamic routes from external sources like a database before the HTTP server begins accepting connections. ```typescript import router from '@adonisjs/core/services/router' import type { ApplicationService } from '@adonisjs/core/types' export default class RoutesProvider { constructor(protected app: ApplicationService) {} async start() { /** * Load routes from database or external configuration */ const dynamicRoutes = await this.loadRoutesFromDatabase() dynamicRoutes.forEach((route) => { router.get(route.path, route.handler) }) } private async loadRoutesFromDatabase() { // Implementation would fetch routes from database return [] } } ``` -------------------------------- ### Manual construction of framework classes Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/container_services.md Demonstrates the manual instantiation of a framework class, which requires providing all dependencies manually. ```typescript import { Router } from '@adonisjs/core/http' export const router = new Router(/** Router dependencies */) ``` -------------------------------- ### Monitor Multiple Database Connections with DbCheck (TypeScript) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/health_checks.md To monitor multiple database connections, register the DbCheck for each connection instance. This allows for granular monitoring of different database setups within your application. ```typescript export const healthChecks = new HealthChecks().register([ new DiskSpaceCheck(), new MemoryHeapCheck(), // [!code ++:3] new DbCheck(db.connection()), new DbCheck(db.connection('mysql')), new DbCheck(db.connection('pg')), ]) ``` -------------------------------- ### Connect a controller action to a route Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Binds the 'index' action of the PostsController to the '/posts' GET route. It utilizes AdonisJS's barrel file system for efficient controller referencing, ensuring lazy loading. ```typescript import router from '@adonisjs/core/services/router' import { controllers } from '#generated/controllers' router.get('/posts', [controllers.Posts, 'index']) ``` -------------------------------- ### Render formatted times Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/i18n.md The example shows the expected output for a time formatting string. Ensure the `appointmentAt` value is a valid time representation. ```txt You have an appointment today at 2:48 PM ``` -------------------------------- ### Define a controller action for listing posts Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Adds an 'index' method to the PostsController to handle GET requests for listing posts. It demonstrates how to access the HttpContext, define mock data, and return a JSON response. ```typescript import type { HttpContext } from '@adonisjs/core/http' export default class PostsController { /** * Handle GET requests to list all posts */ async index({ response }: HttpContext) { const posts = [ { id: 1, title: 'Getting started with AdonisJS' }, { id: 2, title: 'Understanding controllers' }, ] return response.json({ posts }) } } ``` -------------------------------- ### Install Queue Package Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/queues.md Installs the `@adonisjs/queue` package and configures it by registering service providers, commands, and preload files. It also sets up environment variables and creates necessary database migrations if the database driver is selected. ```sh node ace add @adonisjs/queue ``` -------------------------------- ### AdonisJS Inline Route Handlers Example Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Demonstrates a basic AdonisJS routes file with inline asynchronous functions for handling HTTP requests. This approach can lead to unmanageable route files as the application grows. ```typescript import router from '@adonisjs/core/services/router' router.get('/posts', async () => { // Logic to fetch all posts return { posts: [] } }) router.get('/posts/:id', async ({ params }) => { // Logic to fetch a single post return { post: {} } }) router.post('/posts', async ({ request }) => { // Logic to create a post return { post: {} } }) // This file becomes unmanageable as routes grow ``` -------------------------------- ### Monitor Multiple Redis Connections with RedisCheck (TypeScript) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/health_checks.md To monitor multiple Redis connections, register the RedisCheck for each connection instance. This allows for comprehensive monitoring of different Redis setups, such as caching or locking services. ```typescript export const healthChecks = new HealthChecks().register([ new DiskSpaceCheck(), new MemoryHeapCheck(), // [!code ++:3] new RedisCheck(redis.connection()), new RedisCheck(redis.connection('cache')), new RedisCheck(redis.connection('locks')), ]) ``` -------------------------------- ### Controller instance isolation per request Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Illustrates that each controller instance is created per request, ensuring state isolation. This example uses a private property to show that a unique requestId is generated for each incoming request. ```typescript import type { HttpContext } from '@adonisjs/core/http' export default class PostsController { // This property is unique to each request #requestId = Math.random() async index({ response }: HttpContext) { // Each request will see a different requestId return response.json({ requestId: this.#requestId }) } } ``` -------------------------------- ### API Call Examples (Request Method) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/frontend/api_client.md Illustrates making API calls by explicitly passing the route name as a string to the `client.request` method. This is functionally identical to the proxy syntax. ```typescript const result = await client.request('auth.register', { body: { email: 'foo@ok.com', password: 'password123' } }) const user = await client.request('users.show', { params: { id: '1' }, query: { include: 'posts' } }) ``` -------------------------------- ### Write Basic Log Message in AdonisJS Route Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/logger.md This snippet demonstrates how to import and use the logger service to write an informational log message within an AdonisJS route handler. It's a fundamental example for starting with logging in AdonisJS applications. ```typescript import router from '@adonisjs/core/services/router' import logger from '@adonisjs/core/services/logger' router.get('/', async () => { logger.info('Processing home page request') return { hello: 'world' } }) ``` -------------------------------- ### Seed the Database Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/tutorial/hypermedia/deployment.md Populates the PostgreSQL database with initial data using the Ace command-line tool. This step ensures the database has test data, allowing for immediate application testing after setup. ```bash node ace db:seed ``` -------------------------------- ### Create a production-optimized Dockerfile Source: https://github.com/adonisjs/v7-docs/blob/main/content/start/deployment.md Uses a multi-stage build process to minimize image size by separating dependency installation, application building, and the production runtime. ```dockerfile FROM node:lts-bookworm-slim AS base # ---------------------------- # Stage 1: Install all dependencies # ---------------------------- FROM base AS deps WORKDIR /app COPY package*.json ./ RUN npm ci # ---------------------------- # Stage 2: Build the application # ---------------------------- FROM deps AS build WORKDIR /app COPY . . RUN node ace build # ---------------------------- # Stage 3: Production runtime # ---------------------------- FROM base AS production WORKDIR /app ENV NODE_ENV=production COPY --from=build /app/build ./ RUN npm ci --omit=dev EXPOSE 3333 CMD ["node", "bin/server.js"] ``` -------------------------------- ### Service Provider Lifecycle Methods (start, ready) Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/application_lifecycle.md Demonstrates the use of `start` and `ready` methods within an AdonisJS service provider. The `start` method is executed after the boot phase, useful for tasks like verifying database connections. The `ready` method runs when the application is fully initialized and ready to handle requests, often used for logging readiness. ```typescript import type { ApplicationService } from '@adonisjs/core/types' export default class AppProvider { constructor(protected app: ApplicationService) {} async start() { const database = await this.app.container.make('lucid.db') /** * Verify database connection is working */ await database.connection().select(1) } async ready() { if (this.app.getEnvironment() === 'web') { const logger = await this.app.container.make('logger') logger.info('HTTP server is ready to accept requests') } } } ``` -------------------------------- ### Use Controller as Route Handler - AdonisJS Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/routing.md Demonstrates how to delegate route handling to a specific controller method. This approach promotes better organization and reusability of logic. The example uses a Posts controller and its 'show' method for handling GET requests to '/posts/:id'. ```typescript import router from '@adonisjs/core/services/router' import { controllers } from '#generated/controllers' router.get('/posts/:id', [controllers.Posts, 'show']) ``` -------------------------------- ### Adaptive Caching Example Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/digging_deeper/cache.md Demonstrates how to use adaptive caching to dynamically set the TTL based on fetched data. ```APIDOC ## Adaptive Caching Adaptive caching lets you dynamically adjust cache options based on the data being cached. This is useful when the ideal TTL depends on the actual value. The factory function receives a context object with helper methods to adjust cache behavior after inspecting the fetched data. ```ts title="app/services/auth_service.ts" import cache from '@adonisjs/cache/services/main' const token = await cache.getOrSet({ key: `auth:token:${provider}`, ttl: '1h', factory: async (ctx) => { const token = await fetchOAuthToken(provider) /** * Set the TTL based on the token's actual expiration * rather than using a fixed value */ ctx.setOptions({ ttl: `${token.expiresIn}s` }) return token }, }) ``` The context object also provides: - `ctx.skip()` to prevent caching the returned value - `ctx.fail()` to prevent caching and throw an error - `ctx.setTags([...])` to dynamically set tags based on the cached value - `ctx.gracedEntry` to access the stale value from the grace period (if any) ``` -------------------------------- ### Assign Middleware to Specific Resource Routes Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/basics/controllers.md Explains how to apply middleware to specific resource route actions. The `.use()` method accepts an array of action names and the middleware to apply, allowing for granular security or processing logic. For example, applying authentication only to mutation routes. ```typescript import router from '@adonisjs/core/services/router' import { controllers } from '#generated/controllers' import { middleware } from '#start/kernel' router .resource('posts', controllers.Posts) .use( ['create', 'store', 'update', 'destroy'], middleware.auth() ) ``` -------------------------------- ### AdonisJS IndexGenerator: Default Setup for Controllers, Events, and Listeners Source: https://github.com/adonisjs/v7-docs/blob/main/content/guides/concepts/assembler_hooks.md This example showcases a complete `init` hook configuration for AdonisJS's `IndexGenerator`. It sets up barrel file generation for controllers, events, and listeners, mirroring the framework's default setup. This enables features like lazy-loading in routes for controllers and type-safe event emission/binding for events and listeners. The configuration includes specifying source directories, import aliases, export names, and output file paths. ```typescript import { hooks } from '@adonisjs/core/app' export default hooks.init((parent, hooksManager, indexGenerator) => { /** * Generate a barrel file for controllers. * Enables lazy-loading in routes: [controllers.Posts, 'index'] */ indexGenerator.add('controllers', { source: './app/controllers', importAlias: '#controllers', as: 'barrelFile', exportName: 'controllers', removeSuffix: 'controller', output: './.adonisjs/server/controllers.ts', }) /** * Generate a barrel file for event classes. * Enables type-safe event emission. */ indexGenerator.add('events', { source: './app/events', importAlias: '#events', as: 'barrelFile', exportName: 'events', output: './.adonisjs/server/events.ts', }) /** * Generate a barrel file for event listeners. * Enables lazy-loading listeners in event bindings. */ indexGenerator.add('listeners', { source: './app/listeners', importAlias: '#listeners', as: 'barrelFile', exportName: 'listeners', output: './.adonisjs/server/listeners.ts', }) }) ```