@generazioneai/genquery-nestjs

中文文档
0.12.0发布于 2026/10/26BSD-3-ClauseTypeScriptCommonJS零依赖近 30 天下载 2236

NestJS module for @generazioneai/genquery — DI-friendly Prisma engine integration

原始使用文档
文档目录23 节
  1. Limits and secrets (0.11, genquery >= 0.15)
  2. Install
  3. Quick start
  4. Result shape
  5. Configuration
  6. Sync — GenQueryModule.forPrismaRoot(options)
  7. Async — GenQueryModule.forPrismaRootAsync(options)
  8. Policy from resource manifests
  9. Multiple engines
  10. Renaming wire keys / picking which keys to honor
  11. Options
  12. Project-wide defaults
  13. Passing JSON strings in the query
  14. GET vs POST — when to use which
  15. Standalone helper
  16. Swagger helpers — /swagger subpath
  17. Federation (gateways)
  18. Remote failures (0.12)
  19. rpcCall — RPC resilience helper
  20. Error handling
  21. Public API
  22. Documentation
  23. License

@generazioneai/genquery-nestjs

NestJS module for @generazioneai/genquery — exposes the Prisma-backed GenQueryEngine as an injectable provider.

Frontends send a GenQueryInput JSON object. The engine validates it against a schema derived from your Prisma datamodel (DMMF) and translates it into findMany / findFirst argument objects. This package wires that engine into the Nest DI container, plus the HTTP glue around it: a parameter decorator that reads the input off the request, typed Swagger helpers, and a federation transport for gateways.

Limits and secrets (0.11, genquery >= 0.15)

GenQueryModule builds the adapter with the genquery limits: GENQUERY_LIMIT_MODE=log|enforce (default log: measure and log, change nothing), GENQUERY_MAX_ROWS (2000), GENQUERY_MAX_DEPTH (3), or adapter: { limits: {...} }. Events go to the Nest Logger ("GenQuery") unless limits.onEvent is given. In enforce, pagination: "all" is cut to the cap and the result carries truncated: true. Per-model exception: policy: { resources, maxRows: { Model: null } }. policy.extraSecretFields also closes the columns in the schema, so a hand-written schema.policy cannot reopen them. See the genquery README for the full table.

Install

# npm pubblico (registry.npmjs.org), con provenienza
npm install @generazioneai/genquery-nestjs @generazioneai/genquery
# peer deps (most apps already have these)
npm install @nestjs/common @nestjs/core @prisma/client reflect-metadata rxjs

@prisma/client and @nestjs/swagger are optional peers: the former is your own generated client, the latter is only needed when importing the /swagger subpath.

Quick start

// app.module.ts
import { Module } from "@nestjs/common";
import { GenQueryModule } from "@generazioneai/genquery-nestjs";
import { Prisma } from "@prisma/client";
import { PrismaService } from "./prisma.service";

@Module({
  imports: [
    GenQueryModule.forPrismaRoot({
      prisma: PrismaService,                    // DI token of your PrismaClient
      datamodel: Prisma.dmmf.datamodel,
      schema: { models: ["User", "Post"] },     // optional: restrict to specific models
    }),
  ],
})
export class AppModule {}
// users.service.ts
import { Injectable } from "@nestjs/common";
import {
  GenQueryEngine,
  GenQueryInput,
  InjectGenQueryEngine,
} from "@generazioneai/genquery-nestjs";
import { PrismaService } from "./prisma.service";

@Injectable()
export class UsersService {
  constructor(
    private readonly prisma: PrismaService,
    @InjectGenQueryEngine()
    private readonly engine: GenQueryEngine<any, any>,
  ) {}

  // `engine.run` is async and resolves to `{ data, current?, total? }`
  // (see "Result shape" below). The root entity name must be passed
  // explicitly — Prisma delegates don't expose it.
  search(input: GenQueryInput) {
    return this.engine.run(input, "User", this.prisma.user);
  }
}
// users.controller.ts
import { GenQuery, GenQueryInput } from "@generazioneai/genquery-nestjs";

@Controller("users")
export class UsersController {
  constructor(private readonly users: UsersService) {}

  // GET /users?searchBy[firstName]=mario&orderBy=createdAt&pagination[perPage]=20
  @Get()
  list(@GenQuery() input: GenQueryInput) {
    return this.users.search(input);
  }
}

@GenQuery() auto-picks the request surface: request.query for GET/HEAD, request.body otherwise. So the same decorator works for both:

// REST-conventional read
@Get()
list(@GenQuery() input: GenQueryInput) { /* reads query */ }

// POST /search for very complex / deeply nested queries that would be ugly as
// a URL — URL length limits, types stay typed, payload kept out of access logs.
@Post("search")
search(@GenQuery() input: GenQueryInput) { /* reads body */ }

// Force a specific source when needed:
@Get()
list(@GenQuery({ from: "query" }) input: GenQueryInput) { /* ... */ }

Express's default qs parser handles nested query strings out of the box (?searchBy[firstName]=mario&pagination[page]=0 → nested objects). All values arrive as strings — fine for string / enum / date fields, but for number / boolean filters either pass whole-JSON values per key (see JSON strings in the query) or use POST with a JSON body.

For the full query language reference (search modes, date ranges, OR, relations, pagination, etc.) see the upstream docs.

Result shape

engine.run is async and resolves to a PaginatedResult<T> (re-exported from this package):

interface PaginatedResult<T> {
  data: T[];
  current?: number;   // rows in this page (when pagination.showNumber is true)
  total?: number;     // rows matching the query without pagination (when pagination.showTotal is true)
}

Both flags default to true, so a plain engine.run(input, "User", prisma.user) returns { data, current, total }. Opt out via the input:

engine.run(
  { searchBy: { firstName: "mario" }, pagination: { page: 0, perPage: 20, showTotal: false } },
  "User",
  prisma.user,
);
// → { data, current }   ← no parallel `count` query

showTotal: false skips the extra count (faster on large tables); showNumber: false omits data.length from the response (cosmetic). When you need full control over execution — custom chaining, transactions, your own findMany call — use engine.parse + engine.runParsed instead (sync, returns the Prisma args object without executing).

Configuration

Sync — GenQueryModule.forPrismaRoot(options)

GenQueryModule.forPrismaRoot({
  prisma: PrismaService,                          // required: DI token of the Prisma client
  datamodel: Prisma.dmmf.datamodel,               // required: drives schema derivation
  // Optional schema introspection options (forwarded to `schemaFromPrisma`).
  schema: {
    models: ["User", "Post"],                     // restrict to specific models
    overrides: { User: { metadata: "string" } },  // map non-standard columns
  },
  // Optional Prisma adapter options.
  adapter: { parallelCount: false },
});
OptionTypeDefaultPurpose
namestring"default"Register a named engine (see Multiple engines).
prismastring | symbol | Function | Type— (required)DI token resolving to your PrismaClient / PrismaService.
datamodelPrismaDatamodel— (required)Prisma.dmmf.datamodel (or structurally equivalent).
schemaSchemaFromPrismaOptions{}Forwarded to schemaFromPrisma.
adapterPrismaAdapterOptions{}Forwarded to the PrismaAdapter constructor.
policyGenQueryPolicyInput—Auto-build the allowlist policy from resource manifests (see below).
modelstring—Early-fail check that the client has a delegate for this model.
globalbooleanfalseRegister the module as global (mirrors ConfigModule.isGlobal).

Async — GenQueryModule.forPrismaRootAsync(options)

Use this when options depend on injected services (e.g. a config service).

GenQueryModule.forPrismaRootAsync({
  prisma: PrismaService,
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    datamodel: Prisma.dmmf.datamodel,
    schema:  { overrides: config.get("genquery.overrides") },
    adapter: { parallelCount: config.get("genquery.parallelCount") },
  }),
});

Also supports useClass / useExisting with a class that implements GenQueryPrismaOptionsFactory:

@Injectable()
class GenQueryConfig implements GenQueryPrismaOptionsFactory {
  createGenQueryPrismaOptions() {
    return { datamodel: Prisma.dmmf.datamodel };
  }
}

GenQueryModule.forPrismaRootAsync({ prisma: PrismaService, useClass: GenQueryConfig });

name and prisma stay on the top-level call (they determine the DI tokens — the engine token and the client to inject — which must be known synchronously); datamodel / schema / adapter / policy flow through the factory.

Policy from resource manifests

Instead of pre-building an EntityPolicy map by hand, pass your resource manifests through the policy option and the module derives a DENY-based policy (canonical secret fields excluded) over the same datamodel via buildGenQueryPolicy:

GenQueryModule.forPrismaRoot({
  prisma: PrismaService,
  datamodel: Prisma.dmmf.datamodel,
  policy: {
    resources: RESOURCE_MANIFESTS,                  // drives maxPerPage etc.
    deny: { User: { fields: ["internalNotes"] } },  // per-model extra deny
    extraSecretFields: ["legacyHash"],              // beyond DEFAULT_SECRET_FIELDS
  },
});

The result is merged into schema.policy; an explicit schema.policy entry wins over the auto-built one (override hook).

Multiple engines

Register more than one engine by passing distinct name values. Inject each by name:

@Module({
  imports: [
    GenQueryModule.forPrismaRoot({
      prisma: PrismaService,
      datamodel: Prisma.dmmf.datamodel,
    }),                                             // default engine
    GenQueryModule.forPrismaRoot({
      name: "strict",
      prisma: PrismaService,
      datamodel: Prisma.dmmf.datamodel,
      schema: { models: ["User"] },
    }),
  ],
})
export class AppModule {}
constructor(
  @InjectGenQueryEngine()         private readonly defaultEngine: GenQueryEngine<any, any>,
  @InjectGenQueryEngine("strict") private readonly strictEngine:  GenQueryEngine<any, any>,
) {}

Different prisma tokens per engine work the same way — useful when an app talks to more than one database through distinct Prisma clients.

Renaming wire keys / picking which keys to honor

GenQueryInput uses the canonical keys searchBy, orderBy, select, include, pagination. Public APIs often want different names (filter, sort, fields, with, page) and may want to expose only some of them. The @GenQuery() parameter decorator handles the translation.

import { GenQuery, GenQueryInput } from "@generazioneai/genquery-nestjs";

@Controller("users")
export class UsersController {
  // GET /users?filter[firstName]=mario&sort=createdAt&page[perPage]=20
  @Get()
  list(
    @GenQuery({
      keys:   { searchBy: "filter", orderBy: "sort", pagination: "page" },
      allow:  ["searchBy", "orderBy", "pagination"],   // ignore select/include
      strict: true,                                    // throw 400 on unknown keys
    })
    input: GenQueryInput,
  ) {
    return this.users.search(input);    // → { data, current?, total? }
  }
}

The decorator rewrites the parsed query string

{ "filter": { "firstName": "mario" }, "sort": "createdAt", "page": { "perPage": "20" } }

into canonical form before handing it to your handler. Keys not listed in allow are silently dropped (or rejected with BadRequestException when strict: true).

The same decorator works on @Post() endpoints — it reads the body instead. Use POST when query strings get unwieldy (deeply nested OR conditions, mixed-type filters, URL length over a few KB).

Options

OptionTypeDefaultPurpose
keysPartial<Record<CanonicalKey, string>>identityMap canonical → external name. Unmapped keys keep their name.
allowreadonly CanonicalGenQueryKey[]all fiveWhitelist of canonical keys to honor.
strictbooleanfalseThrow on keys that are neither mapped nor in allow.
parseJsonboolean | "auto""auto"auto = parse string values that start with {/[. Lets ?searchBy={...} and ?orderBy=createdAt coexist. true always parses (400 on invalid JSON), false disables.
from"auto" | "query" | "body""auto"auto = query for GET/HEAD, body otherwise. Override to force one.

Project-wide defaults

To avoid repeating the same options on every endpoint, bake them into a custom decorator with createGenQueryDecorator:

// shared/search-input.decorator.ts
import { createGenQueryDecorator } from "@generazioneai/genquery-nestjs";

export const SearchInput = createGenQueryDecorator({
  keys:   { searchBy: "filter", orderBy: "sort", pagination: "page" },
  allow:  ["searchBy", "orderBy", "pagination"],
  strict: true,
});
@Get()
list(@SearchInput() input: GenQueryInput) { ... }

// Per-endpoint override merges over the defaults:
@Get("export")
exportAll(@SearchInput({ allow: ["searchBy"] }) input: GenQueryInput) { ... }

Passing JSON strings in the query

@GenQuery() also accepts whole-JSON values per top-level key, so the wire form

GET /users?searchBy={"firstName":"ada"}&orderBy={"field":"createdAt","order":"desc"}&pagination={"page":0,"perPage":20}

is parsed as

{
  searchBy:   { firstName: "ada" },
  orderBy:    { field: "createdAt", order: "desc" },
  pagination: { page: 0, perPage: 20 },
}

The default parseJson: "auto" only kicks in when the string starts with { or [, so bare-string shorthands keep working on the same endpoint:

GET /users?orderBy=createdAt&pagination=all

…stays a plain string "createdAt" / "all" (which the engine accepts). Invalid JSON in a value that clearly tried to be JSON (?searchBy={broken) yields a BadRequestException. Set parseJson: false to disable the behavior, or parseJson: true to require JSON for every value.

ℹ Remember to URL-encode the JSON value (encodeURIComponent) — most clients do this automatically.

GET vs POST — when to use which

@GenQuery() works on both. Pick by what you're transporting:

  • GET (default for read endpoints) — REST-conventional, idempotent, cacheable, bookmarkable. Good when filters are mostly strings/enums and the query is shallow. Express's qs parser turns ?filter[firstName]=mario&page[page]=0 into nested objects automatically. Caveat: every value arrives as a string — pass whole-JSON values per key to keep native types, or fall back to POST.
  • POST (/resource/search or similar) — when the query is large, deeply nested (OR conditions, multiple relation filters), or contains many typed values you'd rather not stringify. URL length limits and access-log noise also matter for sensitive filters. The decorator reads request.body here without any extra config.

The "auto" default routes correctly for both styles, so the same decorator stays in place when you move an endpoint between methods.

For flat query params (?page=0&perPage=20 instead of ?page[page]=0&page[perPage]=20) preprocess in a Pipe — the mapping decorator only renames top-level keys, it doesn't reshape nested values.

Standalone helper

The translation is a pure function — usable outside controllers (tests, message handlers, custom pipes):

import { mapToGenQueryInput } from "@generazioneai/genquery-nestjs";

const input = mapToGenQueryInput(rawJson, {
  keys: { searchBy: "filter" },
  allow: ["searchBy", "pagination"],
});

Swagger helpers — /swagger subpath

The @generazioneai/genquery-nestjs/swagger subpath ships typed Swagger decorators for gateways exposing genquery endpoints over HTTP. It requires @nestjs/swagger (optional peer) — engine-only backends never load it.

import {
  GenQueryDto,
  ApiOkData,
  ApiCreatedData,
  ApiPaginatedData,
  ApiIdParam,
  ApiFindOneQuery,
  ApiListQueries,
} from "@generazioneai/genquery-nestjs/swagger";

@Controller("users")
export class UsersController {
  @Get()
  @ApiPaginatedData(UserEntity)           // 200 — { success, data: UserEntity[], meta }
  @ApiListQueries("User")                 // documents searchBy/orderBy/pagination/include/select
  list(@GenQuery({ from: "query" }) genquery: GenQueryDto) { /* ... */ }

  @Get(":id")
  @ApiOkData(UserEntity)                  // 200 — { success, data: UserEntity }
  @ApiIdParam()                           // UUID path param
  findOne(@Param("id") id: string) { /* ... */ }

  @Post()
  @ApiCreatedData(UserEntity)             // 201 — { success, data: UserEntity }
  create(@Body() dto: CreateUserDto) { /* ... */ }
}
  • GenQueryDto — permissive DTO for the genquery envelope (searchBy / orderBy / select / include / pagination); validation is delegated to the engine's per-model policy downstream.
  • ApiOkData / ApiCreatedData / ApiPaginatedData — typed success responses inside the standard { success, data, meta? } envelope, with $ref to the real Entity/DTO class (auto-registered via ApiExtraModels).
  • ApiIdParam — standard UUID path param.
  • ApiFindOneQuery / ApiListQueries — document the serialized-JSON genquery query params on findOne / list endpoints.

Federation (gateways)

GenQueryFederationModule / GenQueryFederation give an orchestrator (typically the API gateway) a federated genquery transport over ClientProxy.send: a cmd is dispatched to its owning service and cross-service includes are discovered from the datamodel union and resolved automatically — through the target service's own genquery endpoints, so tenant scoping, authz enforcement and field-level read stripping of the owner service apply to the included rows.

GenQueryFederationModule.forRoot({
  services: [
    { service: "skillID", clientToken: "id", datamodel: idDatamodel },
    { service: "skillHr", clientToken: "hr", datamodel: hrDatamodel },
  ],
  aliasMap: { customer: "Juridical" },     // global semantic aliases (optional)
})
constructor(private readonly federation: GenQueryFederation) {}

list(genquery: GenQueryDto, tenantId: string) {
  return this.federation.send({
    client: "hr",
    cmd: "structure-juridical-individuals.findAll",
    model: "StructureJuridicalIndividual",
    payload: { juridicalId: tenantId, ...genquery },
  });
}

Failed federated includes are best-effort by default (left-join semantics: the key stays null, a WARN is logged); set failFast: true to propagate instead.

Remote failures (0.12)

By default (onRemoteFailure: 'off') a failed federated include resolves to null and logs a structured warning { event: 'federationFailure', key, cmd, kind }. Set onRemoteFailure (or env GENQUERY_FEDERATION_STRICT=off|reject|all; the option wins):

  • reject — validation/authorization errors of the remote service (QueryValidationError, 400, 403, too many nested relations, to-many relation, nested include … not allowed) and truncated: true batch responses throw BadRequestException/ForbiddenException carrying key, cmd, kind; timeouts stay best-effort.
  • all — every remote error is thrown.

root on @GenQuery({ root: 'Order' }) and @ApiPaginatedData(Model, { root: 'Order' }) emits x-genquery-root in the OpenAPI operation.

rpcCall — RPC resilience helper

rpcCall wraps an RPC Observable (e.g. ClientProxy.send()) with timeout + retry. It retries only transport-level "no responders" errors (a service briefly down during a K8s rolling update) with exponential backoff (1s, 2s, 4s, cap 5s) — business errors (validation, not found, …) are never retried.

import { rpcCall } from "@generazioneai/genquery-nestjs";

const result = await rpcCall(this.client.send({ cmd: "users.findAll" }, payload));
// rpcCall(observable, timeoutMs?, maxRetries?) — defaults via env:
//   RPC_TIMEOUT_MS (30000) / RPC_MAX_RETRIES (3)

Error handling

Parse failures throw QueryValidationError (re-exported from this package). The path field points to the offending location in the input:

import { QueryValidationError } from "@generazioneai/genquery-nestjs";

try {
  await this.engine.run(input, "User", this.prisma.user);
} catch (e) {
  if (e instanceof QueryValidationError) {
    throw new BadRequestException({ path: e.path, message: e.message });
  }
  throw e;
}

A reusable exception filter is shown in docs/recipes.md.

Public API

import {
  GenQueryModule,
  InjectGenQueryEngine,
  getGenQueryEngineToken,
  DEFAULT_GENQUERY_ENGINE_NAME,

  // federation (gateways)
  GenQueryFederationModule,
  GenQueryFederation,
  GENQUERY_FEDERATION_OPTIONS,
  FederationServiceConfig,
  GenQueryFederationOptions,
  FederatedSendArgs,
  MessageClientLike,

  // RPC resilience helper
  rpcCall,

  // wire-key remapping
  GenQuery,
  createGenQueryDecorator,
  mapToGenQueryInput,
  mergeGenQueryMappingOptions,
  CANONICAL_GENQUERY_KEYS,
  CanonicalGenQueryKey,
  GenQueryKeyMapping,
  GenQueryMappingOptions,
  GenQueryParamOptions,

  // option types
  GenQueryPrismaModuleOptions,
  GenQueryPrismaModuleAsyncOptions,
  GenQueryPrismaFactoryOptions,
  GenQueryPrismaOptionsFactory,
  GenQueryPolicyInput,
  CreatePrismaEngineOptions,

  // re-exported from @generazioneai/genquery/prisma
  schemaFromPrisma,
  SchemaFromPrismaOptions,
  PrismaAdapterOptions,
  PrismaDatamodel,
  PrismaFindManyArgs,
  PrismaModelDelegate,
  PrismaWhere,

  // re-exported from @generazioneai/genquery
  GenQueryEngine,
  GenQueryInput,
  PaginatedResult,
  ParsedQuery,
  Schema,
  QueryValidationError,
  parseQuery,
  parseDateTime,
  Adapter,
} from "@generazioneai/genquery-nestjs";

import {
  GenQueryDto,
  ApiOkData,
  ApiCreatedData,
  ApiPaginatedData,
  ApiIdParam,
  ApiFindOneQuery,
  ApiListQueries,
} from "@generazioneai/genquery-nestjs/swagger";

Documentation

FileContents
docs/recipes.mdController patterns, exception filter, named engines, testing
Upstream READMEQuery language and adapter internals
Upstream query referenceFull GenQueryInput reference

License

BSD 3-Clause

版本与发布记录

@generazioneai/genquery-nestjs 共发布 17 个版本,首次发布于 2026/05/13;过去 12 个月发布了 17 个版本。

版本发布日期距今
0.12.0latest2026/10/2621 天前
0.11.02026/10/2323 天前
0.10.02026/06/125 个月前
0.9.12026/06/125 个月前
0.9.02026/06/125 个月前
0.8.12026/06/125 个月前

关于 @generazioneai/genquery-nestjs 的常见问题

@generazioneai/genquery-nestjs 是什么?

NestJS module for @generazioneai/genquery — DI-friendly Prisma engine integration

如何安装 @generazioneai/genquery-nestjs?

在项目目录运行 npm install @generazioneai/genquery-nestjs,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(^7.0.0)、@nestjs/core(>=9.0.0)、@nestjs/common(>=9.0.0)、reflect-metadata(^0.1.13 || ^0.2.0)、@generazioneai/genquery(>=0.15.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@generazioneai/genquery-nestjs 支持 TypeScript 吗?

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

@generazioneai/genquery-nestjs 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@generazioneai/genquery-nestjs 可以商用吗?

@generazioneai/genquery-nestjs 使用 BSD-3-Clause 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。另外不得用原作者名义为衍生产品背书。以上为概括,不构成法律意见,请以许可原文为准。

@generazioneai/genquery-nestjs 的下载量有多少?

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

@generazioneai/genquery-nestjs 还在维护吗?

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