@generazioneai/genquery-nestjs (英语)
雀巢JS模块 @generazioneai/genquery - 揭露普里斯玛支持的 GenQueryEngine 作为可注射提供者.
前端发送一个 GenQueryInput JSON对象. 引擎根据从您 Prisma 数据模型( DMMF) 中得出的计划来验证,并将其翻译为 findMany 编号 : findFirst 参数对象。 这个软件包将引擎接入Nest DI容器,加上周围的HTTP胶水:一个从请求中读取输入的参数装饰器,打入了Swagger帮助器,以及用于网关的联邦运输.
限制和秘密 (0.11, 流派 + 0.15)
GenQueryModule 将适配器构建为有流派限制 : GENQUERY_LIMIT_MODE=log|enforce (默认) log:计量
和记录,不改变任何物, GENQUERY_MAX_ROWS (2000), GENQUERY_MAX_DEPTH (3),或 adapter: { limits: {...} }。 。 。 .
活动到巢穴 Logger ("金曲")除非 limits.onEvent 给出。 单位 enforce, (中文(简体) ), pagination: "all" 切为
盖和结果 truncated: true。每个模型例外: policy: { resources, maxRows: { Model: null } }。 。 。 .
policy.extraSecretFields 也关闭了计划中的列,所以手写 schema.policy 不能重新打开它们.
完整的表格请参见基因README.
安装
# 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 财务报告和审定财务报表 @nestjs/swagger 为: 选项 等同端:前者是您自己生成的客户端,后者只有在导入时才需要 /swagger 子路径.
快开始
// 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() 自动选择请求表面 : request.query 页:1 GET编号 :HEAD, (中文(简体) ), request.body 否则。 所以,同样的装饰器为两者工作:
// 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) { /* ... */ }
快递的默认值 qs 解析器把嵌入式查询字符串从框中取出( p)?searchBy[firstName]=mario&pagination[page]=0 □ 被窝的物体)。 所有值都以字符串形式到达 — fine for string 编号 : enum / 日期字段,但用于 number 编号 : boolean 过滤器或者通过每个键的全JSON值(参见 查询中的 JSON 字符串或用有JSON身体的POST.
完整的查询语言参考(搜索模式、日期范围、OR、关系、页码等)见 上游文档。 。 。 .
结果形状
engine.run 将同步并决心 PaginatedResult<T> (从本包中再出):
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)
}
两面旗帜默认为 true,所以一个平地 engine.run(input, "User", prisma.user) 返回时 { data, current, total }。通过输入输出:
engine.run(
{ searchBy: { firstName: "mario" }, pagination: { page: 0, perPage: 20, showTotal: false } },
"User",
prisma.user,
);
// → { data, current } ← no parallel `count` query
showTotal: false 跳过额外 count (放在大桌子上); showNumber: false 省略 data.length 从反应(化妆)中。 当需要完全控制执行时——自定义链路,交易,你自己 findMany 调用 - 使用 engine.parse + 键 engine.runParsed 相反(同步,不执行则返回Prisma args对象).
配置
同步—— 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 },
});
| 选项 | 类型 | 默认 | 目的 |
|---|---|---|---|
name | string | "default" | 注册一个命名的引擎(参见 多个引擎) (中文(简体) ). |
prisma | string | symbol | Function | Type | ——(需要) | 签名解析到您的 PrismaClient 编号 : PrismaService。 。 。 . |
datamodel | PrismaDatamodel | ——(需要) | Prisma.dmmf.datamodel (或结构等同). |
schema | SchemaFromPrismaOptions | {} | 转交 schemaFromPrisma。 。 。 . |
adapter | PrismaAdapterOptions | {} | 转交 PrismaAdapter 建筑师. |
policy | GenQueryPolicyInput | —— 说 | 从资源清单中自动构建许可列表策略(见下文). |
model | string | —— 说 | 提前检查客户端是否有这个模型的代表. |
global | boolean | false | 将模块注册为全局( 镜像) ConfigModule.isGlobal) (中文(简体) ). |
Async - (英语) GenQueryModule.forPrismaRootAsync(options)
当选项依赖于被注入的服务(如配置服务)时使用此功能.
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") },
}),
});
还支持 useClass 编号 : useExisting 带有执行的类 GenQueryPrismaOptionsFactory数字 :
@Injectable()
class GenQueryConfig implements GenQueryPrismaOptionsFactory {
createGenQueryPrismaOptions() {
return { datamodel: Prisma.dmmf.datamodel };
}
}
GenQueryModule.forPrismaRootAsync({ prisma: PrismaService, useClass: GenQueryConfig });
name 财务报告和审定财务报表 prisma 保持顶级呼叫(它们确定必须同步已知的DI令牌——引擎令牌和要注入的客户端); datamodel 编号 : schema 编号 : adapter 编号 : policy 流经工厂.
来自资源清单的政策
而不是预建 EntityPolicy 将您的资源清单通过 policy 选项,该模块得出基于DENY的政策(排除分类秘密字段) datamodel 通过 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
},
});
结果合并为 schema.policy; 明示 schema.policy 条目胜过自动所建的(覆盖钩) .
多个引擎
通过不同方式注册多个引擎 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>,
) {}
不同 prisma 每个引擎的符号作用相同——当一个应用程序通过独特的Prisma客户端与一个以上的数据库交谈时有用.
重新命名有线密钥 / 选择要尊重的密钥
GenQueryInput 使用条形键 searchBy, (中文(简体) ), orderBy, (中文(简体) ), select, (中文(简体) ), include, (中文(简体) ), pagination. 公共APIs经常想要不同的名称( :filter, (中文(简体) ), sort, (中文(简体) ), fields, (中文(简体) ), with, (中文(简体) ), page),可能只想要揭露其中的一些. 这个 @GenQuery() 参数装饰器处理翻译.
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? }
}
}
装饰器重写已解析的查询字符串
{ "filter": { "firstName": "mario" }, "sort": "createdAt", "page": { "perPage": "20" } }
在交给你的处理者之前 以警犬的形式 未列出的密钥 allow 静默地放弃(或以 BadRequestException 何时 strict: true) (中文(简体) ).
同一个装饰器在工作 @Post() 结尾——它读取了身体。 当查询字符串变得不通通时使用 POST(深度嵌入 OR 条件,混合类型过滤器, URL 长度超过几个 KB).
选项
| 选项 | 类型 | 默认 | 目的 |
|---|---|---|---|
keys | Partial<Record<CanonicalKey, string>> | 身份 | (原始内容存档于2017-10-26). Map Canonical ~ 外部名. 未放大的密钥保留其名. |
allow | readonly CanonicalGenQueryKey[] | 全部五个 | 白名单 Canical keys to honor. 白名单 白名单 白名单 白名单. |
strict | boolean | false | 扔出既不映射也不包含的密钥 allow。 。 。 . |
parseJson | boolean | "auto" | "auto" | auto = 解析开始的字符串值 {编号 :[让我们 ?searchBy={...} 财务报告和审定财务报表 ?orderBy=createdAt 并肩作战. true 总是剖析( 无效的 JSON 有400个), false 禁用 . |
from | "auto" | "query" | "body" | "auto" | auto =: query 为获得/获得, body 否则。 推翻强制一. |
全项目默认
为了避免在每个端点重复相同的选项,将其烤入自定义的装饰器中 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) { ... }
在查询中传递 JSON 字符串
@GenQuery() 还接受每个顶级密钥的全- JSON 值, 所以线形
GET /users?searchBy={"firstName":"ada"}&orderBy={"field":"createdAt","order":"desc"}&pagination={"page":0,"perPage":20}
解析为
{
searchBy: { firstName: "ada" },
orderBy: { field: "createdAt", order: "desc" },
pagination: { page: 0, perPage: 20 },
}
默认 parseJson: "auto" 只在字符串开始时踢入 { 或者说 [,所以光弦的快手 继续工作在同一端点:
GET /users?orderBy=createdAt&pagination=all
...保持简单的字符串 "createdAt" 编号 : "all" (发动机接受). 无效的 JSON , 其数值显然尝试为 JSON ()?searchBy={broken产生a BadRequestException设置 parseJson: false 以禁用行为,或 parseJson: true 要求JSON为每个值.
记住 URL 编码 JSON 值 (
encodeURIComponent) ——大多数客户自动这样做.
使用时间
@GenQuery() 两者都有用 从你运送的东西中选择:
- 获取( 默认读取终点) ——REST-常规,一能,可缓存,可书签. 当过滤器多为字符串/enum,且查询很浅时,效果良好. 快递
qs剖析器旋转?filter[firstName]=mario&page[page]=0自动输入嵌入对象。 Caveat:每个值作为字符串到达——每个按键通过整个-JSON值来保持本地类型,或者倒回POST. - 邮政 (单位:千美元)
/resource/search或相类似) ——当查询是大而深的嵌入(OR条件,多关系过滤器),或者包含许多被键入的数值时,你宁愿不弦入. URL长度限制和访问日志噪声对于敏感的过滤器也很重要. 装潢师说request.body这里没有任何额外的配置.
这个 "auto" 两种样式的默认路径正确,所以当您在方法间移动一个端点时,相同的装饰器会留在原地.
用于平面查询参数(?page=0&perPage=20 改为 ?page[page]=0&page[perPage]=20) 管道中的预处理——绘图装饰器只重命名顶级密钥,不重塑巢值.
独立助手
翻译是一个纯函数——可用外部控制器(测试,消息处理器,自定义管道):
import { mapToGenQueryInput } from "@generazioneai/genquery-nestjs";
const input = mapToGenQueryInput(rawJson, {
keys: { searchBy: "filter" },
allow: ["searchBy", "pagination"],
});
斯瓦格帮手—— /swagger 子路径
这个 @generazioneai/genquery-nestjs/swagger 亚路径船打出 Swagger 装饰器 用于在HTTP上暴露出基因端点的网关。 这需要 @nestjs/swagger (可选的对等点)——只有引擎的后端从不加载.
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用于基因封套的可允许的DTO(searchBy编号 :orderBy编号 :select编号 :include编号 :pagination);验证权下放给下游的发动机按型号政策.ApiOkData编号 :ApiCreatedData编号 :ApiPaginatedData- 在标准内输入成功答复{ success, data, meta? }信封,与$ref自动注册ApiExtraModels) (中文(简体) ).ApiIdParam——标准UUID路径参数.ApiFindOneQuery编号 :ApiListQueries——在 find One / List end points上记录已序列化的-JSON genquery查询参数.
联合会(大门)
GenQueryFederationModule 编号 : GenQueryFederation 给一个管弦乐手(典型的API网关)一个联合的分流器 ClientProxy.send: 发送到自己的服务和交叉服务 includes是从数据模型联盟中发现并自动解决的——通过目标服务本身的流派端点,因此租户范围界定、授权执行和实地一级读取 拥有者 服务适用于包含的行.
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 },
});
}
失败的联邦语义包括默认的最好方法( 左- join semtics: key stays) null; 设置 failFast: true 转而传播.
远程故障( 0. 12)
默认( E)onRemoteFailure: 'off')失败的联邦包括决心 null 并记录结构化的警告 { event: 'federationFailure', key, cmd, kind }设置 onRemoteFailure (或潜入) GENQUERY_FEDERATION_STRICT=off|reject|all; 选项获胜 :
reject远程服务的验证/授权错误(QueryValidationError, 400, 403, (英语),too many nested relations, (中文(简体) ),to-many relation, (中文(简体) ),nested include … not allowed和truncated: true批量响应投出BadRequestException编号 :ForbiddenException携带key, (中文(简体) ),cmd, (中文(简体) ),kind暂停是最佳的.all——每个远程错误被抛出.
root 打开 @GenQuery({ root: 'Order' }) 财务报告和审定财务报表 @ApiPaginatedData(Model, { root: 'Order' }) 发射 x-genquery-root openAPI 操作中.
rpcCall ——RPC复原力帮助者
rpcCall 包裹 RPC Observable (例如:. ClientProxy.send())有超时+重试. 复试 仅限 运输级"无应答器"出错(在K8s滚动更新中短暂下调的服务) 有指数回放(1s,2s,4s,5s)——商业出错(验证,没有找到,.)从未被再试.
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)
处理错误
分析失败 QueryValidationError (从本包中再出). 这个 path 字段指出输入中的违法地点:
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;
}
可重用例外过滤器显示于 文档/目录。 。 。 .
公共 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";
文档
| 文件 | 目录 |
|---|---|
| 文档/目录 | 控制器模式,例外过滤器,命名引擎,测试 |
| 上游读取 | 查询语言和适配器内部 |
| 上游查询参考 | 满 GenQueryInput 参考文献 |