[GraphQL] 유니언과 인터페이스

cooking_123·2024년 5월 2일

GraphQL

목록 보기
4/5

1. Union

타입 여럿을 한 배열에 반환하고자 할 때 사용

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) { // given에 used.by가 있으면 Equipment
                return 'Equipment'
            }
            if (given.team) { // given에 team항목이 있으면 Supply
                return 'Supply'
            }
            return null
        }
    }
}
module.exports = {
    typeDefs: typeDefs,
    resolvers: resolvers
}

index.js에 모듈을 추가해주고 데이터를 불러오면 아래와 같이 데이터가 들어오는 것을 볼 수 있다.

query {
  givens {
    __typename // 각각의 데이터가 Equipment에 속하는지 Supply에 속하는지 보여준다.
    ... on Equipment {
      id
      used_by
      count
      new_or_used
    }
    ... on Supply {
      id
      team
    }
  }
}

2. 인터페이스(Interface)

  • 유사한 객체 타입을 만들기 위한 공통 필드 타입
  • 추상 타입 - 다른 타입에 implement되기 위한 타입
type Equipment {
    id: ID!
    used_by: Role!
    count: Int
    new_or_used: NewOrUsed!
}
...
type Software {
    id: ID!
    used_by: Role!
    developed_by: String!
    description: String
}

위의 코드를 보면 id, used_by같은 공통적으로 가진 필드들이 있다. 객체 지향 언어들의 경우 인터페이스로 정의를 내린다.

tools.js

아래와 같이 공통된 필드를 가지고 인터페이스를 만들어 준다.

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
}

아래와 같이 implements를 넣어 작성해준다.

type Equipment implements Tool {
    id: ID!
    used_by: Role!
    count: Int
    new_or_used: NewOrUsed!
}
...
type Software implements Tool {
    id: ID!
    used_by: Role!
    developed_by: String!
    description: String
}

0개의 댓글