设置 NestJS GraphQL
配置 NestJS 提供 GraphQL API,并在代码优先和模式优先两种方式之间进行选择。
设置 NestJS GraphQL 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
Welcome to GraphQL Setup
Hello! In this lesson, you'll learn how to integrate GraphQL into your NestJS application. We'll cover the essential setup steps and explore two primary approaches:
- Schema-First: Defining your API using GraphQL Schema Definition Language (SDL).
- Code-First: Building your schema directly from TypeScript classes and decorators.
By the end, you'll be able to choose the best approach for your project and have a basic GraphQL server running!
Install GraphQL Dependencies
Before we write any code, we need to install the necessary packages. NestJS uses @nestjs/graphql along with an underlying GraphQL library like Apollo.
Open your terminal and run the following command to add the required packages:
npm install @nestjs/graphql @nestjs/apollo graphqlgraphql is the core GraphQL library, and @nestjs/apollo provides the Apollo server integration.
Configure GraphQLModule
The heart of NestJS GraphQL is the GraphQLModule. You need to import it into your root module (usually AppModule) and configure it. Here's a basic setup:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver, // Use Apollo for GraphQL server
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
// main.ts (entry point for NestJS)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('GraphQL server ready on http://localhost:3000/graphql');
}
bootstrap();Schema-First: Design with SDL
The Schema-First approach means you define your GraphQL schema using the Schema Definition Language (SDL) first. This is like creating a blueprint for your API.
- You write your types, queries, and mutations in a
.graphqlor.gqlfile. - NestJS then uses this file to understand your API structure.
- You'll later connect these schema definitions to actual data handling logic (resolvers).
Schema-First: Basic Type Example
Let's define a simple Author type in an SDL file. This file describes the data structure without any implementation details yet.
// src/graphql.schema.gql
type Author {
id: ID!
firstName: String
lastName: String
}
type Query {
authors: [Author!]!
author(id: ID!): Author
}Schema-First: Link Schema to Module
To make NestJS aware of your SDL file, you configure the GraphQLModule to point to it. This tells NestJS where to find your schema definition.
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
typePaths: ['./**/*.gql'], // Tells NestJS where to find .gql files
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
// main.ts (entry point for NestJS)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('GraphQL server ready on http://localhost:3000/graphql');
}
bootstrap();Code-First: TypeScript Magic
The Code-First approach leverages TypeScript decorators to define your GraphQL schema. Instead of writing SDL, you define classes that NestJS automatically converts into a GraphQL schema.
- You use decorators like
@ObjectType()and@Field()on your TypeScript classes. - This approach offers strong type safety and excellent IDE support.
- It reduces duplication, as your TypeScript types directly define your GraphQL schema.
Code-First: Create an Object Type
Here's how you define the same Author type using the code-first approach. Notice the use of @ObjectType and @Field decorators.
// src/authors/models/author.model.ts
import { Field, ID, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class Author {
@Field(type => ID) // Explicitly define GraphQL type
id: number;
@Field({ nullable: true }) // Field can be null
firstName?: string;
@Field({ nullable: true })
lastName?: string;
}Code-First: Auto-Generating Schema
For the code-first approach, the GraphQLModule automatically generates the schema by scanning your project for classes decorated with @ObjectType(), @InputType(), etc.
You simply tell it where to save the generated schema file (optional, but good for inspection).
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: 'src/schema.gql', // Path to save the generated schema
sortSchema: true, // Optional: keeps schema consistent
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
// main.ts (entry point for NestJS)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('GraphQL server ready on http://localhost:3000/graphql');
}
bootstrap();Schema-First vs. Code-First
Both approaches are valid, and your choice often depends on team preference and project needs:
- Schema-First: Great for API design collaboration. The schema is the single source of truth, making it easy for frontend teams to start consuming the API early.
- Code-First: Favored by TypeScript developers for its strong type safety, less context switching, and reduced schema-code duplication. It feels more idiomatic to NestJS.
NestJS supports both, allowing you to pick what works best!
Check Your Understanding
Let's test your knowledge about setting up GraphQL in NestJS.
Lesson Summary
Great job! You've learned the fundamental steps to set up a GraphQL API in NestJS.
- We installed the necessary
@nestjs/graphqland@nestjs/apollopackages. - You saw how to integrate and configure the
GraphQLModulein yourAppModule. - We explored both the Schema-First approach (using SDL files) and the Code-First approach (using TypeScript decorators).
You now have the foundation to choose and implement your preferred GraphQL setup in NestJS!
常见问题解答
「设置 NestJS GraphQL」课时是免费的吗?
是的 — 「设置 NestJS GraphQL」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
「设置 NestJS GraphQL」这节课中我会学到什么?
配置 NestJS 提供 GraphQL API,并在代码优先和模式优先两种方式之间进行选择。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NestJS Enterprise Backend APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。
「设置 NestJS GraphQL」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?
能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- GraphQL 基础
- 设置 NestJS GraphQL
- 解析器与订阅