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.
Installation
Section titled “Installation”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.
Basic Usage
Section titled “Basic Usage”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'); } }
Filter a query based on a request
Section titled “Filter a query based on a request”Request: /users?filter[name]=John
const users = await User.query().allowedFilters('name'); // all Users that contain the string "John" in their name
Including relations based on a request
Section titled “Including relations based on a request”Request: /users?include=posts
const users = await User.query().allowedIncludes('posts'); // all Users with their posts loaded
Sorting a query based on a request
Section titled “Sorting a query based on a request”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);