본문 바로가기

GraphQL

[GraphQL] GraphQL 문법 - Alias, Fragment, Directives, Variables

 

 

[GraphQL] GraphQL이란, GraphQL vs REST API

GraphQL의 특징Facebook에서 개발한 데이터 쿼리 언어로, API 요쳥을 최적화하는 것을 목적으로 한다.GraphQL은 REST API의 대안으로 사용된다.클라이언트 주도 데이터 요청: 클라이언트는 필요한 데이터

kanoos-stu.tistory.com

 
 

Alias를 사용한 쿼리 요청

Alias를 사용하면 동일한 필드를 여러 번 요청하거나 반환되는 데이터의 이름을 변경할 수 있다.
예를 들어, 사용자의 이름과 이메일을 다른 이름으로 요청하고 싶다면 다음과 같이 할 수 있다.

{
    user1: user(id: 1) {
        userName: name
        email
        posts {
            postTitle: title
            content
        }
    }
}
  • user1: 반환된 데이터에서 user 필드 대신 user1이라는 이름으로 표시된다.
  • userName: name은 name 필드를 userName으로 요청
  • postTitle: title은 title 필드를 postTitle로 요청

 

응답값

{
    "data": {
        "user1": {
            "userName": "John Doe",
            "email": "john.doe@example.com",
            "posts": [
                {
                    "postTitle": "First Post",
                    "content": "This is the content of the first post."
                },
                {
                    "postTitle": "Second Post",
                    "content": "This is the content of the second post."
                }
            ]
        }
    }
}

 

Alias 응용 예시

{
    primaryUser: user(id: 1) {
        name
        email
        posts {
            title
            content
        }
    }
    secondaryUser: user(id: 2) {
        name
        email
        posts {
            title
            content
        }
    }
}

GraphQL 쿼리에서 한번에 동일한 필드명을 두 번 요청할 경우, 충돌이 발생하여 오류가 생길 수 있다.
이를 해결하기 위해 일반적으로 동일한 필드명을 가진 요청을 각각 해야 하지만, Alias를 사용하면 하나의 쿼리에서 동일한 필드명을 가진 요청 두개 이상을 한 번에 할 수 있다.
Alias를 사용하면 각 요청에 별칭을 부여하여 같은 쿼리라도 충돌 없이 데이터를 한 번에 요청할 수 있다.
 


 

Fragment를 사용한 쿼리 요청

 
Fragment를 사용하면 재사용 가능한 필드 세트를 정의할 수 있다.
이를 통해 쿼리의 반복을 줄일 수 있다.

{
    user(id: 1) {
        ...UserInfo
        posts {
            ...PostInfo
        }
    }
}

fragment UserInfo on User {
    name
    email
}

fragment PostInfo on Post {
    title
    content
}
  • fragment UserInfo on User는 User 타입에 대한 name과 email 필드 세트를 정의
  • fragment PostInfo on Post는 Post 타입에 대한 title과 content 필드 세트를 정의
  • 쿼리에서 ...UserInfo와 ...PostInfo를 사용하여 미리 정의한 필드 세트를 삽입

 

Alias와 Fragment 응용 예시

{
    primaryUser: user(id: 1) {
        ...UserInfo
        posts {
            ...PostInfo
        }
    }
    secondaryUser: user(id: 2) {
        ...UserInfo
        posts {
            ...PostInfo
        }
    }
}

fragment UserInfo on User {
    name
    email
}

fragment PostInfo on Post {
    title
    content
}

Fragment의 재사용성을 통해 기존의 Alias만 사용했을 때의 코드보다 훨씬 간결하게 작성할 수 있다.
 


 

Directives를 사용한 쿼리 요청

Directives는 쿼리나 스키마에 조건을 추가하여 특정 필드를 포함하거나 제외할 수 있게 해준다.
가장 흔하게 사용되는 Directive는 @include와 @skip

{
  user(id: 1) {
    name
    email @include(if: true)
    posts @skip(if: false) {
      title
      content
    }
  }
}
  • @include(if: true): 조건이 true일 때만 해당 필드를 포함
  • @skip(if: false): 조건이 false일 때만 해당 필드를 포함

 
 


 

Variables를 사용한 쿼리 요청

variable은 쿼리를 작성할 때 값을 하드코딩하지 않고 동적으로 제공할 수 있도록 한다.
이를 통해 쿼리의 재사용성과 유연성을 높일 수 있다.

query GetUser($userId: Int!) {
  user(id: $userId) {
    name
    email
  }
}

변수 $userId는 쿼리 외부에서 값을 전달받아 사용된다.
 

variables를 포함한 쿼리 요청

{
  "query": "query GetUser($userId: Int!) { user(id: $userId) { name email } }",
  "variables": { "userId": 1 }
}

 
 


 

Directives과 Variables를 함께 사용한 쿼리 요청

쿼리에서 Variables와 Directives를 함께 사용해서 동적이고 조건부적인 쿼리를 작성할 수 있다.
클라이언트가 어떤 데이터를 요청할지 동적으로 결정해야 할 때 유용하다.

query GetUser($userId: Int!, $includeEmail: Boolean!) {
  user(id: $userId) {
    name
    email @include(if: $includeEmail)
    posts {
      title
      content
    }
  }
}
  • $userId 변수는 사용자 ID를 동적으로 설정
  • $includeEmail 변수는 이메일 필드를 포함할지 여부를 동적으로 결정
  • email @include(if: $includeEmail) 지시자는 $includeEmail 변수가 true일 때만 이메일 필드를 포함

 

variables를 포함한 쿼리 요청

{
  "query": "
    query GetUser($userId: Int!, $includeEmail: Boolean!) { 
      user(id: $userId) { 
        name email @include(if: $includeEmail) 
        posts { 
          title content 
        } 
      }
    }",
  "variables": { "userId": 1, "includeEmail": true }
}

 

Directives과 Variables를 함께 사용한 쿼리의 장점

  1. 동적 쿼리 작성
    • Variables를 사용하면 쿼리를 작성할 때 값들을 하드코딩하지 않고 동적으로 설정할 수 있다.
    • 이로 인해 클라이언트 애플리케이션에서 사용자 입력이나 다른 동적 데이터를 쿼리에 포함시키기 쉽도록 한다.
  2. 조건부 데이터 포함
    • Directives를 사용하면 특정 조건에 따라 필드를 포함하거나 제외할 수 있다.
    • 이로 인해 불필요한 데이터를 요청하지 않도록 하여 네트워크 효율성을 높일 수 있다.
  3. 재사용성과 유연성
    • Variables와 Directives를 함께 사용하면 쿼리를 재사용 가능하고 유연하게 만들 수 있다.
    • 예를 들어, 하나의 쿼리로 다양한 조건을 처리할 수 있어 코드 중복을 줄일 수 있다.
  4. 네트워크 효율성
    • Directives로 데이터를 요청함으로써 필요한 데이터만 전송되어 네트워크 사용량을 줄일 수 있다.
    • 이는 특히 모바일 네트워크나 제한된 대역폭 환경에서 유용하다.
  5. 응답 크기 최적화
    • Directives를 통해 필요한 필드만 포함시키면 응답 크기를 줄일 수 있다.
    • 이는 클라이언트가 더 빠르게 데이터를 처리하고 사용자 경험을 향상시키는 데 도움이 된다.

 
 
* mutation과 subscriptions도 query와 마찬가지로 variables나 directives 같은 문법을 똑같이 사용할 수 있음