0Pricing
NestJS Enterprise Backend APIs · 강의

NestJS GraphQL 설정

NestJS가 GraphQL API를 제공하도록 구성하고 코드 우선 방식과 스키마 우선 방식 중 하나를 선택합니다.

NestJS GraphQL 설정은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 graphql

graphql 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 .graphql or .gql file.
  • 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/graphql and @nestjs/apollo packages.
  • You saw how to integrate and configure the GraphQLModule in your AppModule.
  • 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 설정” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.

“NestJS GraphQL 설정”에서 뭘 배우나요?

NestJS가 GraphQL API를 제공하도록 구성하고 코드 우선 방식과 스키마 우선 방식 중 하나를 선택합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.

“NestJS GraphQL 설정” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. GraphQL 기초
  2. NestJS GraphQL 설정
  3. 리졸버와 구독
← NestJS Enterprise Backend APIs(으)로 돌아가기