@dudousxd/nestjs-filter

中文文档
2.1.0发布于 2026/11/13MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 4052

NestJS filter library — core abstractions, runner, decorators.

原始使用文档
文档目录10 节
  1. Install
  2. Quick Start
  3. API Reference
  4. Decorators
  5. Classes
  6. Exceptions
  7. Exception Filter
  8. Testing (from @dudousxd/nestjs-filter/testing )
  9. Types
  10. Configuration

@dudousxd/nestjs-filter

Core package for nestjs-filter -- declarative, ORM-agnostic filter classes for NestJS.

Provides BaseFilter, FilterRunner, decorators (@Filterable, @FilterFor, @ApplyFilter), FilterModule, exception handling, and testing utilities.

Install

pnpm add @dudousxd/nestjs-filter

You also need an ORM adapter package:

# MikroORM
pnpm add @dudousxd/nestjs-filter-mikro-orm

# TypeORM
pnpm add @dudousxd/nestjs-filter-typeorm

Quick Start

import { Injectable } from '@nestjs/common';
import { Filterable, FilterFor, BaseFilter, FilterModule, ApplyFilter } from '@dudousxd/nestjs-filter';

// 1. Define a filter
@Injectable()
@Filterable({ entity: User })
class UserFilter extends BaseFilter<QueryBuilder> {
  @FilterFor('name')
  applyName(value: string) {
    this.$query.andWhere({ name: value });
  }
}

// 2. Register
@Module({
  imports: [
    FilterModule.forRoot({ inputNormalizer: 'camelCase' }),
    FilterModule.forFeature([UserFilter]),
  ],
})
class AppModule {}

// 3. Use in controller
@Controller('users')
class UsersController {
  @Get()
  list(@ApplyFilter(UserFilter) qb: QueryBuilder) {
    return qb.getResultList();
  }
}

API Reference

Decorators

  • @Filterable({ entity, allowed?, blocked? }) -- Class decorator. Associates a filter with an entity. allowed whitelists keys; blocked blacklists them. A blacklisted key is barred from filtering entirely: it is skipped in structured dispatch and dropped from where column filters (matching clauses are ignored with a warning, at any depth, rather than rejected). The runtime blacklistMethod(key) behaves the same; whitelistMethod/allowed grant dispatch access and do not constrain where.
  • @FilterFor(inputKey?) -- Method decorator. Maps an input key to the method. Defaults to the method name if omitted.
  • @ApplyFilter(FilterClass, options?) -- Parameter decorator. Resolves input from the request, runs the filter, and injects the QueryBuilder. Options: source ('auto'|'query'|'body'|Function), dto, resolve (dynamic filter selection).

Classes

  • BaseFilter<TQuery> -- Abstract base class. Provides $query, $input, $context, $adapter via AsyncLocalStorage. Optional setup() hook.
  • FilterRunner -- Injectable service. apply(FilterClass, input, qb, context?) runs a filter programmatically.
  • FilterModule -- forRoot(options?) registers global infrastructure. forFeature(filters) registers filter classes.

Exceptions

  • FilterException -- Abstract base.
  • FilterNotRegisteredException -- Filter class not in DI container.
  • FilterMissingEntityException -- Missing @Filterable({ entity }).
  • FilterStateUnavailableException -- Accessing $query outside FilterRunner.apply().
  • UnknownFilterKeyException -- Unknown key when onUnknownKey: 'throw'.
  • FilterValidationException -- class-validator validation failed.
  • FilterMethodException -- A filter method (or setup()) threw an error.

Exception Filter

  • FilterExceptionFilter -- Catches FilterValidationException and returns { statusCode: 400, message, errors }.

Client-facing messages (this one and the runner's 400s) are translated through @nestjs/i18n when the app registers it (optional peer, >= 0.0.3 < 1.0), as filter.* keys; merge @dudousxd/nestjs-filter/i18n/en.json / pt-BR.json into your catalogs. Missing keys stay in English. See the Controllers guide ("Translated messages").

Testing (from @dudousxd/nestjs-filter/testing)

  • FilterTestingModule -- forRoot(options?) and forFeature(filters). Defaults to validation: 'off'.
  • makeMockQueryBuilder<E>() -- Proxy-based mock QB that records all calls. Access via qb.calls.

Types

  • FilterInput<F> -- Extracts the input shape from a filter class.
  • FilterContext -- { req?, user?, raw? }.
  • FilterModuleOptions -- { inputNormalizer?, dropId?, onUnknownKey?, validation? }.
  • ApplyFilterOptions -- { source?, dto?, resolve? }.
  • InputSource -- 'auto' | 'query' | 'body' | ((req) => Record<string, unknown>).

Configuration

OptionTypeDefaultDescription
inputNormalizer'camelCase' | 'snakeCase' | fn'camelCase'Normalize input keys.
dropIdbooleanset explicitlyStrip trailing Id/_id. Effective default is currently inconsistent in the code — when run through FilterRunner/@ApplyFilter the suffix is stripped unless you pass dropId: false.
onUnknownKey'ignore' | 'warn' | 'throw''ignore'Policy for unrecognized structured filter keys (no @FilterFor, auto-field, relation, computed field or aggregate path). Unknown columns inside a where[] clause are governed by throwOnInvalid instead.
throwOnInvalidbooleanfalseWhen true, invalid sorts, distinct fields, and unknown where[] columns raise a BadRequestException instead of being dropped with a warning. Overridable per @Filterable.
validation'auto' | 'off''auto'Validate with class-validator if installed.

See the root README for full documentation.

版本与发布记录

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

版本发布日期距今
2.1.0latest2026/11/13今天
2.0.12026/11/121 天前
1.37.12026/11/094 天前
1.37.02026/11/085 天前
1.36.02026/11/0211 天前
2.0.02026/11/0111 天前

关于 @dudousxd/nestjs-filter 的常见问题

@dudousxd/nestjs-filter 是什么?

NestJS filter library — core abstractions, runner, decorators.

如何安装 @dudousxd/nestjs-filter?

在项目目录运行 npm install @dudousxd/nestjs-filter,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(>=7.0.0)、@nestjs/core(>=10.0.0)、@nestjs/common(>=10.0.0)、reflect-metadata(>=0.1.13)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。它还提供命令行工具 nestjs-filter,可以用 npx nestjs-filter 直接运行。

@dudousxd/nestjs-filter 支持 TypeScript 吗?

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

@dudousxd/nestjs-filter 支持 ESM 还是 CommonJS?

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

@dudousxd/nestjs-filter 需要什么版本的 Node.js?

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

@dudousxd/nestjs-filter 可以商用吗?

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

@dudousxd/nestjs-filter 的下载量有多少?

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

@dudousxd/nestjs-filter 还在维护吗?

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