GraphQL

[GraphQL] Query & Mutation

동누크 2022. 12. 26. 16:28

Query 구현 - Code

Query : 데이터 조회
Mutation : 데이터 추가, 수정, 삭제

Query 루트 타입

type Query {
    teams: [Team]
}
  • 자료요청에 사용될 쿼리들을 정의
  • 쿼리 명령문마다 반환될 데이터 형태를 지정

Type

type Team {
    id: Int
    manager: String
    office: String
    extension_number: String
    mascot: String
    cleaning_duty: String
    project: String
}
  • 반환될 데이터의 형태를 지정
  • 자료형을 가진 필드들로 구성

Resolver

const resolvers = {
  Query: {
    teams: () => database.teams
  }
}
  • Query란 object의 항목들로 데이터를 반환하는 함수 선언
  • 실제 프로젝트에서는 MySQL 조회 코드 등..

Mutation 구현 - Code

Equipment 데이터 추가하기

Mutation - 추가 루트 타입

type Mutation {
    insertEquipment(
        id: String,
        used_by: String,
        count: Int,
        new_or_used: String
    ): Equipment
    ...
}

Resolver

Mutation: {
    insertEquipment: (parent, args, context, info) => {
        database.equipments.push(args)
        return args
    },
    //...
}
  • SQL의 INSERT 문 등으로 구현

Test

mutation {
  insertEquipment (
    id: "laptop",
    used_by: "developer",
    count: 17,
    new_or_used: "new"
  ) {
    id
    used_by
    count
    new_or_used
  }
}

Equipment 데이터 수정하기

Mutation - 수정 루트 타입

type Mutation {
    editEquipment(
        id: String,
        used_by: String,
        count: Int,
        new_or_used: String
    ): Equipment
    ...
}

Resolver

Mutation: {
    // ...
    editEquipment: (parent, args, context, info) => {
        return database.equipments.filter((equipment) => {
            return equipment.id === args.id
        }).map((equipment) => {
            Object.assign(equipment, args)
            return equipment
        })[0]
    },
    // ...
}
  • SQL의 UPDATE 문 등으로 구현

Test

mutation {
  editEquipment (
    id: "pen tablet",
    new_or_used: "new",
    count: 30,
    used_by: "designer"
  ) {
    id
    new_or_used
    count
    used_by
  }
}

Equipment 데이터 삭제하기

Mutation - 삭제 루트 타입

type Mutation {
    deleteEquipment(id: String): Equipment
}

Resolver

Mutation: {
      deleteEquipment: (parent, args, context, info) => {
          const deleted = database.equipments
              .filter((equipment) => {
                  return equipment.id === args.id
              })[0]
          database.equipments = database.equipments
              .filter((equipment) => {
                  return equipment.id !== args.id
              })
          return deleted
      }
}
  • 삭제 후 결과값으로 받아올 데이터를 deleted 변수에 저장
  • 데이터에서 해당 데이터 삭제 후 deleted 반환
  • 실제 프로젝트에서는 SQL의 DELETE 문 등으로 구현

Test

mutation {
  deleteEquipment(id: "notebook") {
    id
    used_by
    count
    new_or_used
  }
}

Reference

https://www.yalco.kr/@graphql-apollo/2-2/
https://www.yalco.kr/@graphql-apollo/2-3/

'GraphQL' 카테고리의 다른 글

[GraphQL] Apollo 서버 구축  (0) 2022.12.26
[GraphQL] GraphQL & Apollo  (0) 2022.12.26
[GraphQL] REST API 한계와 GraphQL 사용 이유  (0) 2022.12.26