@dirupt/adonis-lucid-filter

中文文档
6.0.3发布于 2026/07/10MITTypeScriptES Module构建来源已验证近 30 天下载 9456

Addon for filtering AdonisJS Lucid ORM (fork with AdonisJS v7 support)

原始使用文档
文档目录13 节
  1. Credits
  2. Versions
  3. Migrating from adonis-lucid-filter
  4. Introduction
  5. Installation
  6. Usage
  7. Generating The Filter
  8. Defining The Filter Logic
  9. Applying The Filter To A Model
  10. Dynamic Filters
  11. Filtering relations
  12. Type-safe input
  13. License

@dirupt/adonis-lucid-filter

Fork of adonis-lucid-filter with AdonisJS v7 support

npm-image ci-image license-image typescript-image

This addon adds the functionality to filter Lucid Models.

Inspired by EloquentFilter Original work by Lookin Anton

Credits

This package is a fork of adonis-lucid-filter by LookinLab, updated for AdonisJS v7 compatibility. All credit for the original implementation goes to the original author.

Versions

@dirupt/adonis-lucid-filter@adonisjs/lucidAdonisJS
^6.*.*^22.*.*v7

For AdonisJS v6, use the original package: adonis-lucid-filter@^5

Migrating from adonis-lucid-filter

If you are coming from the upstream adonis-lucid-filter package, the migration is straightforward:

pnpm remove adonis-lucid-filter
pnpm add @dirupt/adonis-lucid-filter

Then update your imports across the codebase:

- import { BaseModelFilter, Filterable } from 'adonis-lucid-filter'
+ import { BaseModelFilter, Filterable } from '@dirupt/adonis-lucid-filter'

And update your adonisrc.ts:

  providers: [
-   () => import('adonis-lucid-filter/provider'),
+   () => import('@dirupt/adonis-lucid-filter/provider'),
  ],
  commands: [
-   () => import('adonis-lucid-filter/commands')
+   () => import('@dirupt/adonis-lucid-filter/commands')
  ]

Do not keep both packages installed at the same time, they extend the same ModelQueryBuilder and will conflict.

Introduction

Example, we want to return a list of users filtered by multiple parameters. When we navigate to:

/users?name=Tony&lastName=&companyId=2&industry=5

request.all() or request.qs() will return:

{
  "name": "Tony",
  "lastName": "",
  "companyId": 2,
  "industry": 5
}

To filter by all those parameters we would need to do something like:

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

export default class UsersController {
  async index({ request }: HttpContext): Promise<User[]> {
    const { companyId, lastName, name, industry } = request.qs()

    const query = User.query().where('company_id', +companyId)

    if (lastName) {
      query.where('last_name', 'LIKE', `%${lastName}%`)
    }
    if (name) {
      query.where(function () {
        this.where('first_name', 'LIKE', `%${name}%`)
          .orWhere('last_name', 'LIKE', `%${name}%`)
      })
    }
    return query.exec()
  }
}

To filter that same input with Lucid Filters:

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

export default class UsersController {
  async index({ request }: HttpContext): Promise<User[]> {
    return User.filter(request.qs()).exec()
  }
}

Installation

Requires Node.js 24+ and TypeScript with strict: true for full type inference on filter inputs.

pnpm add @dirupt/adonis-lucid-filter

After install call configure:

node ace configure @dirupt/adonis-lucid-filter

Usage

Make sure to register the provider and commands inside adonisrc.ts file.

providers: [
  // ...
  () => import('@dirupt/adonis-lucid-filter/provider'),
],
commands: [
  // ...
  () => import('@dirupt/adonis-lucid-filter/commands')
]

Generating The Filter

You can create a model filter with the following ace command:

node ace make:filter user

Where user is the Lucid Model you are creating the filter for. This will create app/models/filters/user_filter.ts

Defining The Filter Logic

Define the filter logic based on the camel cased input key passed to the filter() method.

  • Empty strings are ignored
  • setup() will be called regardless of input
  • _id is dropped from the end of the input to define the method so filtering user_id would use the user() method
  • Input without a corresponding filter method are ignored
  • The value of the key is injected into the method
  • All values are accessible through the this.$input property
  • All QueryBuilder methods are accessible in this.$query object in the model filter class.

To define methods for the following input:

{
  "companyId": 5,
  "name": "Tony",
  "mobilePhone": "888555"
}

You would use the following methods:

import { BaseModelFilter } from '@dirupt/adonis-lucid-filter'
import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
import User from '#models/user'

export default class UserFilter extends BaseModelFilter {
  declare $query: ModelQueryBuilderContract<typeof User>

  static blacklist: string[] = ['secretMethod']

  company(id: number) {
    this.$query.where('company_id', id)
  }

  name(name: string) {
    this.$query.where((builder) => {
      builder
        .where('first_name', 'LIKE', `%${name}%`)
        .orWhere('last_name', 'LIKE', `%${name}%`)
    })
  }

  mobilePhone(phone: string) {
    this.$query.where('mobile_phone', 'LIKE', `${phone}%`)
  }

  secretMethod(secretParameter: any) {
    this.$query.where('some_column', true)
  }
}

Blacklist

Any methods defined in the blacklist array will not be called by the filter. Those methods are normally used for internal filter logic.

The whitelistMethod() method can be used to dynamically whitelist methods.

Example:

setup($query) {
  this.whitelistMethod('secretMethod')
  this.$query.where('is_admin', true)
}

setup() may not be async

Static properties

export default class UserFilter extends BaseModelFilter {
  // Blacklisted methods
  static blacklist: string[] = []

  // Dropped `_id` from the end of the input
  static dropId: boolean = true

  // Convert input keys to camelCase method names
  static camelCase: boolean = true
}

Applying The Filter To A Model

import UserFilter from '#models/filters/user_filter'
import { compose } from '@adonisjs/core/helpers'
import { Filterable } from '@dirupt/adonis-lucid-filter'

export default class User extends compose(BaseModel, Filterable) {
  static $filter = () => UserFilter

  // ...columns and props
}

This gives you access to the filter() method that accepts an object of input:

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

export default class UsersController {
  async index({ request }: HttpContext): Promise<User[]> {
    return User.filter(request.qs()).exec()
  }

  // or with paginate method

  async index({ request }: HttpContext): Promise<ModelPaginatorContract<User>> {
    const { page = 1, ...input } = request.qs()
    return User.filter(input).paginate(page, 15)
  }
}

Dynamic Filters

You can define the filter dynamically by passing the filter to use as the second parameter of the filter() method.

import type { HttpContext } from '@adonisjs/core/http'
import AdminFilter from '#models/filters/admin_filter'
import UserFilter from '#models/filters/user_filter'

export default class UsersController {
  async index({ request, auth }: HttpContext): Promise<User[]> {
    const filter = auth.user.isAdmin() ? AdminFilter : UserFilter
    return User.filter(request.qs(), filter).exec()
  }
}

Filtering relations

For filtering relations of model you may use .query().filter() or scope filtration:

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

export default class UserPostsController {
  async index({ params, request }: HttpContext): Promise<Post[]> {
    const user: User = await User.findOrFail(params.user_id)

    return user.related('posts').query()
      .apply(scopes => scopes.filtration(request.qs()))
      .exec()

    // or

    return user.related('posts').query().filter(request.qs()).exec()
  }
}

The relation model must have the Filterable mixin and $filter must be defined

Type-safe input

The package exposes an InputObject<> helper that infers accepted input keys directly from your filter class. Both snake_case, camelCase and _id variants are recognised:

import type { InputObject } from '@dirupt/adonis-lucid-filter/types/filter'
import type UserFilter from '#models/filters/user_filter'

type UserFilterInput = InputObject<UserFilter>
// → { company?: number; companyId?: number; company_id?: number;
//     name?: string; mobilePhone?: string; mobile_phone?: string; ... }

// Useful to type request payloads or DTOs:
async index({ request }: HttpContext) {
  const input = request.qs() as UserFilterInput
  return User.filter(input).exec()
}

Your IDE will autocomplete the legal keys based on the methods you declared on UserFilter.

License

MIT

版本与发布记录

@dirupt/adonis-lucid-filter 共发布 4 个版本,首次发布于 2026/03/07;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.0.3latest2026/07/104 个月前
6.0.22026/05/225 个月前
6.0.12026/05/215 个月前
6.0.02026/03/078 个月前

关于 @dirupt/adonis-lucid-filter 的常见问题

@dirupt/adonis-lucid-filter 是什么?

Addon for filtering AdonisJS Lucid ORM (fork with AdonisJS v7 support)

如何安装 @dirupt/adonis-lucid-filter?

在项目目录运行 npm install @dirupt/adonis-lucid-filter,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@adonisjs/core(^7.0.0)、@adonisjs/lucid(^22.0.0)、lodash(^4.17.21)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dirupt/adonis-lucid-filter 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dirupt/adonis-lucid-filter 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@dirupt/adonis-lucid-filter 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dirupt/adonis-lucid-filter 可以商用吗?

@dirupt/adonis-lucid-filter 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dirupt/adonis-lucid-filter 的下载量有多少?

根据 npm 官方下载统计,@dirupt/adonis-lucid-filter 在 2026/10/13 – 2026/11/11 这 30 天内被下载 9,456 次,日均约 315 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dirupt/adonis-lucid-filter 还在维护吗?

最新版本 6.0.3 发布于 2026/07/10(4 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/03/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。