后端GraphQLAPI设计【免费下载链接】type-graphqlCreate GraphQL schema and resolvers with TypeScript, using classes and decorators!项目地址https://gitcode.com/gh_mirrors/ty/type-graphql点击查看免费下载本指南以 TypeGraphQL 官方文档的 Examples 页面为脉络系统梳理当前仓库examples/目录下 24 个示例工程的组织方式、运行方法与技术要点。读完本文你将掌握如何一键启动任意示例npx ts-node ./index.ts、如何借助每个示例自带的examples.graphql在 Apollo Studio 中快速调试查询以及 TypeGraphQL 的枚举/联合、订阅、鉴权、校验、IoC 容器、Query Complexity 等核心特性在真实工程中的落地方案。示例仓库的整体布局与快速启动TypeGraphQL 官方文档website/versioned_docs/version-2.0.0-rc.4/examples.md明确说明仓库中存放了一批用于演示不同 TypeGraphQL 特性、以及 TypeGraphQL 与第三方库集成方式的示例工程。这些示例全部位于仓库根目录的 examples 下仓库根目录的 examples/README.md 与文档内容保持一致。运行任意一个示例只需两步cd ./examples/simple-usage # 进入某个示例的子目录 npx ts-node ./index.ts # 启动 GraphQL 服务器服务默认监听http://localhost:4000。每个示例子目录中都包含一个examples.graphql文件里面预置了可直接使用的 GraphQL 查询query、变更mutation与订阅subscription操作你可以把这些操作原样粘贴到Apollo Studio中执行并通过修改请求的 shape字段选取形状与 data入参数据来观察 schema 行为。以最简单的 examples/simple-usage/examples.graphql 为例文件里预置了三个操作query GetRecipe1 { recipe(title: Recipe 1) { title description ratings creationDate ratingsCount(minRate: 2) averageRating } } query GetRecipes { recipes { title description creationDate averageRating } } mutation AddRecipe { addRecipe(recipe: { title: New recipe, description: Simple description }) { creationDate } }这种「每个示例自带一份可交互的 GraphQL 操作样本」的设计是官方示例体系最重要的实践约定你不需要猜测 schema 里有什么字段直接打开examples.graphql即可开始调试。示例的统一启动骨架所有示例都遵循同一套 bootstrap 模式其骨架可见于 examples/simple-usage/index.tsimport reflect-metadata; import path from node:path; import { ApolloServer } from apollo/server; import { startStandaloneServer } from apollo/server/standalone; import { buildSchema } from type-graphql; import { RecipeResolver } from ./recipe.resolver; async function bootstrap() { // Build TypeGraphQL executable schema const schema await buildSchema({ // Array of resolvers resolvers: [RecipeResolver], // Create schema.graphql file with schema definition in current directory emitSchemaFile: path.resolve(__dirname, schema.graphql), }); // Create GraphQL server const server new ApolloServer({ schema }); // Start server const { url } await startStandaloneServer(server, { listen: { port: 4000 } }); console.log(GraphQL server ready at ${url}); } bootstrap().catch(console.error);这一段代码浓缩了 TypeGraphQL 应用的标准三步流程导入reflect-metadataTypeScript 装饰器依赖反射元数据所有 TypeGraphQL 程序的第一步都是导入它buildSchema构建可执行 schema传入 resolver 数组如resolvers: [RecipeResolver]emitSchemaFile会把生成的 SDLSchema Definition Language写入当前目录的schema.graphql方便你直接查看最终 schema 定义接入 Apollo Server把 schema 交给new ApolloServer({ schema })再通过startStandaloneServer以4000端口启动。后续所有进阶示例只是在这套骨架上追加特性参数如authChecker、container、globalMiddlewares或替换数据层如 TypeORM、MikroORM。基础示例字段、基础类型与 ResolverSimple usageexamples/simple-usage是文档 Basics 分类下唯一的示例也是理解 TypeGraphQL「用类与装饰器定义 GraphQL schema」的最小完整范例。对象类型定义见 examples/simple-usage/recipe.type.tsimport { Field, Float, Int, ObjectType } from type-graphql; ObjectType({ description: Object representing cooking recipe }) export class Recipe { Field() title!: string; Field(_type String, { nullable: true, deprecationReason: Use description field instead }) get specification(): string | undefined { return this.description; } Field({ nullable: true, description: The recipe description with preparation info }) description?: string; Field(_type [Int]) ratings!: number[]; Field() creationDate!: Date; Field(_type Int) ratingsCount!: number; Field(_type Float, { nullable: true }) get averageRating(): number | null { const ratingsCount this.ratings.length; if (ratingsCount 0) { return null; } const ratingsSum this.ratings.reduce((a, b) a b, 0); return ratingsSum / ratingsCount; } }该类型示例展示了Field的多个核心用法基础标量类型string、Int、Float、Date、列表类型[Int]、可空性nullable: true、字段描述description、弃用标记deprecationReason以及基于 getter 的计算字段averageRating、specification均由 getter 计算得出TypeGraphQL 会将其编译为 GraphQL 字段。对应的 Resolver 定义见 examples/simple-usage/recipe.resolver.ts它同时演示了 Query、Mutation、FieldResolver 三类装饰器Resolver(_of Recipe) export class RecipeResolver implements ResolverInterfaceRecipe { private readonly items: Recipe[] createRecipeSamples(); Query(_returns Recipe, { nullable: true }) async recipe(Arg(title) title: string): PromiseRecipe | undefined { return this.items.find(recipe recipe.title title); } Query(_returns [Recipe], { description: Get all the recipes from around the world }) async recipes(): PromiseRecipe[] { return this.items; } Mutation(_returns Recipe) async addRecipe(Arg(recipe) recipeInput: RecipeInput): PromiseRecipe { // ... } FieldResolver() ratingsCount( Root() recipe: Recipe, Arg(minRate, _type Int, { defaultValue: 0 }) minRate: number, ): number { return recipe.ratings.filter(rating rating minRate).length; } }这里值得注意的细节Arg(title)直接把方法参数映射为 GraphQL 参数Arg(minRate, _type Int, { defaultValue: 0 })演示了参数的类型显式声明与默认值FieldResolver配合Root()为既有对象类型补充派生字段ratingsCount。输入对象类型RecipeInput定义于 examples/simple-usage/recipe.input.ts由InputType装饰用于 mutation 的复合入参。进阶示例枚举、联合、订阅与元数据扩展文档 Advanced 分类收录了五个示例覆盖 TypeGraphQL 的进阶类型系统与实时能力。Enums and unions枚举与联合类型examples/enums-and-unions 演示两类组合类型枚举类型difficulty.enum.ts 用registerEnumType把 TypeScript 枚举注册为 GraphQL 枚举联合类型search-result.union.ts 用createUnionType把Recipe与Cook组合为SearchResult。resolver.ts 中的searchQuery 返回Arraytypeof SearchResult即一次搜索同时命中菜谱与厨师两类实体recipesQuery 则把Difficulty枚举作为可选过滤参数Arg(difficulty, _type Difficulty, { nullable: true })。Subscriptionssimple实时订阅examples/simple-subscriptions 是订阅Subscription的最简实现pubsub.ts 基于graphql-subscriptions的PubSub实例notification.resolver.ts 用Subscription装饰器暴露notifications订阅主题配合Root()取回发布时携带的载荷。该示例适合先理解订阅模型再迁移到更复杂的 Redis 版本。Subscriptionsusing Redis**examples/redis-subscriptions 把 PubSub 后端替换为 Redis对应 pubsub.ts实现多实例间共享的订阅通道。文档脚注特别说明该示例需要提供环境变量REDIS_URL指向你本地的 Redis 实例连接参数例如REDIS_URLredis://localhost:6379。运行前务必先启动 Redis 并正确配置该变量。Interfaces接口与继承examples/interfaces-inheritance 演示 GraphQL 接口Interface与类型继承。person/目录中的 person.interface.ts 定义InterfaceType而employee/、student/目录中的具体类型分别用ObjectType({ implements: Person })继承接口字段Field通过_type Person声明接口返回类型。resolver.ts 中返回接口类型的 Query 需要配合Resolver的类型解析逻辑详见仓库 helpers.ts。该示例同时被文档 Features usage 分类引用为Types inheritance的示例。Extensionsmetadata字段级元数据扩展examples/extensions 演示 TypeGraphQL 的Extensions特性通过 log-message.decorator.ts 自定义装饰器把附加元数据挂到字段上再由 helpers/config.extractors.ts 提取这些扩展信息典型场景是供 Apollo 生态或自研工具消费logger.service.ts 与 logger.middleware.ts 则展示如何把扩展元数据接入运行时日志。特性使用示例容器、鉴权、校验与复杂度控制文档 Features usage 分类集中展示了 TypeGraphQL 在工程实践中高频使用的框架级能力。Dependency injectionIoC container与 Scoped containersexamples/using-container 演示 TypeGraphQL 与第三方 IoC 容器的集成在buildSchema中传入container选项将 resolver 实例的创建权交给容器默认方案Container来自typedi// examples/using-container/index.ts 节选 import { Container } from typedi; Container.set({ id: SAMPLE_RECIPES, factory: () sampleRecipes.slice() }); const schema await buildSchema({ resolvers: [RecipeResolver], container: Container, emitSchemaFile: path.resolve(__dirname, schema.graphql), });容器注册的服务经由 recipe.service.ts 注入到 resolver 中。而 examples/using-scoped-container 进一步演示作用域容器scoped container每次请求创建独立的容器实例见其 index.ts 与 recipe 目录适用于每次请求独立上下文的场景如请求级日志、租户隔离。Authorization鉴权examples/authorization 是Authorized装饰器 authChecker的完整范例buildSchema传入自定义的authChecker见 auth-checker.ts服务器端通过context注入用户信息见 index.ts 中 mock 的user: { id: 1, name: Sample user, roles: [REGULAR] }resolver 方法上用Authorized()或Authorized(ADMIN)声明访问门槛未通过authChecker校验的请求会抛出鉴权错误。相关错误类型AuthenticationError、AuthorizationError定义于 src/errors/graphql/。Validation自动校验与自定义校验examples/automatic-validation 演示automatic validation结合class-validator在 recipe.input.ts 与 recipes.arguments.ts 的类属性上声明校验装饰器如Length、IsIntTypeGraphQL 会在参数转换后自动执行校验helpers.ts 中可配置校验行为。其姊妹示例 examples/custom-validation 则演示绕过内置校验、自定义参数校验逻辑的方式。核心实现可对照 src/resolvers/validate-arg.ts 与 src/resolvers/convert-args.ts。Resolvers inheritanceResolver 继承examples/resolvers-inheritance 演示 Resolver 类的继承复用person/目录定义基类 Resolverperson.resolver.tsrecipe/目录的 Resolverrecipe.resolver.ts通过继承获得通用查询/变更能力同时可覆写或扩展有效消除重复样板代码。Generic types泛型类型examples/generic-types 演示泛型Generic类型的处理 paginated-response.type.ts 用泛型定义分页响应包装类再通过createUnionType或类型工厂在运行时为不同实体实例化具体类型。此类模式与文档 generic-types.md 中的讲解相互印证。Mixin classes混入类examples/mixin-classes 演示mixin classesmixins/目录with.id.ts、with.password.ts定义可复用的字段片段types/目录把多个 mixin 组合成完整对象类型inputs/目录则组合出不同的输入类型实现按需拼装的类型工程化。Middlewares and custom decorators中间件与自定义装饰器examples/middlewares-custom-decorators 是高级特性集中演示包含三层内容全局中间件buildSchema传入globalMiddlewares: [ErrorLoggerMiddleware]见 index.tsmiddlewares/ 目录还提供log-access、resolve-time、number-interceptor等示例自定义方法装饰器decorators/目录利用createMethodMiddlewareDecorator、createParameterDecorator实现见 src/decorators/封装current-user、random-id-arg、validate-args等可复用装饰器请求上下文通过context注入currentUser见 context.type.ts。Query complexity查询复杂度防护examples/query-complexity 演示如何保护服务器免受复杂查询与 DoS 攻击借助graphql-query-complexity库在 Apollo Server 的插件生命周期didResolveOperation中调用getComplexity计算复杂度index.tsconst MAX_COMPLEXITY 20; // 计算复杂度schema operationName document variables estimators const complexity getComplexity({ schema, operationName: request.operationName, query: document, variables: request.variables, estimators: [ fieldExtensionsEstimator(), // 使用 fieldExtensionsEstimator 是配合 type-graphql 的前提 simpleEstimator({ defaultComplexity: 1 }), // 兜底每个字段默认复杂度 1 ], }); if (complexity MAX_COMPLEXITY) { throw new Error( Sorry, too complicated query! ${complexity} exceeded the maximum allowed complexity of ${MAX_COMPLEXITY}, ); }注意代码中的关键注释fieldExtensionsEstimator是让查询复杂度与 TypeGraphQL 协同工作所必需的估计器字段级复杂度可通过Extensions元数据驱动。第三方库集成示例文档 3rd party libs integration 分类的示例展示 TypeGraphQL 与主流数据层、联邦网关及标量库的集成方式。ORM 集成TypeORM、MikroORM、TypegooseTypeORM手动、同步*examples/typeorm-basic-usage 先通过 datasource.ts 初始化数据源dataSource.initialize()用 helpers.ts 中的seedDatabase()填充种子数据再把实体entities/包装为 GraphQL 类型resolver 通过仓库模式手动同步查询。该示例需要环境变量DATABASE_URL指向本地数据库TypeORM自动、懒加载关系*examples/typeorm-lazy-relations 演示 TypeORM 懒加载关系Promise包装的属性如何自动映射为 GraphQL 字段解析同样需要DATABASE_URLMikroORM *examples/mikro-orm 是 MikroORM 的集成范例结构entities/、resolvers/、helpers.ts与 TypeORM 版本对称同样依赖DATABASE_URLTypegoose *examples/typegoose 面向 MongoDB实体定义在 entities/并通过 typegoose.middleware.ts 把 mongoose 文档转换为可返回的普通对象object-id.scalar.ts 注册了ObjectId的自定义标量同样依赖DATABASE_URL。以上四个示例中*号对应文档脚注需要设置DATABASE_URL环境变量例如DATABASE_URLpostgres://user:passlocalhost:5432/db。Apollo Federation 1 与 2联邦子图examples/apollo-federation 与 examples/apollo-federation-2 分别演示基于 Federation 1 与 Federation 2 的子图subgraph拆分每个子图accounts/、inventory/、products/、reviews/各自是一个 TypeGraphQL 应用通过 helpers/buildFederatedSchema.tsFederation 2 版本见 examples/apollo-federation-2/helpers/buildFederatedSchema.ts构建联邦 schema并用ReferenceResolver风格的引用解析如user.reference.ts、product.reference.ts支持跨子图的实体引用。两个示例目录下均提供examples.graphql与schema.graphql供对照。Apollo Cache Control缓存指令examples/apollo-cache 演示结合apollo-cache-control的缓存控制通过 cache-control.ts 与 helpers/如 getTime.ts、RequireAtLeastOne.d.ts为字段声明缓存 TTL 等元数据recipe.resolver.ts 中配合使用。GraphQL Scalars扩展标量examples/graphql-scalars 演示graphql-scalars库提供的扩展标量如日期时间、非空字符串等recipe.type.ts 与 recipe.input.ts 中把自定义标量类直接用作字段类型无需手写标量解析器。TSyringe另一个 IoC 容器examples/tsyringe 与using-container思路相同但容器换成微软的tsyringeindex.ts 中注册容器并传给buildSchemarecipe.service.ts 作为依赖注入的服务类被 resolver 消费展示容器方案的可替换性。运行与调试的实用提示环境变量。涉及数据库的示例TypeORM、MikroORM、Typegoose必须提供DATABASE_URLRedis 订阅示例必须提供REDIS_URLTypeORM 示例通过import dotenv/config自动加载本地.env见 examples/typeorm-basic-usage/index.ts。版本对齐。仓库根目录 examples/README.md 特别提醒master 分支上的示例是为尚未发布的最新代码编写的若你使用的是已发布版本应通过对应 git tag如v0.16.0浏览该版本的 examples 目录以保证示例与所用 TypeGraphQL 版本兼容。调试入口。所有示例都在4000端口启动 Apollo Server可直接用 Apollo Studiohttp://localhost:4000连接每个子目录的schema.graphql是构建时由emitSchemaFile自动生成的 SDL 产物可作为期望 schema的速查清单而examples.graphql则是如何调用的操作手册二者配合即可快速上手任意示例。公共配置。各示例共享 examples/tsconfig.json 编译配置所有示例源码都依赖reflect-metadata在各自index.ts首行导入与装饰器语法这是运行 TypeGraphQL 工程的硬性前提。小结从文档 Examples 页面出发可以看到TypeGraphQL 的示例体系是一条完整的学习路径先以simple-usage掌握类 装饰器定义 schema、resolver 处理业务的基本范式再通过 enums/unions、subscriptions、interfaces、extensions 理解类型系统与实时能力的进阶用法随后用容器、鉴权、校验、继承、泛型、混入、中间件、查询复杂度等示例打通工程化能力最后通过 ORM、Federation、Scalars、TSyringe 等第三方集成示例把 TypeGraphQL 放进真实技术栈。每个示例都是可直接npx ts-node ./index.ts运行的完整工程配合examples.graphql即可在本地快速验证——这既是学习资源也是搭建新项目时最直接的脚手架参考。赞分享后端GraphQLAPI设计【免费下载链接】type-graphqlCreate GraphQL schema and resolvers with TypeScript, using classes and decorators!项目地址https://gitcode.com/gh_mirrors/ty/type-graphql点击查看免费下载相关推荐TypeGraphQL 0.17.2 官方示例全览从基础类型到第三方库集成TypeGraphQL 0.17.2 官方示例全览从基础类型到第三方库集成 本篇文章基于 TypeGraphQL 仓库 v0.17.2 版本官方文档中的 Ex后端GraphQLAPI设计Haystack 集成 Oracle AI Vector Search 实战OracleDocumentStore 与 OracleEmbeddingRetriever 完整指南Haystack 集成 Oracle AI Vector Search 实战OracleDocumentStore 与 OracleEmbeddingRetr后端GraphQLAPI设计TypeGraphQL 官方示例实战指南从基础用法到第三方库集成全解析TypeGraphQL 官方示例实战指南从基础用法到第三方库集成全解析 导读 TypeGraphQL 是一个基于 TypeScript 装饰器语法创建 Gra后端GraphQLAPI设计上一篇终极Audiobookshelf播放队列管理指南自定义排序与循环模式完全掌握下一篇asc-devkit PyTorch算子注册示例创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考