# GraphQL query, mutation
###### tags: `tech sharing`
```graphql=
{
hero {
name
# 쿼리에 주석을 쓸 수도 있습니다!
friends {
name
}
}
}
```
필드에 인자를 추가할 수 있다.
```graphql=
{
human(id: "1000") {
name
height(unit: FOOT)
}
}
```
필드의 결과를 원하는 이름으로 바꿀 수 있다. 이것을 `alias`라고 한다.
```graphql=
{
empireHero: hero(episode: EMPIRE) {
name
}
jediHero: hero(episode: JEDI) {
name
}
}
```
## 프래그먼트
재사용 가능한 field set을 프래그먼트라고 한다
```graphql=
{
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}
fragment comparisonFields on Character {
name
appearsIn
friends {
name
}
}
```
query나 mutaion에 선언된 변수는 프래그먼트에서 접근할 수 있다.
```graphql=
query HeroComparison($first: Int = 3) {
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}
fragment comparisonFields on Character {
name
friendsConnection(first: $first) {
totalCount
edges {
node {
name
}
}
}
}
```
## Operation Name
작업 타입과 작업 이름을 생략한 채로 작성을 할 수도 있지만 기능을 명확하게 명시해주기 위해서 작업 타입과 작업 이름을 적어주는 것이 좋다.
```graphql=
query HeroNameAndFriends {
hero {
name
friends {
name
}
}
}
```
### Operation types
- query
- mutation
- subscription
## 변수
필드에 대한 인자는 대부분의 프로그램에서 동적이다. 클라이언트의 코드에서 쿼리 문자열을 runtime에 동적으로 조작하고 GraphQL의 특정한 포맷으로 만들어야하기 때문에 인자를 쿼리 문자열에 직접 전달한느 것은 좋은 방법이 아니다. 따라서 값을 별도로 전달하는 방법을 제공하는데 이를 `변수`라고 한다.
변수를 사용하기 위해서 해야하는 작업은 다음과 같다.
1. 쿼리 안의 정적인 값을 `$variableName`으로 변경한다.
2. $variableName 을 쿼리에서 받는 변수로 선언한다.
3. variableName: value 을 전달힌디.
```graphql=
query HeroNameAndFriends($episode: Episode) {
hero(episode: $episode) {
name
friends {
name
}
}
}
```
변수에는 기본값을 할당할 수 있다.
## Directives
변수를 사용하여 쿼리의 구조와 형태 등을 동적으로 변경하는 방법이다.
- `@include(if: Boolean)`: 인자가 true 인 경우에만 이 필드를 결과에 포함한다.
- `@skip(if: Boolean)`: 인자가 true 이면 이 필드를 건너뛴다.
```graphql=
query Hero($episode: Episode, $withFriends: Boolean!) {
hero(episode: $episode) {
name
friends @include(if: $withFriends) {
name
}
}
}
```
## Mutation
```graphql=
mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
```
쿼리 필드는 병렬로 실행되지만 뮤테이션 필드는 하나씩 차례대로 실행된다.