Getting Started
Installation
Install and configure @eienjs/adonisjs-api-query in your AdonisJS application.
Requirements
- Node.js:
>= 24.0.0 - AdonisJS Core (
@adonisjs/core):^7.3.4 - AdonisJS Lucid (
@adonisjs/lucid):^22.4.2 - VineJS (
@vinejs/vine):>= 4.4.0(optional, only required if you use query parameter validation)
Quick Installation
Install and configure the package automatically using the AdonisJS ace add command:
node ace add @eienjs/adonisjs-api-query
This command will:
- Install
@eienjs/adonisjs-api-queryusing your detected package manager. - Register the
@eienjs/adonisjs-api-query/providers/api_query_providerprovider in youradonisrc.tsfile. - Generate the
config/apiquery.tsconfiguration file.
Manual Installation
If you prefer to install and configure the package manually, install the package with your package manager:
pnpm add @eienjs/adonisjs-api-query
npm install @eienjs/adonisjs-api-query
yarn add @eienjs/adonisjs-api-query
Then run the configure command to register the provider and publish the config file:
node ace configure @eienjs/adonisjs-api-query
Passing the HTTP Request to the Query Builder
To read query parameters (?filter[...], ?sort=..., ?include=...), the query builder needs access to the current AdonisJS HttpRequest. There are two ways to provide it:
1. Explicitly via .withRequest(request) or $filter(request)
Pass the request from your controller's HttpContext:
app/controllers/users_controller.ts
import type { HttpContext } from '@adonisjs/core/http';
import User from '#models/user';
export default class UsersController {
public async index({ request }: HttpContext) {
// Using inline macros:
const users = await User.query()
.withRequest(request)
.allowedFilters('name')
.allowedSorts('createdAt');
// Or using a Filterable class:
const filteredUsers = await User.$filter(request);
return users;
}
}
2. Automatically via AsyncLocalStorage
If you enable useAsyncLocalStorage in config/app.ts, the package automatically resolves the active HttpRequest via HttpContext.getOrFail().request when you omit .withRequest(request):
import { defineConfig } from '@adonisjs/core/http';
export const http = defineConfig({
useAsyncLocalStorage: true,
});
import User from '#models/user';
export default class UsersController {
public async index() {
// No need to pass `request` when AsyncLocalStorage is enabled
return await User.query()
.allowedFilters('name')
.allowedSorts('createdAt');
}
}
Passing
request explicitly via .withRequest(request) or User.$filter(request) works regardless of whether useAsyncLocalStorage is enabled and is slightly more explicit in tests.