# GraphQL type
###### tags: `tech sharing`
## 객체 타입
GraphQL 스키마의 가장 기본적인 구성요소는 객체 타입이다. 객체 타입은 서비스에서 가져올 수 있는 객체의 종류와 객체의 field를 나타낸다.
```graphql=
type Character {
name: String!
appearsIn: [Episode]!
}
```
## arguments
객체 타입의 모든 field는 0개 이상의 인자를 가질 수 있다. graphql의 인자에는 순서가 없다.
```graphql=
type Starship {
id: ID!
name: String!
length(unit: LengthUnit = METER): Float
}
```
## Query type과 mutation type
스키마의 대부분의 타입은 일반 객체 타입이지만 스키마 내에는 `Query`, `Mutation`이라는 특수한 두 가지 타입이 있다. 이 두가지 타입은 GraphQL 쿼리의 진입점을 정의한다.
```graphql=
query {
hero {
name
}
droid(id: "2000") {
name
}
}
```
위와 같은 query가 있다면 graphQL의 Query type에 `hero`와 `droid`가 있어야한다.
```graphql=
type Query {
hero(episode: Episode): Character
droid(id: ID!): Droid
}
```
## 내장 자료형(스칼라 타입)
- ID : String이지만 고유 식별자 역할을 한다.
- String
- Int
- Float
- Boolean
> `!`가 붙으면 null을 반환할 수 없다.
## 열거 타입
```javascript=
// _enums.js
const { gql } = require('apollo-server')
const typeDefs = gql`
enum Role {
developer
designer
planner
}
enum NewOrUsed {
new
used
}
`
module.exports = typeDefs
// inde.js
const enums = require('./typedefs-resolvers/_enums')
// ...
const typeDefs = [
// ...
enums,
// ...
]
```
## 리스트 타입
```javascript=
const typeDefs = gql`
// ...
type EquipmentAdv {
id: ID!
used_by: Role!
count: Int!
use_rate: Float
is_new: Boolean!,
users: [String!]
}
`
```
| 선언부 |users: null |users: [ ] |users: [..., null]|
| -------- | -------- | -------- |-------- |
| [String]| ✔| ✔| ✔|
| [String!] |✔ |✔ |❌|
| [String]! |❌ |✔| ✔|
| [String!]!| ❌ |✔ |❌|
## 유니언
타입 여럿을 한 배열에 반환하고자 할 때 사용한다.
```javascript=
const { gql } = require('apollo-server')
const dbWorks = require('../dbWorks.js')
const typeDefs = gql`
union Given = Equipment | Supply
`
const resolvers = {
Query: {
givens: (parent, args) => {
return [
...dbWorks.getEquipments(args),
...dbWorks.getSupplies(args)
]
}
},
Given: {
__resolveType(given, context, info) {
if (given.used_by) {
return 'Equipment'
}
if (given.team) {
return 'Supply'
}
return null
}
}
}
module.exports = {
typeDefs: typeDefs,
resolvers: resolvers
}
```
## 인터페이스
유사한 객체 타입을 만들기 위한 공통 필드 타입
```javascript=
const { gql } = require('apollo-server')
const typeDefs = gql`
interface Tool {
id: ID!
used_by: Role!
}
`
const resolvers = {
Tool: {
__resolveType(tool, context, info) {
if (tool.developed_by) {
return 'Software'
}
if (tool.new_or_used) {
return 'Equipment'
}
return null
}
}
}
module.exports = {
typeDefs: typeDefs,
resolvers: resolvers
}
```