Spring Boot + GraphQL 설정

Yeeun_Kim·2024년 4월 22일
0
post-thumbnail

기본 설정

build.gradle

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-graphql'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.mysql:mysql-connector-j'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.springframework:spring-webflux'
	testImplementation 'org.springframework.graphql:spring-graphql-test'
}

dependencies 설정에 'org.springframework.boot:spring-boot-starter-graphql'을 추가해주어야 사용 가능하다. 그 외 dependency들은 테스트를 하기 위한 설정들이다.

application.yml

spring:
  #DB설정부분 생략
  graphql:
    graphiql:
      enabled: true #GraphQL 가능 여부
    schema:
      printer:
        enabled: true

테스트 코드

User정보를 바탕으로 GraphQL을 사용하는 테스트 코드를 작성하였습니다.

User.java

@Entity
@Getter
@Setter
public class User {
    @Id
    private String id;
    private String phone;
    private String email;
}

UserRepository.java

@GraphQlRepository
public interface UserRepository extends JpaRepository<User, String> {
}

UserService.java

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;

    public List<User> getUsers() {
        return userRepository.findAll();
    }
}

UserController.java

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class UserController {
    private final UserService userService;

    @QueryMapping
    public List<User> getUsers() {
        return userService.getUsers();
    }
}

schema.graphqls

type Query {
	getUsers:[User]
}

type User {
	id:ID,
    phone:String,
    email:String
}

GraphQL 실행

query {
	getUsers {
    	id
    }
}
  • getUser()를 통해서 데이터를 가져올때 id값만을 조회한다는 의미이다.
  • 이를 통해서 OverFetching문제를 해결할 수 있다.
결과

2개의 댓글

comment-user-thumbnail
2024년 4월 23일

front에서 직접적인 query를 입력함으로써 받는 데이터 용량을 더 줄일 수도 있군요.
좋은 글 감사합니다!

답글 달기
comment-user-thumbnail
2024년 4월 25일

request를 명시함으로 디비에 접근하는 것이 코드적으로 보아도 프론트와 백의 용어를 어느정도 맞출 수 있을 것 같아 이점으로 보이네요!

답글 달기