[java] Vaadin과 GraphQL 통신하기

Vaadin은 자바 기반의 웹 프레임워크로, 웹 애플리케이션 개발을 쉽고 효율적으로 할 수 있도록 도와줍니다. GraphQL은 데이터를 효율적으로 가져오거나 조작하기 위한 쿼리 언어입니다. 이번 글에서는 Vaadin과 GraphQL을 함께 사용하여 데이터를 통신하는 방법에 대해 알아보겠습니다.

1. 의존성 추가하기

Vaadin에서 GraphQL을 사용하기 위해서는 먼저 몇 가지 의존성을 추가해야 합니다. build.gradle 파일에 아래의 의존성을 추가해주세요.

implementation 'com.graphql-java-kickstart:graphql-spring-boot-starter:11.0.0'
implementation 'com.graphql-java-kickstart:graphql-java-tools:11.0.0'
implementation 'com.graphql-java-kickstart:graphiql-spring-boot-starter:11.0.0'

2. GraphQL 스키마 정의하기

Vaadin과 GraphQL을 통신하려면 먼저 GraphQL 스키마를 정의해야 합니다. 스키마는 GraphQL에서 사용할 데이터 모델과 쿼리, 뮤테이션 등을 정의합니다. 다음은 예시 스키마의 일부분입니다.

type User {
  id: ID!
  name: String!
  email: String!
}

type Query {
  user(id: ID!): User
  users: [User]
}

type Mutation {
  createUser(name: String!, email: String!): User
}

3. GraphQL 서버 설정하기

GraphQL 서버를 설정하기 위해 @SpringBootApplication 애너테이션이 있는 클래스에 @EnableGraphQL 애너테이션을 추가해주세요. 예시 코드는 다음과 같습니다.

import com.graphql.spring.boot.annotations.EnableGraphQL;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableGraphQL
public class YourApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

4. Vaadin에서 GraphQL 사용하기

Vaadin에서 GraphQL을 사용하기 위해서는 GraphQLClient를 사용하여 API 요청을 보내야 합니다. 예시 코드는 다음과 같습니다.

import com.graphql.spring.boot.client.GraphQLClient;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;

@Route
public class MainView extends VerticalLayout {

    private final GraphQLClient graphQLClient;

    public MainView(GraphQLClient graphQLClient) {
        this.graphQLClient = graphQLClient;

        Button fetchUserButton = new Button("Fetch User");
        fetchUserButton.addClickListener(e -> {
            // GraphQL API 요청 보내기
            String query = "query { user(id: \"1\") { id name email } }";
            String response = graphQLClient.executeQuery(query);
            
            // 결과 처리하기
            Notification.show(response);
        });

        add(fetchUserButton);
    }
}

위의 예시 코드는 Vaadin의 MainView에서 버튼 클릭 시 GraphQL API를 통해 사용자 정보를 가져와서 결과를 알림창으로 보여줍니다.

이렇게 Vaadin과 GraphQL을 함께 사용하여 효율적으로 데이터를 통신할 수 있습니다.

더 자세한 내용은 아래의 참고 자료를 확인해주세요.

참고 자료