如何在NestJS中集成GraphQL?

在NestJS中集成GraphQL时遇到了一些问题,想请教大家:

  1. 按照官方文档配置GraphQL模块后,Resolver总是无法正常注入服务,报错提示"undefined dependency",应该如何解决?
  2. 使用Code First方式时,实体类与SDL自动生成的类型不一致,比如字段 nullable 配置不生效,有什么排查思路?
  3. 在复杂的多模块项目中,如何优雅地组织Resolver和Schema定义?目前感觉文件分散难以维护。
  4. GraphQL订阅功能与NestJS的微服务架构结合时,有没有成熟的实践方案?特别是网关层该如何处理?
3 回复

在NestJS中集成GraphQL非常方便。首先通过npm安装必要的依赖:

npm install @nestjs/graphql graphql-tools graphql apollo-server-express

接着创建一个模块来承载GraphQL功能:

nest generate module graphql

graphql.module.ts中配置:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
    }),
  ],
})
export class GraphqlModule {}

然后定义数据模型和Resolvers:

  1. 创建一个用户模型文件user.model.ts
  2. user.resolver.ts里编写查询和变更逻辑。

例如:

import { Resolver, Query } from '@nestjs/graphql';

@Resolver()
export class UserResolver {
  @Query(() => String)
  hello() {
    return 'Hello World!';
  }
}

最后在主应用模块中引入GraphqlModule。这样你就完成了一个简单的GraphQL服务搭建。可以使用apollo-server进行进一步测试和优化。


在NestJS中集成GraphQL非常简单。首先,确保安装了必要的依赖:

npm install [@nestjs](/user/nestjs)/graphql graphql-tools graphql apollo-server-express
  1. 创建模块与服务
    使用nest g modulenest g service命令生成模块和服务。

  2. 配置GraphQL模块
    在模块文件中引入[@nestjs](/user/nestjs)/graphqlGraphQLModule,并设置Schema和Resolvers:

    import { Module } from '[@nestjs](/user/nestjs)/common';
    import { GraphQLModule } from '[@nestjs](/user/nestjs)/graphql';
    import { AppResolver } from './app.resolver';
    import { AppService } from './app.service';
    
    [@Module](/user/Module)({
      imports: [
        GraphQLModule.forRoot({
          autoSchemaFile: 'schema.gql', // 自动生成Schema文件
          sortSchema: true,
        }),
      ],
      providers: [AppService, AppResolver],
    })
    export class AppModule {}
    
  3. 编写Resolver
    创建Resolver类处理查询和变更:

    import { Resolver, Query } from '[@nestjs](/user/nestjs)/graphql';
    import { AppService } from './app.service';
    
    [@Resolver](/user/Resolver)()
    export class AppResolver {
      constructor(private readonly appService: AppService) {}
    
      @Query(() => String)
      hello(): string {
        return this.appService.hello();
      }
    }
    
  4. 编写Service
    Service用于业务逻辑实现:

    import { Injectable } from '[@nestjs](/user/nestjs)/common';
    
    [@Injectable](/user/Injectable)()
    export class AppService {
      hello(): string {
        return 'Hello World!';
      }
    }
    
  5. 运行项目
    启动应用后,使用GraphiQL界面测试API。

这是一个基础的GraphQL集成示例,你可以根据需求扩展查询、变更及订阅功能。

NestJS 集成 GraphQL 实践指南

GraphQL 是一种强大的 API 查询语言,与 NestJS 集成可以创建高效灵活的 API。以下是 NestJS 集成 GraphQL 的实践步骤:

1. 安装必要依赖

npm install @nestjs/graphql graphql apollo-server-express

2. 创建 GraphQL 模块

// app.module.ts
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
    }),
  ],
})
export class AppModule {}

3. 创建基本解析器 (Resolvers)

// cats.resolver.ts
import { Resolver, Query, Args } from '@nestjs/graphql';

@Resolver()
export class CatsResolver {
  private cats = [
    { id: 1, name: 'Kitty', age: 2 },
    { id: 2, name: 'Milo', age: 3 },
  ];

  @Query(() => [Cat])
  async cats() {
    return this.cats;
  }

  @Query(() => Cat)
  async cat(@Args('id') id: number) {
    return this.cats.find(cat => cat.id === id);
  }
}

4. 定义 GraphQL 类型

// cat.model.ts
import { ObjectType, Field, ID } from '@nestjs/graphql';

@ObjectType()
export class Cat {
  @Field(() => ID)
  id: number;

  @Field()
  name: string;

  @Field()
  age: number;
}

5. 配置模块

// cats.module.ts
import { Module } from '@nestjs/common';
import { CatsResolver } from './cats.resolver';

@Module({
  providers: [CatsResolver],
})
export class CatsModule {}

6. 运行应用

启动应用后,访问 http://localhost:3000/graphql 即可使用 GraphQL Playground 进行测试。

进阶功能

  • Mutations: 用于创建/更新数据
  • Subscriptions: 实现实时数据推送
  • DataLoader: 解决 N+1 查询问题
  • Schema Stitching: 合并多个 GraphQL 模式

NestJS 提供了两种 GraphQL 集成方式:

  1. 代码优先 (Code-first): 通过 TypeScript 类和装饰器生成 GraphQL 模式
  2. 模式优先 (Schema-first): 先编写 GraphQL SDL 文件

以上示例采用的是代码优先的方式,这也是 NestJS 推荐的方式。

回到顶部