GraphQL Subscriptions를 이용한 자바스크립트 웹소켓 통신 개발하기

웹 애플리케이션에서 실시간 데이터 푸시를 구현하기 위해 웹소켓을 사용하는 것은 매우 일반적입니다. GraphQL Subscriptions는 GraphQL 서비스와 웹소켓을 연결하여 클라이언트와 서버 간의 실시간 통신을 용이하게 만드는 기술입니다. 이 기술을 사용하면 클라이언트에서 서버로부터의 데이터 변경 사항을 별도의 API 호출 없이도 구독(subscribe)하여 실시간으로 받을 수 있습니다.

이번 글에서는 GraphQL Subscriptions를 이용하여 자바스크립트로 웹소켓 통신을 개발하는 방법을 설명하겠습니다.

1. 웹소켓 서버 설정

웹소켓 통신을 위해 Express.js와 subscriptions-transport-ws 패키지를 사용할 것입니다. 다음과 같이 패키지를 설치합니다.

npm install express subscriptions-transport-ws

그리고 Express.js 서버를 시작합니다.

const express = require('express');
const { createServer } = require('http');
const { execute, subscribe } = require('graphql');
const { SubscriptionServer } = require('subscriptions-transport-ws');

const app = express();
const httpServer = createServer(app);

httpServer.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

// GraphQL 스키마와 리졸버를 import 하세요.

const subscriptionServer = SubscriptionServer.create(
  {
    execute,
    subscribe,
    schema: // GraphQL 스키마를 입력하세요,
    onConnect: // 웹소켓 연결 시 호출될 함수를 입력하세요
  },
  {
    server: httpServer,
    path: '/graphql',
  }
);

2. GraphQL Subscriptions 구현

이제 GraphQL Subscriptions를 구현할 차례입니다. GraphQL 스키마에 Subscription 타입을 정의하고 해당 타입에 필요한 필드와 리졸버 함수를 작성해야 합니다. 다음은 예시입니다.

type Subscription {
  newMessage: Message
}

type Message {
  id: ID!
  content: String!
}

이렇게 정의된 Subscription 타입은 클라이언트가 newMessage 필드에 구독(subscribe)하여 새로운 메시지가 생성될 때마다 실시간으로 데이터를 받을 수 있습니다.

리졸버 함수에서는 데이터 변경 시 클라이언트에게 데이터를 전송하는 방법을 정의해야 합니다. 예를 들어, newMessage 필드의 리졸버 함수는 새로운 메시지가 생성될 때마다 해당 메시지를 클라이언트에게 전송하는 역할을 합니다.

3. 클라이언트에서의 사용

웹소켓 통신을 위해 Apollo Client를 사용하여 클라이언트를 구현할 수 있습니다. Apollo Client를 사용하기 위해 다음과 같이 패키지를 설치합니다.

npm install apollo-client apollo-link-ws apollo-utilities subscriptions-transport-ws

그리고 클라이언트를 다음과 같이 설정합니다.

import ApolloClient from 'apollo-client';
import { WebSocketLink } from 'apollo-link-ws';
import { InMemoryCache } from 'apollo-cache-inmemory';

const client = new ApolloClient({
  link: new WebSocketLink({
    uri: 'ws://localhost:4000/graphql',
    options: {
      reconnect: true,
    },
  }),
  cache: new InMemoryCache(),
});

이제 위에서 정의한 Subscription 타입의 필드에 대해 구독(subscribe)을 수행하면 됩니다.

import { gql } from 'apollo-boost';

const NEW_MESSAGE_SUBSCRIPTION = gql`
  subscription {
    newMessage {
      id
      content
    }
  }
`;

const subscription = client.subscribe({
  query: NEW_MESSAGE_SUBSCRIPTION,
});

subscription.subscribe({
  next: data => {
    console.log('Received new message:', data.newMessage);
  },
});

위 코드에서 next 함수는 서버로부터 새로운 메시지가 전송되었을 때 호출됩니다.

이제 GraphQL Subscriptions를 이용하여 자바스크립트 웹소켓 통신을 개발할 수 있는 방법을 알아보았습니다. 웹 애플리케이션에서 실시간 데이터 푸시를 구현하는 데 GraphQL Subscriptions는 매우 유용한 기술입니다.

#reference #GraphQL #Websocket