Skip to content
Github

adonisjs-api-query

This package provides a set of methods to filter, sort and include models relations based on a request. Query parameter names follow the JSON API spec as closely as possible. It’s inspired by Laravel Query Builder Spatie.

Install and configure Adonisjs Api Query using the following command.

node ace add @eienjs/adonisjs-api-query

The package will automatically register its service provider.

If you’re enable Async local storage not need extra steps to use this package. Otherwise you need pass first request to query builder. For example:

import { type HttpContext } from '@adonisjs/core/http';
import User from '#models/user';

// inside a controller
export default class MyController {
  public async handle({ request }: HttpContext) {
    const users = await User.query()
      .withRequest(request) // Pass the request to the query builder if async local storage is not enabled
      .allowedFilters('name')
      .allowedIncludes('posts')
      .allowedSorts('id');
  }
}

Request: /users?filter[name]=John

const users = await User.query().allowedFilters('name');

// all Users that contain the string "John" in their name

Request: /users?include=posts

const users = await User.query().allowedIncludes('posts');

// all Users with their posts loaded

Request: /users?sort=id

const users = await User.query().allowedSorts('id');

// all Users sorted by ascending id

Works together nicely with existing queries

Section titled “Works together nicely with existing queries”
const users = await User.query()
  .where('active', true)
  .allowedFilters('name')
  .allowedIncludes('posts', 'permissions')
  .allowedSorts('id')
  .paginate(1, 10);