npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nestjs-rest-query

v2.1.0

Published

Declarative, whitelist-first REST query params for NestJS and TypeORM.

Readme

nestjs-rest-query

Declarative, whitelist-first REST query params for NestJS.

Turn ?filter[email][like]=acme&sorts=-createdAt&page=2 into safe, typed database queries — without writing a single WHERE clause.

npm version npm downloads CI OSSF Scorecard Provenance License


Why?

NestJS has controllers. TypeORM has a query builder. The boilerplate between them — parsing query strings, validating fields, building filters, paginating, joining relations — is the same in every project.

nestjs-rest-query removes it. You declare a whitelist of what each endpoint accepts; the library handles the rest.

Features

  • 🎯 Whitelist-first — unknown query params are silently ignored. Defense by default.
  • 🔍 14 comparison operatorseq, ne, like, ilike, notLike, notIlike, gt, gte, lt, lte, in, notIn, between, isNull.
  • 📑 Pagination with { data, page, perPage, total, lastPage }.
  • ↕️ Multi-field sorting with +/- prefix.
  • 🔗 Relations on demand via ?includes=.
  • ✂️ Sparse fieldsets via ?fields=.
  • 🔎 Full-text search across whitelisted columns.
  • 📚 Swagger/OpenAPI integration — query params documented automatically.
  • 🛡️ Type-safe end-to-end.
  • 🪶 Zero runtime dependencies beyond your peers.

Compatibility

| nestjs-rest-query | NestJS | TypeORM | Drizzle | Node | | ----------------- | ------ | ------- | -------- | ------ | | 2.x | 11.x | 0.3.x | 0.45.x | >=20 | | 1.x | 11.x | 0.3.x | — | >=20 |

Adapters

| ORM | Status | Import path | | ------- | --------- | --------------------------- | | TypeORM | ✅ Stable | nestjs-rest-query | | Drizzle | ✅ Stable | nestjs-rest-query/drizzle | | Prisma | ✅ Stable | nestjs-rest-query/prisma |

Want a different ORM? Open a discussion.

Install

pnpm add nestjs-rest-query
# or
npm install nestjs-rest-query

Peer dependencies: @nestjs/common, @nestjs/core, reflect-metadata. Optionally typeorm (for TypeORM) or drizzle-orm (for Drizzle). Add @nestjs/swagger for OpenAPI integration (optional).

Choose your ORM

// TypeORM (default)
import { DynamicQueryBuilderModule } from 'nestjs-rest-query';

DynamicQueryBuilderModule.forRoot({});

// Drizzle
import { DynamicQueryBuilderModule } from 'nestjs-rest-query';
import { DrizzleAdapter } from 'nestjs-rest-query/drizzle';

DynamicQueryBuilderModule.forRoot({
  adapter: new DrizzleAdapter(),
});

See Adapters for more.

Quick start

1. Register the module

// app.module.ts
import { Module } from '@nestjs/common';
import { DynamicQueryBuilderModule } from 'nestjs-rest-query';

@Module({
  imports: [
    DynamicQueryBuilderModule.forRoot({
      pagination: { defaultPerPage: 20, maxPerPage: 100 },
    }),
  ],
})
export class AppModule {}

2. Declare rules and use the decorator

// users.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
  ApiDynamicQuery,
  QueryRules,
  QueryBuilderService,
  RulesConfig,
  QueryInput,
} from 'nestjs-rest-query';
import { User } from './user.entity';

const rules: RulesConfig = {
  alias: 'user',
  filters: ['email', 'name', 'createdAt', 'status'],
  sorts: ['name', 'createdAt'],
  fields: ['id', 'name', 'email'],
  includes: ['company'],
  search: ['name', 'email'],
};

@Controller('users')
export class UsersController {
  constructor(
    @InjectRepository(User) private readonly users: Repository<User>,
    private readonly qb: QueryBuilderService
  ) {}

  @Get()
  @ApiDynamicQuery(rules)
  list(@Query() query: QueryInput, @QueryRules() endpointRules = rules) {
    return this.qb.execute(this.users, query, endpointRules);
  }
}

3. Send a request

GET /users
  ?filter[email][ilike]=%@acme.com
  &filter[createdAt][gte]=2025-01-01
  &sorts=-createdAt,name
  &includes=company
  &fields=id,name,email
  &search=ana
  &page=1
  &perPage=20

4. Get a typed response

{
  "data": [
    {
      "id": "u_1",
      "name": "Ana Souza",
      "email": "[email protected]",
      "company": { "id": "c_1", "name": "Acme" }
    }
  ],
  "page": 1,
  "perPage": 20,
  "total": 137,
  "lastPage": 7
}

That's the whole loop.

Operators

All operators target a whitelisted column and use the filter[<column>][<operator>]=<value> syntax.

| Operator | Example | SQL equivalent | | ------------ | -------------------------------------------------- | ------------------------------- | | eq | filter[status][eq]=active | status = 'active' | | ne | filter[status][ne]=archived | status <> 'archived' | | gt / gte | filter[age][gte]=18 | age >= 18 | | lt / lte | filter[price][lt]=100 | price < 100 | | like | filter[name][like]=%souza% | name LIKE '%souza%' | | ilike | filter[email][ilike]=%@acme.com | email ILIKE '%@acme.com' | | notLike | filter[name][notLike]=%spam% | name NOT LIKE '%spam%' | | notIlike | filter[email][notIlike]=%@spam.io | email NOT ILIKE '%@spam.io' | | in | filter[role][in]=admin,editor | role IN ('admin','editor') | | notIn | filter[role][notIn]=guest | role NOT IN ('guest') | | between | filter[createdAt][between]=2025-01-01,2025-12-31 | createdAt BETWEEN ... AND ... | | isNull | filter[deletedAt][isNull]=true | deletedAt IS NULL |

Restrict the available operators globally via forRoot({ operators: { allowed: ['eq', 'in', 'gte'] } }).

Sorting, fields, includes, search, pagination

?sorts=name,-createdAt          # name ASC, createdAt DESC
?fields=id,name,email           # SELECT id, name, email
?includes=company,company.owner # LEFT JOIN company; LEFT JOIN owner
?search=keyword                 # against rules.search columns
?page=2&perPage=50              # offset/limit

Anything not declared in RulesConfig is ignored — clients can't sort by password_hash even if they try.

Swagger / OpenAPI

Use @ApiDynamicQuery(rules) instead of @DynamicQuery(rules) and every query param shows up in your Swagger UI with the right type and description.

import { dqbSwaggerRequestInterceptor } from 'nestjs-rest-query';

SwaggerModule.setup('docs', app, document, {
  swaggerOptions: {
    requestInterceptor: dqbSwaggerRequestInterceptor(document),
  },
});

The interceptor lets users type filters in the Swagger UI form and forwards them in the wire format the parser expects.

Configuration

DynamicQueryBuilderModule.forRoot({
  pagination: {
    defaultPerPage: 20,
    maxPerPage: 100,
  },
  operators: {
    allowed: ['eq', 'ne', 'in', 'notIn', 'gte', 'lte', 'ilike'],
  },
  logging: {
    enabled: true,
    level: 'info',
    format: 'json', // or 'console'
  },
});

All fields are optional. Sane defaults apply.

Security model

Whitelist-first is the primary defense. Consumers should still:

  • Keep RulesConfig minimal — least privilege.
  • Never expose internal columns (password_hash, internal flags) in fields or sorts.
  • Layer auth/authz (NestJS guards) above the query.
  • Enforce tenant scoping in the controller before calling execute().

See SECURITY.md for vulnerability reporting.

API surface

| Export | Purpose | | --------------------------------------------- | ---------------------------------------------------- | | DynamicQueryBuilderModule | The dynamic module — call .forRoot(config). | | QueryBuilderService | buildQuery(repo, query, rules) and execute(...). | | @DynamicQuery(rules) | Stores rules in metadata. | | @ApiDynamicQuery(rules) | Same + Swagger decorators. | | @QueryRules() | Parameter decorator — injects rules at runtime. | | RulesConfig, QueryInput, QueryResult<T> | Public types. |

Try a PR before it ships

Every pull request publishes a one-off preview release via pkg.pr.new. Install it with:

pnpm add https://pkg.pr.new/naldomadeira/nestjs-rest-query@<commit-or-pr>

Supply chain

Releases are published with npm provenance via GitHub Actions Trusted Publishing — no long-lived NPM_TOKEN. Each release tarball can be cryptographically traced to the exact commit and workflow run that built it.

Contributing

PRs welcome. See CONTRIBUTING.md for setup, branching, and the changeset workflow. By participating you agree to the Code of Conduct.

License

MIT © Naldo Madeira