### Install AdonisJs Lucid Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Command to install the Lucid package for AdonisJs. This is a prerequisite for using the Database Provider and Lucid ORM. ```bash > adonis install @adonisjs/lucid ``` -------------------------------- ### Install Vow Provider for AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Command to install the @adonisjs/vow package using npm. This package provides the testing framework for AdonisJS applications. ```bash > adonis install @adonisjs/vow ``` -------------------------------- ### Example Unit Test File in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc A basic example of a unit test file (`.spec.js`) in AdonisJS. This test verifies a simple arithmetic operation. ```javascript 'use strict' const { test } = use('Test/Suite')('Example') test('make sure 2 + 2 is 4', async ({ assert }) => { assert.equal(2 + 2, 4) }) ``` -------------------------------- ### Install AdonisJS WebSocket Provider via CLI Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc This command installs the WebSocket provider package from npm, adding configuration files like config/socket.js, start/socket.js, and start/wsKernel.js to the project. It requires the AdonisJS CLI to be installed globally. No inputs or outputs beyond file creation; limitations include needing manual provider registration afterward. ```bash > adonis install @adonisjs/websocket ``` -------------------------------- ### Select All Users with Query Builder Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Example of selecting all columns from the 'users' table using the AdonisJs Query Builder. This demonstrates a basic GET request to retrieve user data as JSON. ```javascript const Database = use('Database') Route.get('/', async () => { return await Database.table('users').select('*') }) ``` -------------------------------- ### Boot WebSocket Server using AdonisJS Ignitor Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Configures and starts the WebSocket server in server.js by chaining .wsServer() to the Ignitor instance, enabling real-time connections. Requires @adonisjs/ignitor and @adonisjs/fold packages. Inputs: App root directory; outputs: Running HTTP and WebSocket servers. Limitations: Handles errors via console; clustering needs separate setup. ```javascript const { Ignitor } = require('@adonisjs/ignitor') new Ignitor(require('@adonisjs/fold')) .appRoot(__dirname) .wsServer() // boot the WebSocket server .fireHttpServer() .catch(console.error) ``` -------------------------------- ### Run Tests in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Command to execute all tests in an AdonisJS application. This command utilizes the installed Vow provider. ```bash > adonis test ``` -------------------------------- ### Create and Save User Instance (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Provides an example of how to instantiate a User model, set its properties, and persist it to the database using the `save()` method. This demonstrates basic data creation with Lucid. ```javascript const User = use('App/Models/User') const user = new User() user.username = 'virk' user.password = 'some-password' await user.save() ``` -------------------------------- ### Register WebSocket Provider in AdonisJS App Configuration Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Adds the WsProvider to the providers array in start/app.js to enable WebSocket functionality within the AdonisJS application. Depends on the installed @adonisjs/websocket package. No specific inputs; outputs integrated server capabilities. Limitation: Must be done after installation. ```javascript const providers = [ '@adonisjs/websocket/providers/WsProvider' ] ``` -------------------------------- ### Fetch All Users (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Demonstrates how to fetch all records of a specific model (User) from the database using the `all()` static method. This example is typically placed within a route definition. ```javascript const Route = use('Route') const User = use('App/Models/User') Route.get('users', async () => { return await User.all() }) ``` -------------------------------- ### Query Builder Usage Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Illustrates how to obtain and use the Lucid Query Builder instance for database queries. ```APIDOC ## Query Builder Lucid models use the AdonisJs Query Builder to run database queries. Obtain a Query Builder instance by calling the model's `query` method. ### Example ```javascript const User = use('App/Models/User') const adults = await User .query() .where('age', '>', 18) .fetch() ``` **Notes:** 1. All Query Builder methods are fully supported. 2. The `fetch` method is required to execute the query and ensure results are returned within a serializer instance. ``` -------------------------------- ### Query Users with OR Condition Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Shows how to chain multiple 'where' conditions using 'orWhere' to broaden query results. This example selects users older than 18 or who are VIP. ```javascript Database .table('users') .where('age', '>', 18) .orWhere('vip', true) ``` -------------------------------- ### Unit Test Example in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc An example of a unit test written in JavaScript for AdonisJS. This test validates user details using a UserValidator service, asserting the validation results. ```javascript const { test } = use('Test/Suite')('Example unit test') const UserValidator = use('App/Services/UserValidator') test('validate user details', async ({ assert }) => { const validation = await UserValidator.validate({ email: 'wrong email' }) assert.isTrue(validation.fails()) assert.deepEqual(validation.messages(), [ { field: 'email', message: 'Invalid user email address' } ]) }) ``` -------------------------------- ### AdonisJS Lifecycle Hooks (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Illustrates the usage of lifecycle hooks (before, beforeEach, after, afterEach) within an AdonisJS test suite. These hooks allow for setup and teardown operations before and after tests. ```javascript const Suite = use('Test/Suite')('User registration') const { before, beforeEach, after, afterEach } = Suite before(async () => { // executed before all the tests for a given suite }) beforeEach(async () => { // executed before each test inside a given suite }) after(async () => { // executed after all the tests for a given suite }) afterEach(async () => { // executed after each test inside a given suite }) ``` -------------------------------- ### Configure Table Prefix Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Sets a table prefix for all queries on a specific connection. This is useful for organizing tables within a single database or for multi-tenancy setups. ```javascript module.exports = { connection: 'sqlite', sqlite: { client: 'sqlite3', prefix: 'my_' } } ``` -------------------------------- ### Listen for Query Event Globally Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Registers a hook to listen for the 'query' event globally, logging each executed query to the console. This requires creating or modifying the `start/hooks.js` file. ```javascript const { hooks } = require('@adonisjs/ignitor') hooks.after.providersBooted(() => { const Database = use('Database') Database.on('query', console.log) }) ``` -------------------------------- ### Static Methods Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Details various static methods available on Lucid models for common database operations. ```APIDOC ## Static Methods Lucid models provide several static methods for common operations without needing the Query Builder interface. `fetch()` is not required when using these methods. ### `find(primaryKey)` Find a record using its primary key. Always returns one record or null. ```javascript const User = use('App/Models/User') await User.find(1) ``` ### `findOrFail(primaryKey)` Similar to `find`, but throws a `ModelNotFoundException` if the record is not found. ```javascript const User = use('App/Models/User') await User.findOrFail(1) ``` ### `findBy(field, value)` / `findByOrFail(field, value)` Find a record using a key/value pair. Returns the first matching record or throws an exception if `findByOrFail` is used and no record is found. ```javascript const User = use('App/Models/User') await User.findBy('email', 'foo@bar.com') await User.findByOrFail('email', 'foo@bar.com') ``` ### `first()` / `firstOrFail()` Find the first row from the database based on the current query scope. `firstOrFail` throws an exception if no record is found. ```javascript const User = use('App/Models/User') await User.first() await User.firstOrFail() ``` ### `last()` Find the latest row from the database based on the current query scope. ```javascript const User = use('App/Models/User') await User.last() ``` ### `findOrCreate(whereAttributes, values)` Find a record matching `whereAttributes`, or create a new record using `values` if it doesn't exist. ``` -------------------------------- ### Apply Browser Trait in AdonisJS Test Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Example of applying the Test/Browser trait within an AdonisJS test suite. This enables browser-level testing capabilities. ```javascript const { test, trait } = use('Test/Suite')('User registration') trait('Test/Browser') ``` -------------------------------- ### Define Test Suite in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc JavaScript code showing how to define a test suite in AdonisJS using the Test/Suite module. It demonstrates both direct instantiation and destructuring. ```javascript const Suite = use('Test/Suite')('User registration') // or destructuring const { test } = use('Test/Suite')('User registration') ``` -------------------------------- ### Installing and Configuring BodyParser Middleware (Bash & JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Steps to install the BodyParser middleware using npm and configure it by registering its provider and global middleware in AdonisJs application files. ```bash > adonis install @adonisjs/bodyparser ``` ```javascript const providers = [ '@adonisjs/bodyparser/providers/BodyParserProvider' ] ``` ```javascript const globalMiddleware = [ 'Adonis/Middleware/BodyParser' ] ``` -------------------------------- ### Use Lucid Query Builder to Fetch Records (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Demonstrates how to obtain and use a Query Builder instance from a Lucid model to construct and execute database queries. This example filters users by age and fetches the results, which are returned within a serializer instance. ```javascript const User = use('App/Models/User') const adults = await User .query() .where('age', '>', 18) .fetch() ``` -------------------------------- ### Functional Test Example in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc An example of a functional test in AdonisJS using the Test/Browser trait. This test programmatically interacts with a web browser to fill out a form and validate error messages. ```javascript const { test, trait } = use('Test/Suite')('Example functional test') trait('Test/Browser') trait('Test/Session') test('validate user details', async ({ browser }) => { const page = await browser.visit('/') await page .type('email', 'wrong email') .submitForm('form') .waitForNavigation() page.session.assertError('email', 'Invalid user email address') }) ``` -------------------------------- ### AdonisJS Test Suite Definition (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Demonstrates defining a test suite in AdonisJS using the 'Test/Suite' class. Includes lifecycle hooks and custom context getters. ```javascript const { test, trait } = use('Test/Suite')('User registration') trait(function (suite) { suite.Context.getter('foo', () => { return 'bar' }) }) test('foo must be bar', async ({ foo, assert }) => { assert.equal(foo, 'bar') }) ``` -------------------------------- ### Query Users with Age Condition Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Demonstrates how to add a 'where' clause to a database query to filter users based on their age. This example selects users older than 18. ```javascript Database .table('users') .where('age', '>', 18) ``` -------------------------------- ### SQL Output with Table Prefix Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Illustrates the SQL output when a table prefix is defined and applied to a query. The `my_` prefix is automatically added to the `users` table name. ```sql select * from `my_users` ``` -------------------------------- ### Generate Model with Migration (Bash) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Illustrates how to use the AdonisJS CLI to generate both a Lucid model and its corresponding database migration file simultaneously. This streamlines the process of setting up new database-backed models. ```bash > adonis make:model User --migration ``` -------------------------------- ### Date Management Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Covers how to define, format, and cast date fields in Lucid models. ```APIDOC ## Dates Lucid handles date management gracefully, minimizing manual work. ### Defining Date Fields Define custom date fields by concatenating them in a `dates` getter on your model. By default, `created_at` and `updated_at` are marked as dates. ```javascript class User extends Model { static get dates () { return super.dates.concat(['dob']) } } ``` ### Formatting Date Fields (For Storage) Customize date formats for storage by overriding the `formatDates` method. This method is called before the model instance is saved to the database. ```javascript class User extends Model { static formatDates (field, value) { if (field === 'dob') { return value.format('YYYY-MM-DD') } return super.formatDates(field, value) } } ``` ### Casting Date Fields (For Display) Format dates differently for display using the `castDates` method. The `value` parameter is a Moment.js instance. ```javascript class User extends Model { static castDates (field, value) { if (field === 'dob') { return `${value.fromNow(true)} old` } return super.formatDates(field, value) } } ``` #### Deserialization The `castDates` method is called automatically when a model instance is deserialized (e.g., by calling `toJSON`). ```javascript const users = await User.all() const usersJSON = users.toJSON() ``` ``` -------------------------------- ### Define a Test Case in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc JavaScript snippet illustrating how to define an individual test case within a suite in AdonisJS using the 'test' function obtained from Test/Suite. ```javascript test('return error when credentials are wrong', async (ctx) => { // implementation }) ``` -------------------------------- ### AdonisJs HTTP Client: GET Request Example Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/02-HTTP-Tests.adoc Demonstrates making a simple HTTP GET request to a specified URL using the AdonisJs HTTP client. ```javascript client.get('posts') ``` -------------------------------- ### Close Database Connection Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Example of closing a specific database connection after it's no longer needed. This helps in managing resources, especially in long-running processes. ```javascript const users = await Database .connection('mysql') .table('users') // later close the connection Database.close(['mysql']) ``` -------------------------------- ### Initialize Webpack and Install Dependencies Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/03-frontend-assets.adoc Installs webpack and webpack-cli as development dependencies and creates the webpack configuration file. These are essential for setting up frontend asset bundling. No specific inputs or outputs are defined at this stage, as it's primarily an initialization step. ```bash npm i --save-dev webpack webpack-cli touch webpack.config.js ``` -------------------------------- ### Select Users from Specific Connection Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Illustrates how to explicitly select a database connection at runtime, overriding the default connection. This is useful when managing multiple database configurations. ```javascript Database .connection('mysql') .table('users') ``` -------------------------------- ### AdonisJS Assertion with Exception Handling (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Shows how to handle exceptions within a test and verify error messages using the `assert` object. Demonstrates proper planning of assertions. ```javascript test('must throw exception', async ({ assert }) => { try { await badOperation() } catch ({ message }) { assert.equal(message, 'Some error message') } }) ``` ```javascript test('must throw exception', async ({ assert }) => { assert.plan(1) try { await badOperation() } catch ({ message }) { assert.equal(message, 'Some error message') } }) ``` -------------------------------- ### Find the First Lucid Model Record (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Demonstrates the 'first' static method for retrieving the very first record from a Lucid model's table based on the database's default ordering. This is a simple way to get a sample record from a dataset. ```javascript const User = use('App/Models/User') await User.first() ``` -------------------------------- ### Configure Default Database Connection Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Sets the default database connection to be used by AdonisJs. This file allows customization of connection settings, including the type of database to connect to. ```javascript module.exports = { connection: 'mysql', } ``` -------------------------------- ### Implement WebSocket Chat Controller in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Defines the ChatController with constructor injecting socket and request, plus an onMessage method to handle incoming messages in real-time chat. Depends on AdonisJS WebSocket setup. Inputs: Message object; outputs: Broadcasts or processes messages. Limitations: Incomplete onMessage implementation; extend for full broadcasting. ```javascript 'use strict' class ChatController { constructor ({ socket, request }) { this.socket = socket this.request = request } onMessage (message) { ``` -------------------------------- ### Enable Global Query Debugging Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Enables debugging for all database queries globally by setting `debug: true` in the database configuration. This logs all executed SQL queries. ```javascript module.exports = { connection: 'sqlite', sqlite: { client: 'sqlite3', connection: {}, debug: true } } ``` -------------------------------- ### Configure slow query threshold in AdonisJs Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Sets up slow query monitoring in the database configuration file. Enables tracking and defines the execution time threshold in milliseconds. ```javascript module.exports = { connection: 'sqlite', sqlite: { client: 'sqlite3', slowQuery: { enabled: true, threshold: 5000 } } } ``` -------------------------------- ### Register Vow Provider in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/01-Getting-Started.adoc Configuration snippet for registering the VowProvider in the start/app.js file of an AdonisJS application. It should be added to the aceProviders array. ```javascript const aceProviders = [ '@adonisjs/vow/providers/VowProvider' ] ``` -------------------------------- ### Reading Request Body Data (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Provides JavaScript examples for reading various parts of the HTTP request body using the `request` object's methods: `all`, `get`, `post`, `raw`, `only`, `except`, and `input`. ```javascript const all = request.all() const query = request.get() const body = request.post() const raw = request.raw() const data = request.only(['username', 'email', 'age']) const data = request.except(['csrf_token', 'submit']) const drink = request.input('drink') const drink = request.input('drink', 'coffee') ``` -------------------------------- ### Model Boot Cycle Method in JavaScript Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Explains the model boot cycle in AdonisJS, where the `boot` method of each model is called once during application initialization. This method is suitable for performing actions that should only occur once, such as setting up model-specific configurations or event listeners. ```javascript const Model = use('Model') class User extends Model { static boot () { super.boot() /** I will be called only once */ } } module.exports = User ``` -------------------------------- ### Setting Up Japa Tests for AdonisJS Provider in Bash Source: https://github.com/adonisjs/legacy-docs/blob/4.1/02-Concept/03-service-providers.adoc Series of bash commands to install Japa testing framework, create test directory, run individual tests with Node, install Japa CLI, and execute all tests. Purpose is to facilitate unit testing of the service provider. Depends on npm for installations; inputs are commands in project root, outputs are installed packages, created directories, and executed tests. No specific limitations noted beyond standard npm behavior. ```bash npm i --save-dev japa ``` ```bash mkdir test ``` ```bash node test/example.spec.js ``` ```bash npm i --save-dev japa-cli ``` ```bash ./node_modules/.bin/japa ``` -------------------------------- ### Register Lucid Providers in app.js Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Registers the necessary providers for Lucid ORM and Migrations within the AdonisJs application. This ensures that the database functionalities are available throughout the application. ```javascript const providers = [ '@adonisjs/lucid/providers/LucidProvider' ] const aceProviders = [ '@adonisjs/lucid/providers/MigrationsProvider' ] ``` -------------------------------- ### Generate WebSocket Controller using AdonisJS CLI Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Creates a new WebSocket-specific controller in app/Controllers/Ws/ via the make:controller command, setting up the basic structure for handling socket events. Requires AdonisJS CLI. Inputs: Controller name and type; outputs: New JS file. Limitations: Generates skeleton; manual implementation needed for logic. ```bash > adonis make:controller Chat --type=ws ``` -------------------------------- ### Create WebSocket controller with socket context Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Defines a WebSocket controller constructor that receives a context object containing the socket instance. This pattern enables access to the socket for event handling and messaging. ```javascript class ChatController { constructor ({ socket }) { this.socket = socket } } ``` -------------------------------- ### Install AdonisJS WebSocket Client Package Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/04-Client-API.adoc Installs the @adonisjs/websocket-client via NPM for bundling or directly from UNPKG. Requires polyfill for regenerator-runtime in built environments. For production, define NODE_ENV to remove logs. NPM installs the package, UNPKG provides UMD bundle. ```bash > npm i @adonisjs/websocket-client ``` ```html ``` -------------------------------- ### Get Primary Keys (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet shows how to retrieve an array of primary keys from a database table leveraging the `ids` method. It uses the User model. ```JavaScript const User = use('App/Models/User') const userIds = await User.ids() ``` -------------------------------- ### Select All Rows (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet demonstrates how to retrieve all rows from a database table using the `all` method. It uses the User model. ```JavaScript const User = use('App/Models/User') const users = await User.all() ``` -------------------------------- ### Install AdonisJS Auth Provider Source: https://github.com/adonisjs/legacy-docs/blob/4.1/05-Security/02-Authentication.adoc Command to install the AdonisJS auth provider. This is necessary if the auth provider is not pre-installed in your boilerplate. ```bash > adonis install @adonisjs/auth ``` -------------------------------- ### Generate Lucid Model (Bash) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Shows the command-line interface command to generate a new Lucid model file within an AdonisJS project. This command creates the basic structure for a model class. ```bash > adonis make:model User ``` -------------------------------- ### Install and Register Shield Provider Source: https://github.com/adonisjs/legacy-docs/blob/4.1/05-Security/08-Shield-Middleware.adoc Installs the @adonisjs/shield package and registers the ShieldProvider in the start/app.js file. Ensure sessions are set up as Shield middleware relies on them. ```bash > adonis install @adonisjs/shield ``` ```javascript const providers = [ '@adonisjs/shield/providers/ShieldProvider' ] ``` -------------------------------- ### Get Record Count (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet shows how to return a count of records in a given result set using the `getCount` method. You can also add query constraints before calling the method. ```JavaScript const User = use('App/Models/User') // returns number await User.getCount() ``` ```JavaScript await User .query() .where('is_active', 1) .getCount() ``` -------------------------------- ### Install Drive Provider with npm Source: https://github.com/adonisjs/legacy-docs/blob/4.1/06-Digging-Deeper/04-File-Storage.adoc This command installs the @adonisjs/drive package, which provides the file storage capabilities. Ensure you are in your AdonisJS project directory when running this command. ```bash adonis install @adonisjs/drive ``` -------------------------------- ### Starting AdonisJs App with PM2 Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/01-nginx-proxy.adoc This snippet demonstrates how to start your AdonisJs application using PM2, a popular process manager for Node.js applications. It ensures your application runs reliably in the background. Commands include starting the server, listing running processes, and viewing logs. ```bash pm2 start server.js pm2 list pm2 logs ``` -------------------------------- ### Primary Key Management Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Demonstrates how to access and update the primary key value when the model is not set to auto-incrementing. ```APIDOC ## Primary Key Management Access and update the primary key value when `incrementing` is set to `false`. ### Method - Accessing: `user.primaryKeyValue` - Updating: `user.primaryKeyValue = 'new-uuid'` ### Request Example ```javascript const user = await User.find(1) console.log(user.primaryKeyValue) // when incrementing is false user.primaryKeyValue = uuid.v4() ``` ``` -------------------------------- ### Register WebSocket Channel to Controller in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Binds a channel like 'chat' to a controller in start/socket.js using the Ws use statement, enabling event handling for real-time interactions. Depends on the booted WebSocket server. Inputs: Channel name and controller; outputs: Subscribable channel. Limitations: Recommends dedicated controllers over closures for better organization. ```javascript const Ws = use('Ws') Ws.channel('chat', 'ChatController') ``` -------------------------------- ### Paginate Results (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet illustrates how to paginate results using the `paginate` method. It returns an object containing metadata and a `data` property with the paginated users. ```JavaScript const User = use('App/Models/User') const page = 1 const users = await User.query().paginate(page) return view.render('users', { users: users.toJSON() }) ``` ```JavaScript { total: '', perPage: '', lastPage: '', page: '', data: [{...}] } ``` -------------------------------- ### Install hotel globally via npm Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/02-dev-domains.adoc Installs the hotel package globally to enable domain registration for local development URLs. Requires Node.js and npm to be installed. ```bash npm install -g hotel ``` -------------------------------- ### Listen for Query Event Locally Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Enables query debugging for a single query at runtime by attaching an event listener directly to the query object. This is useful for debugging specific operations without affecting the entire application. ```javascript await Database .table('users') .select('*') .on('query', console.log) ``` -------------------------------- ### Install AdonisJS Session Provider Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/07-Sessions.adoc Command to install the official AdonisJS session provider package. This command also generates the configuration file for sessions. ```bash > adonis install @adonisjs/session ``` -------------------------------- ### Bind to WebSocket events using controller methods Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Maps controller methods to WebSocket events by prefixing method names with 'on'. Supports message, close, and error events. Each method corresponds to a specific socket event listener. ```javascript class ChatController { onMessage () { // same as: socket.on('message') } onClose () { // same as: socket.on('close') } onError () { // same as: socket.on('error') } } ``` -------------------------------- ### Broadcast message to all clients via WebSocket Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Sends a message to all connected WebSocket clients using the broadcastToAll method. Requires an active socket connection and message data as input. ```javascript this.socket.broadcastToAll('message', message) ``` -------------------------------- ### Query with Table Prefix Ignored Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Demonstrates how to bypass the configured table prefix for a specific query using the `withOutPrefix` method. This allows querying tables without the prefix, even if one is globally defined. ```javascript await Database .withOutPrefix() .table('users') ``` -------------------------------- ### Get Request Protocol Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Returns the protocol used for the incoming request (e.g., 'http' or 'https'). Essential for generating correct URLs or understanding the connection security. ```javascript const protocol = request.protocol() ``` -------------------------------- ### Generated User Model Structure (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Presents the default structure of a User model generated by the AdonisJS CLI. This includes the basic class definition extending the base Lucid Model. ```javascript 'use strict' const Model = use('Model') class User extends Model { } module.exports = User ``` -------------------------------- ### Accessing Route Formats via URL Examples Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/01-Routing.adoc Demonstrates URL patterns for different formats after defining .formats(['json']). Purpose is client-server negotiation. Input HTTP GET with/without .json; output JSON or HTML. Bash curl-like, but actual requests depend on server. ```bash GET /users.json # Returns an array of users in JSON GET /users # Returns the view in HTML ``` -------------------------------- ### Creating Model Instances in JavaScript Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Illustrates two ways to create model instances: directly setting attributes after instantiation and using the `create` method with request data. The `create` method is a shortcut for saving a new instance with provided attributes. Both methods are asynchronous and return the saved model instance. ```javascript const User = use('App/Models/User') const userData = request.only(['username', 'email', 'age']) // save and get instance back const user = await User.create(userData) ``` -------------------------------- ### Get Help for the `migration:run` Command Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/03-Migrations.adoc Provides detailed options and usage information for the `migration:run` command. Flags like `--force` and `--silent` allow for customization of the migration execution process. ```bash > adonis migration:run --help ``` -------------------------------- ### Install Antl Provider (Bash) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/06-Digging-Deeper/06-Internationalization.adoc Command to install the Antl Provider package using npm for AdonisJs projects. No specific inputs or outputs, simply installs the package. ```bash > adonis install @adonisjs/antl ``` -------------------------------- ### Track slow SQL queries in AdonisJs Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/01-Getting-Started.adoc Listens for slow SQL queries in AdonisJs and logs them with their execution time. The event listener triggers when a query exceeds the configured threshold. ```javascript Database.on('slow:query', (sql, time) => { console.log(`${time}: ${sql.query}`) }) ``` -------------------------------- ### Install Redis Provider - Bash Source: https://github.com/adonisjs/legacy-docs/blob/4.1/07-Database/05-Redis.adoc Command to install the Redis provider for AdonisJs. This is the first step to enable Redis integration in your AdonisJs application. No direct dependencies are needed beyond npm. ```bash > adonis install @adonisjs/redis ``` -------------------------------- ### Create new AdonisJS project (bash) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/06-number-guessing-game.adoc Initializes a new AdonisJS project with the slim option, which excludes database and model setup for simplicity. ```bash adonis new number-game --slim ``` -------------------------------- ### Start hotel daemon on port 2000 Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/02-dev-domains.adoc Starts the hotel proxy server as a daemon on port 2000. This must be running to register and manage .dev domains. ```bash hotel start ``` -------------------------------- ### AdonisJs Ignitor: Preloading Files After HTTP Server Start Source: https://github.com/adonisjs/legacy-docs/blob/4.1/02-Concept/05-ignitor.adoc Shows how to use the `preLoad` method of the Ignitor instance to preload specific JavaScript files after the HTTP server has started. The `preLoad` method accepts a relative or absolute path to the file. Multiple files can be preloaded by calling `preLoad` multiple times. ```javascript new Ignitor(require('@adonisjs/fold')) .appRoot(__dirname) .preLoad('start/fire-zombies') .fireHttpServer() .catch(console.error) ``` ```javascript new Ignitor(require('@adonisjs/fold')) .preLoad('') .preLoad('') // etc ``` -------------------------------- ### Override Model Database Connection (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Illustrates how to specify a custom database connection for a Lucid model by implementing a static `connection` getter. This allows models to use different database configurations. ```javascript class User extends Model { static get connection () { return 'mysql' } } ``` -------------------------------- ### Install and Register Mail Provider - Bash and JS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/06-Digging-Deeper/07-Mails.adoc Installs the AdonisJS Mail provider via npm and registers it in the app's providers array. Requires Node.js and npm. Takes no input; outputs provider registration. Limited to providers available at installation time. ```bash > adonis install @adonisjs/mail ``` ```js const providers = [ '@adonisjs/mail/providers/MailProvider' ] ``` -------------------------------- ### Pair Rows (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet illustrates how to return an object of key-value pairs from the database table using the `pair` method. The first argument is used as a key and the second as a value. It uses the User model. ```JavaScript const User = use('App/Models/User') const users = await User.pair('id', 'country') ``` -------------------------------- ### Using Global View in Boot Method (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/02-Concept/03-service-providers.adoc Shows how to use existing bindings to bootstrap application state by adding a global view in the `boot` method. ```javascript boot () { const View = this.app.use('Adonis/Src/View') View.global('time', () => new Date().getTime()) } ``` -------------------------------- ### Show Specific Fields in Lucid Model Results (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Demonstrates how to specify which fields should be included in Lucid Model query results, effectively hiding all others. This is useful when you only need a subset of data, for example, displaying only the title and body of a post. ```javascript class Post extends Model { static get visible () { return ['title', 'body'] } } ``` -------------------------------- ### Define Login and Profile Routes in start/routes.js Source: https://github.com/adonisjs/legacy-docs/blob/4.1/05-Security/02-Authentication.adoc Example routes for user login and profile access. The login route uses the guest middleware, while the profile route requires authentication. ```javascript Route .post('login', 'UserController.login') .middleware('guest') Route .get('users/:id', 'UserController.show') .middleware('auth') ``` -------------------------------- ### Pick Rows (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet showcases how to pick a specific number of rows from a database table using the `pick` method. The method defaults to picking one row if no value is provided. It utilizes the User model. ```JavaScript const User = use('App/Models/User') await User.pick(3) ``` -------------------------------- ### Performing Bulk Updates with Query Builder in JavaScript Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Details how to perform bulk updates on model records using the Query Builder. The example filters users by username and updates their role to 'admin'. This method is efficient for modifying multiple records at once. Note that bulk updates do not trigger model hooks. ```javascript const User = use('App/Models/User') await User .query() .where('username', 'virk') .update({ role: 'admin' }) ``` -------------------------------- ### Configure Node.js Cluster for WebSocket Pub/Sub Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Sets up clustering in server.js to fork worker processes and connect pub/sub communication for WebSocket scalability across Node.js processes. Depends on Node.js cluster module and @adonisjs/websocket. Inputs: Number of workers (e.g., 4); outputs: Master process manages workers with pub/sub. Limitations: Only runs on master node; rest of server code follows. ```javascript const cluster = require('cluster') if (cluster.isMaster) { for (let i=0; i < 4; i ++) { cluster.fork() } require('@adonisjs/websocket/clusterPubSub')() return } // ... ``` -------------------------------- ### Method Spoofing via Query String Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Allows HTML forms to use methods other than GET/POST by appending a '_method' parameter to the query string. This example shows how to define a PUT route and simulate it with a POST form. ```javascript // routes.js Route.put('users', 'UserController.update') // HTML Form //
``` -------------------------------- ### Update Dependencies with npm-check Source: https://github.com/adonisjs/legacy-docs/blob/4.1/01-Preface/02-upgrade-guide.adoc Installs and runs npm-check to interactively update project dependencies to their latest versions. This is the first step in the upgrade process. ```bash npm install -g npm-check npm-check -u ``` -------------------------------- ### Installing and Registering Ally Provider in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/06-Digging-Deeper/08-Social-Authentication.adoc Installs the Ally provider via npm and registers it in the application to enable social authentication. Requires Node.js and AdonisJS CLI. No inputs needed beyond the command; outputs the provider file and updates app.js. Limitation: Must run in an AdonisJS project directory. ```bash > adonis install @adonisjs/ally ``` ```javascript const providers = [ '@adonisjs/ally/providers/AllyProvider' ] ``` -------------------------------- ### Get Attribute Value (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/10-testing/03-browser-tests.adoc Retrieves the value of a specific attribute from an HTML element identified by a CSS selector. For example, getting the 'href' of a link or 'data-tip' of a tooltip. ```javascript const dataTip = await page .getAttribute('div.tooltip', 'data-tip') ``` -------------------------------- ### Find or Create Record (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet demonstrates how to find a record based on a given criteria. If the record is not found, it creates a new record with the specified attributes and returns the newly created record. Uses `findOrCreate` method. ```JavaScript const User = use('App/Models/User') const user = await User.findOrCreate( { username: 'virk' }, { username: 'virk', email: 'virk@adonisjs.com' } ) ``` -------------------------------- ### Get HTTP Request Method Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Returns the HTTP method used for the current request (e.g., GET, POST, PUT, DELETE). Essential for routing and request handling logic. ```javascript const method = request.method() ``` -------------------------------- ### Install Babel for JavaScript Transpilation Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/03-frontend-assets.adoc Installs Babel loaders and presets required for transpiling modern JavaScript (ES6+) to ES5. This ensures compatibility with older browsers. These packages are essential for using features like arrow functions and classes in frontend JavaScript code. ```bash npm i --save-dev babel-loader @babel/core @babel/preset-env ``` -------------------------------- ### Client-Side WebSocket Connection and Chat in AdonisJS Source: https://github.com/adonisjs/legacy-docs/blob/4.1/09-WebSockets/01-Getting-Started.adoc Establishes WebSocket connection, subscribes to 'chat' channel, handles messages, and sends user input on Enter key press using jQuery in public/chat.js. Depends on AdonisJS client WS and jQuery; assumes username in window.username and DOM elements like .messages. Inputs: User messages; outputs: Appended chat divs. Limitations: Simple delivery without persistence; requires route for HTML template. ```javascript let ws = null $(function () { // Only connect when username is available if (window.username) { startChat() } }) function startChat () { ws = adonis.Ws().connect() ws.on('open', () => { $('.connection-status').addClass('connected') subscribeToChannel() }) ws.on('error', () => { $('.connection-status').removeClass('connected') }) } // ... function subscribeToChannel () { const chat = ws.subscribe('chat') chat.on('error', () => { $('.connection-status').removeClass('connected') }) chat.on('message', (message) => { $('.messages').append(`

${message.username}

${message.body}

`) }) } // ... $('#message').keyup(function (e) { if (e.which === 13) { e.preventDefault() const message = $(this).val() $(this).val('') ws.getSubscription('chat').emit('message', { username: window.username, body: message }) return } }) ``` -------------------------------- ### Find the First Lucid Model Record or Throw Exception (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Explains the 'firstOrFail' static method, which retrieves the first record from a Lucid model's table. If the table is empty, it throws a 'ModelNotFoundException', ensuring that you are aware when no records are available. ```javascript const User = use('App/Models/User') await User.firstOrFail() ``` -------------------------------- ### AdonisJS Session get() Method Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/07-Sessions.adoc Demonstrates the `get` method for retrieving a value from the session store using its key. It also shows how to provide a default value if the key does not exist. ```javascript session.get('username') // default value session.get('username', 'defaultName') ``` -------------------------------- ### Chrome browser proxy configuration (Linux/OSX) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/02-dev-domains.adoc Starts Chrome browser with proxy configuration pointing to hotel's proxy.pac file. Requires Chrome to be closed before running. ```bash # Linux google-chrome --proxy-pac-url=http://localhost:2000/proxy.pac # OS X open -a "Google Chrome" --args --proxy-pac-url=http://localhost:2000/proxy.pac ``` -------------------------------- ### Install CORS Middleware - Bash Source: https://github.com/adonisjs/legacy-docs/blob/4.1/05-Security/04-CORS.adoc Installs the CORS middleware package for AdonisJS using npm. This is the first step to enable CORS functionality. ```bash adonis install @adonisjs/cors ``` -------------------------------- ### Install pem for self-signed certificates Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/05-https.adoc Installs the pem package from npm, which is used to generate self-signed certificates for development purposes. ```Bash npm i pem ``` -------------------------------- ### Get Request Subdomains Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Returns a list of subdomains from the request hostname. The 'www' subdomain is automatically removed from the list. ```javascript const subdomains = request.subdomains() ``` -------------------------------- ### Registering Bindings with Service Provider (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/02-Concept/03-service-providers.adoc Demonstrates how to create a service provider in AdonisJs using ES6 classes, registering bindings in the `register` method, and bootstrapping application state in the `boot` method. ```javascript const { ServiceProvider } = require('@adonisjs/fold') class MyProvider extends ServiceProvider { register () { // register bindings } boot () { // optionally do some initial setup } } module.exports = MyProvider ``` -------------------------------- ### Get Request Hostname Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Retrieves the hostname from the incoming request. This is useful for routing, logging, or differentiating requests on multi-tenant applications. ```javascript const hostname = request.hostname() ``` -------------------------------- ### AdonisJS Session all() Method Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/07-Sessions.adoc Example of the `all` method, which retrieves all key/value pairs currently stored in the session as an object. ```javascript session.all() ``` -------------------------------- ### Pick Inverse Rows (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet demonstrates how to pick a specific number of rows from a database table starting from the last row, using the `pickInverse` method. The method defaults to picking one row if no value is provided. It utilizes the User model. ```JavaScript const User = use('App/Models/User') await User.pickInverse(3) ``` -------------------------------- ### AdonisJS Flash Messages HTML Form Example Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/07-Sessions.adoc An example using Edge templating to display a form and retrieve old input values and validation errors using session flash message helpers. ```edge {{ csrfField() }} {{ getErrorFor('username') }}
``` -------------------------------- ### Windows network proxy configuration Source: https://github.com/adonisjs/legacy-docs/blob/4.1/recipes/02-dev-domains.adoc Configures Windows system network settings to use hotel's proxy setup script for automatic proxy configuration. ```bash Settings > Network and Internet > Proxy > Use setup script ``` -------------------------------- ### Basic Hello World Edge Template Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/06-Views.adoc Provides a simple 'Hello World' Edge template, demonstrating how to render it using the `view.render` method. The resulting HTML will display 'Hello World!'. ```text

Hello World!

``` -------------------------------- ### Hiding and Visible Fields Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc Explains how to define which fields should be hidden or visible in model outputs, both globally and per query. ```APIDOC ## Hiding Fields Omit fields from database results by defining `hidden` or `visible` attributes on your model classes. ### Hidden Fields Define fields that should always be hidden. ```javascript class User extends Model { static get hidden () { return ['password'] } } ``` ### Visible Fields Define fields that should always be visible. ```javascript class Post extends Model { static get visible () { return ['title', 'body'] } } ``` ### Set Visible/Set Hidden (Per Query) Define `hidden` or `visible` fields for a single query. ```javascript // Hide password for this query User.query().setHidden(['password']).fetch() // Set visible fields for this query User.query().setVisible(['title', 'body']).fetch() ``` ``` -------------------------------- ### Get Request URL Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Retrieves the current request URL without any query strings. This method is useful for logging or basic URL checks. ```javascript const url = request.url() ``` -------------------------------- ### Fill Model Attributes (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet demonstrates how to use the `fill` method to override existing model instance key/pair values. ```JavaScript const User = use('App/Models/User') const user = new User() user.username = 'virk' user.email = 'foo@bar.com' // Fill Example await user.save() ``` -------------------------------- ### Truncate Table (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/08-Lucid-ORM/01-Getting-Started.adoc This snippet shows how to delete all rows from a database table using the `truncate` method. It uses the User model. ```JavaScript const User = use('App/Models/User') const users = await User.truncate() ``` -------------------------------- ### Queue Provider Implementation (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/02-Concept/03-service-providers.adoc Illustrates wrapping an npm package (bee-queue) in a service provider, emphasizing configuration through the `config/queue.js` file and dependency injection. ```javascript 'use strict' const BeeQueue = require('bee-queue') class Queue { constructor (Config) { this.Config = Config this._queuesPool = {} } get (name) { /** * If there is an instance of queue already, then return it */ if (this._queuesPool[name]) { return this._queuesPool[name] } /** * Read configuration using Config * provider */ const config = this.Config.get(`queue.${name}`) /** * Create a new queue instance and save it's * reference */ this._queuesPool[name] = new BeeQueue(name, config) /** * Return the instance back */ return this._queuesPool[name] } } module.exports = Queue ``` ```javascript const { ServiceProvider } = require('@adonisjs/fold') class QueueProvider extends ServiceProvider { register () { this.app.singleton('Bee/Queue', () => { const Config = this.app.use('Adonis/Src/Config') return new (require('.'))(Config) }) } } module.exports = QueueProvider ``` ```javascript const providers = [ path.join(__dirname, '..', 'providers', 'Queue/Provider') ] ``` ```javascript const Queue = use('Bee/Queue') Queue .get('addition') .createJob({ x: 2, y: 3 }) .save() ``` -------------------------------- ### Autoloaded Service (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/02-Concept/02-ioc-container.adoc Example of a service file within an autoloaded directory. No explicit paths are needed in the controller. ```javascript class FooService { } module.exports = FooService ``` -------------------------------- ### Get Trusted IP Address Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Retrieves the most trusted IP address associated with the incoming request. It handles proxies and load balancers to identify the client's IP. ```javascript const ip = request.ip() ``` -------------------------------- ### Get Raw Cookie Data Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Retrieves an object containing all raw cookie data from the incoming request. This is useful for directly accessing cookie values without parsing. ```javascript const plainCookies = request.plainCookies() ``` -------------------------------- ### Handling Array Input from Forms (JavaScript) Source: https://github.com/adonisjs/legacy-docs/blob/4.1/04-Basics/04-Request.adoc Illustrates how to collect and format array data submitted from HTML forms using `request.only` and `request.collect` for database insertion. ```html
``` ```javascript const users = request.only(['username', 'age']) // output // { username: ['virk', 'nikk'], age: [26, 25] } const users = request.collect(['username', 'age']) // output // [{ username: 'virk', age: 26 }, { username: 'nikk', age: 25 }] // save to db await User.createMany(users) ```