Nestjs教程使用Apollo Server实现GraphQL服务
我在使用NestJS结合Apollo Server搭建GraphQL服务时遇到几个问题:
-
如何正确配置Apollo Server模块?官方文档的示例好像和NestJS的最新版本对不上,总是报模块导入错误。
-
GraphQL Schema应该放在项目什么位置比较规范?目前我是直接写在@Resolver装饰器里,但感觉维护起来很混乱。
-
有没有性能优化的建议?比如如何批量处理N+1查询问题?感觉响应速度比REST慢很多。
-
生产环境需要特别注意哪些Apollo Server的配置项?比如缓存、CSRF防护之类的。
求有实际项目经验的大佬指点!
要在NestJS中使用Apollo Server实现GraphQL服务,首先安装必要的依赖:
npm install [@nestjs](/user/nestjs)/graphql apollo-server-express graphql
-
配置模块
在app.module.ts
中引入GraphQLModule
:import { Module } from '[@nestjs](/user/nestjs)/common'; import { GraphQLModule } from '[@nestjs](/user/nestjs)/graphql'; [@Module](/user/Module)({ imports: [ GraphQLModule.forRoot({ autoSchemaFile: 'schema.gql', // 自动生成模式文件 sortSchema: true, // 按字母排序模式 }), ], }) export class AppModule {}
-
创建Resolver
创建一个GraphQL resolver来处理查询和变更。例如:import { Resolver, Query } from '[@nestjs](/user/nestjs)/graphql'; [@Resolver](/user/Resolver)() export class AppResolver { @Query(() => String) hello(): string { return 'Hello World!'; } }
-
启动Apollo Server
如果需要更复杂的配置,可以手动创建Apollo Server:import { NestFactory } from '[@nestjs](/user/nestjs)/core'; import { ApolloServer } from 'apollo-server-express'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const server = new ApolloServer({ schema: await app.getGraphQLSchmea(), }); await server.start(); server.applyMiddleware({ app }); await app.listen(3000); } bootstrap();
这样就完成了一个简单的GraphQL服务搭建。
NestJS结合Apollo Server可以快速搭建强大的GraphQL服务。首先安装依赖:
npm install @nestjs/graphql apollo-server graphql
创建模块和GraphQL服务:
nest generate module graph
nest generate service graph
配置app.module.ts
:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
@Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: 'schema.gql', // 自动生成模式文件
sortSchema: true, // 按字母顺序排序字段
playground: true, // 启用GraphQL Playground
}),
],
})
export class AppModule {}
定义数据模型和服务逻辑。例如,在graph.service.ts
中实现查询:
import { Injectable } from '@nestjs/common';
@Injectable()
export class GraphService {
getItems() {
return [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
];
}
}
在graph.resolver.ts
中定义查询和变更:
import { Resolver, Query } from '@nestjs/graphql';
import { GraphService } from './graph.service';
@Resolver()
export class GraphResolver {
constructor(private readonly service: GraphService) {}
@Query(() => [String])
async items() {
return this.service.getItems();
}
}
运行项目后即可通过GraphQL Playground测试接口。记得根据需求扩展类型、解析器和业务逻辑。
NestJS中使用Apollo Server实现GraphQL服务教程
安装必要依赖
首先需要安装相关依赖包:
npm install @nestjs/graphql graphql apollo-server-express
基本配置
- 在AppModule中导入GraphQLModule:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: true, // 自动生成schema文件
}),
],
})
export class AppModule {}
创建Resolver
Resolver相当于GraphQL中的控制器:
import { Resolver, Query, Args } from '@nestjs/graphql';
@Resolver()
export class AppResolver {
@Query(() => String)
sayHello(@Args('name') name: string): string {
return `Hello ${name}!`;
}
}
创建Schema类型
定义GraphQL类型:
import { ObjectType, Field, ID } from '@nestjs/graphql';
@ObjectType()
export class Book {
@Field(() => ID)
id: string;
@Field()
title: string;
@Field()
author: string;
}
完整示例
// book.resolver.ts
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { Book } from './book.model';
import { BookService } from './book.service';
@Resolver(() => Book)
export class BookResolver {
constructor(private bookService: BookService) {}
@Query(() => [Book])
async books() {
return this.bookService.findAll();
}
@Mutation(() => Book)
async addBook(
@Args('title') title: string,
@Args('author') author: string,
) {
return this.bookService.create({ title, author });
}
}
启动应用
运行应用后,默认GraphQL Playground会在http://localhost:3000/graphql
可用。
高级配置
可以配置更多Apollo Server选项:
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: 'schema.gql',
playground: true,
introspection: true,
context: ({ req }) => ({ req }),
formatError: (error) => ({
message: error.message,
code: error.extensions?.code,
}),
});
这就是在NestJS中使用Apollo Server实现GraphQL服务的基本方法。