본문 바로가기
Node js/Nest js 강의 내용

(다음과정 미리보기) Graphql 사용하기

by Bill Lab 2025. 1. 27.
728x90

1. Graphql 이란

    : GraphQL은 API를 위한 "데이터 요청 언어"로, 클라이언트가 원하는 데이터를 효율적으로

      서버에서 가져올 수 있도록 돕는 기술

 

 

2. Why Graphql?

    : RestAPI와 비교시 여러가지 "장점"들이 있는데 아래와 같이 나열해보겠다.

 

    - B/E server End point가 하나이다!

      : rest 의 경우 /users(사용자목록), /orders(주문목록) 이나, Graphql 의 경우 /graphql 하나!) 

 

    - 필요한 Data 만 요청 가능

      : orders(주문목록) 중 상품명, 가격, 옵션, 변경일자, 재고 수량 중에 상품명과 가격만 필요한 경우가 있다고 가정하자

       rest의 경우 2개의 필드정보만 필요하더라도 전체를 가지고 와서 두개를 뽑아내야하지만, graphql 의 경우 2개 필드

       정보만 요청해서 가지고 올 수 있다.(서버 통신속도 및 비용 감소)

 

     - Data 결합

       : rest 의 경우 users 와 orders의 정보가 필요할 경우 호출을 두번 해야하지만, graphql 의 경우한번의 호출만으로 

       여러개의 조합된 정보를 가지고 올 수 있다.       

 

     - 실시간 Data 지원

       : rest 의 경우 실시간 data 를 구현하려면  websocket, Server Sent Event를 별도로 구현해야하지만 graphql의 경우

        subscription(구독)기능을 통해 실시간 data 스트리밍이 가능하다

 

   

3. Graphql 구조

    1) Schema

        - 객체타입

           : 스키마의 가장 기본적인 구성, 서비스에서 가져올 수 있는 객체의 종류와 필드를 정의(controller DTO와 유사)

type Book {
  title: String
  author: Author
}

type Author {
  name: String
  books: [Book]
}

 

        - 쿼리(query) 타입

        : rest 의 get에 해당하는 타입

query {
  user {
    name
  }
}

       

        - 뮤테이션(mutation) 타입

mutation CreateOrder($customerId: ID!, $items: [OrderItemInput!]!, $totalPrice: Float!) {
  createOrder(input: { customerId: $customerId, items: $items, totalPrice: $totalPrice }) {
    id
    status
    customer {
      id
      name
    }
    items {
      productId
      quantity
      price
    }
    totalPrice
    createdAt
  }
}

 

참조: https://www.apollographql.com/docs/apollo-server/schema/schema

 

 

4. Controller 대신 graphql 을 사용하여 호출하기(refactoring)

 

 

5. Playgroud

728x90