Aviary
Guides

Using Filters in Services

How to apply filters programmatically in services using @ApplyFilter (controller) and FilterRunner.apply() (service).

nestjs-filter provides two primary APIs for applying filters:

  1. @ApplyFilter -- parameter decorator for controllers
  2. FilterRunner.apply() -- programmatic use in services

There is no need for repository wrapper classes. You create a QueryBuilder from your ORM, pass it to FilterRunner.apply(), and continue chaining or executing as usual.


Controller: @ApplyFilter

The @ApplyFilter parameter decorator resolves input from the request, runs the filter, and injects the resulting QueryBuilder directly:

import { Controller, Get } from '@nestjs/common';
import { ApplyFilter } from '@dudousxd/nestjs-filter';
import type { QueryBuilder } from '@mikro-orm/sql';
import { User } from './user.entity.js';
import { UserFilter } from './user.filter.js';

@Controller('users')
export class UsersController {
  @Get()
  list(@ApplyFilter(UserFilter) qb: QueryBuilder<User>) {
    return qb.getResultList();
  }
}

Service: FilterRunner.apply()

For programmatic use in services, inject FilterRunner and call .apply() with a QueryBuilder you create yourself:

import { Injectable } from '@nestjs/common';
import { FilterRunner } from '@dudousxd/nestjs-filter';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { User } from './user.entity.js';
import { UserFilter } from './user.filter.js';

@Injectable()
export class UsersService {
  constructor(
    private readonly runner: FilterRunner,
    private readonly em: SqlEntityManager,
  ) {}

  async search(input: Record<string, unknown>) {
    const qb = this.em.createQueryBuilder(User);
    await this.runner.apply(UserFilter, input, qb);
    return qb.getResultList();
  }
}

This pattern aligns with Spring Boot's Specification approach -- filters are applied to query builders directly, without intermediate repository wrappers.


Injecting a concrete filter class

A filter class registered with FilterModule.forFeature([...]) is a normal NestJS provider, so you can inject it wherever you need it. In practice you rarely need to — FilterRunner.apply() resolves the class from the DI container for you (see the service example above), so you only pass the class reference. Passing the class token is all apply() needs:

import { Injectable } from '@nestjs/common';
import { FilterRunner } from '@dudousxd/nestjs-filter';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { User } from './user.entity.js';
import { UserFilter } from './user.filter.js';

@Injectable()
export class UsersService {
  constructor(
    private readonly runner: FilterRunner,
    private readonly em: SqlEntityManager,
  ) {}

  async search(input: Record<string, unknown>) {
    const qb = this.em.createQueryBuilder(User);
    // `UserFilter` is resolved from the container internally — you never
    // `new` it or look it up yourself.
    await this.runner.apply(UserFilter, input, qb);
    return qb.getResultList();
  }
}

Generic, table-driven filtering (no filter class)

When you want to filter any entity without writing a bespoke filter class — an admin console over many tables, for example — use FilterRunner.applyDynamic(). It reads the entity's ORM metadata (via the adapter) to auto-derive filterable columns, includes, search columns, sort, and pagination. There are no @FilterFor methods, no setup() hook, and no whitelist/blacklist — only what the entity's own schema exposes.

import { Injectable } from '@nestjs/common';
import type { Type } from '@nestjs/common';
import { FilterRunner } from '@dudousxd/nestjs-filter';
import type { SqlEntityManager } from '@mikro-orm/sql';

@Injectable()
export class AdminQueryService {
  constructor(
    private readonly runner: FilterRunner,
    private readonly em: SqlEntityManager,
  ) {}

  // Filter any entity purely from its ORM metadata — no filter class needed.
  async query<E extends object>(entity: Type<E>, input: Record<string, unknown>) {
    const qb = this.em.createQueryBuilder(entity);
    await this.runner.applyDynamic(entity, input, qb);
    return qb.getResultList();
  }
}

For a paginated result plus a total count in one call, use findAndCount(), which owns query execution and loads relations pagination-safely (to-one on the join, to-many in a follow-up query so limit/offset stay correct):

async page<E extends object>(entity: Type<E>, input: Record<string, unknown>) {
  const { rows, total } = await this.runner.findAndCount(entity, input);
  return { data: rows, total };
}

Both applyDynamic() and findAndCount() validate every field against the entity's real columns — unknown where columns, sorts, and select fields are dropped (or rejected when throwOnInvalid is set), so a malformed client query can never reach the ORM as an invalid column.

How the total is computed

total ignores limit/offset, but it does not always cost a second query. A page that comes back shorter than its page size is the tail of the result set, so the total is the offset plus the rows on that page and no COUNT runs. The last page of a list, and any result that fits in one page, is one query. A full page, an empty page past the end, or a grouped query whose rows are not the rows being counted still runs the count. The MikroORM, TypeORM and Drizzle adapters all do this, for both entity rows and distinct projections.

On MikroORM:

  • The count leaves out the LEFT JOINs an include adds, since an eager-load join cannot change which root rows match. A join stays in the count when a condition, a nested join or a projected path references its alias.
  • When the count is needed and can't be derived from the page, the page and the count run concurrently. Inside a transaction they run one after the other, because both would share the transaction's connection.
  • A distinct page over plain columns supplies its own total only when it is the first page and none of its values is null, because count(distinct …) skips the null that select distinct returns as a row.

Trusted page sizes (trustedPageSize)

maxPageSize is a module-level ceiling, and by default it applies to every call. That is right for a size that arrived on an HTTP request — it is what stops a client asking for a million rows — but wrong for a size your own server code wrote: an export, a scheduled report, a batch job. There the cap is not protection, it is a silent wrong answer.

// maxPageSize: 100. This loop writes a 100-row CSV and reports success:
// it asks for 10 000, gets 100, reads 100 < 10 000 as "table exhausted".
const { rows } = await this.runner.findAndCount(entity, {
  paginate: { page, size: 10_000 },
});

Pass trustedPageSize: true to declare at the call site that the size is server-authored, not client input. It lifts the ceiling for that one call and changes nothing else:

const { rows, total } = await this.runner.findAndCount(
  entity,
  { paginate: { page, size: 10_000 } },
  { trustedPageSize: true }, // server-authored size — not from the request
);

Only set this where the size is a literal (or otherwise server-derived) value. Forwarding a request field into a trustedPageSize: true call hands the client the ceiling you configured maxPageSize to enforce.

The same option is available on findPage() (lifting the cap off first/last) and, for callers building the query themselves, as applyDynamic(entity, input, qb, context, { trustedPageSize: true }). It is deliberately not available on apply(): that is the filter-class path @ApplyFilter drives, where the input is the HTTP request by definition. The minimum page size of 1 still applies in every case — that is a correctness floor, not a safety cap.

For keyset/cursor pagination over the same dynamic path, see Cursor pagination (FilterRunner.findPage()).

On this page