자바스크립트를 사용하여 GraphQL Subscriptions와 데이터베이스 연동하기

GraphQL은 프론트엔드 및 백엔드 간의 효율적인 데이터 통신을 위한 쿼리 언어입니다. GraphQL Subscriptions는 실시간으로 업데이트되는 데이터를 처리하기 위한 기능을 제공합니다. 이번 글에서는 자바스크립트를 사용하여 GraphQL Subscriptions과 데이터베이스를 연동하는 방법에 대해 알아보겠습니다.

1. 설치 및 설정

먼저, 프로젝트에 필요한 패키지를 설치해야합니다. GraphQL Subscriptions를 구현하기 위해서는 graphql-yoga라는 패키지가 필요합니다. 여기에는 Subscriptions 기능을 지원하는 Apollo Server가 내장되어 있습니다.

npm install graphql-yoga

2. 데이터베이스 연동

데이터베이스와 연동하기 위해 프로젝트에 적절한 데이터베이스 드라이버를 설치해야합니다. 예를 들어, MongoDB를 사용하는 경우 mongoose 패키지를 설치할 수 있습니다.

npm install mongoose

데이터베이스 드라이버를 설치한 후에는 데이터베이스와의 연결을 설정해야합니다. 일반적으로 데이터베이스의 URL이나 인증 정보를 사용하여 연결을 설정합니다.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

3. GraphQL Subscriptions 구현

GraphQL Subscriptions를 구현하려면 GraphQL 스키마에 Subscription 타입을 추가해야합니다. 이 타입에는 서버에서 클라이언트로 실시간 데이터를 보내는 방법을 정의할 수 있습니다.

const { PubSub } = require('graphql-yoga');
const pubsub = new PubSub();

const typeDefs = `
  type Subscription {
    newMessage: Message!
  }

  type Message {
    text: String!
    sender: String!
  }

  type Query {
    messages: [Message!]!
  }
`;

const resolvers = {
  Subscription: {
    newMessage: {
      subscribe: () => pubsub.asyncIterator(['NEW_MESSAGE'])
    }
  },
  Query: {
    messages: () => {
      // 데이터베이스에서 메시지를 조회하고 반환하는 로직
    }
  }
};

const server = new GraphQLServer({ typeDefs, resolvers });
server.start({ subscriptions: '/subscriptions' }, () => console.log('Server is running on localhost:4000'));

위의 코드에서 Subscription 타입은 newMessage 필드를 갖습니다. 필드 구독(subscribe) 함수는 pubsub.asyncIterator를 사용하여 새로운 메시지 이벤트를 대기합니다.

4. 클라이언트에서 구독하기

이제 클라이언트에서 GraphQL Subscriptions를 구독할 수 있습니다. 클라이언트는 WebSocket 연결을 통해 서버로부터 데이터 업데이트를 실시간으로 받을 수 있습니다. 먼저, Apollo Client를 사용하여 클라이언트를 설정합니다.

import { ApolloClient, createHttpLink, InMemoryCache, split } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';

const httpLink = createHttpLink({
  uri: 'http://localhost:4000/graphql',
});

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/subscriptions`,
  options: {
    reconnect: true
  }
});

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink
);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

그런 다음, 구독을 등록하고 해당 이벤트가 발생할 때마다 데이터를 업데이트받을 수 있습니다.

import { gql, useSubscription } from '@apollo/client';

const MESSAGE_SUBSCRIPTION = gql`
  subscription {
    newMessage {
      text
      sender
    }
  }
`;

function App() {
  const { data, loading } = useSubscription(MESSAGE_SUBSCRIPTION);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {data.newMessage.sender}: {data.newMessage.text}
    </div>
  );
}

위의 코드에서 useSubscription 훅을 사용하면 MESSAGE_SUBSCRIPTION을 구독할 수 있습니다. 구독 중에는 실시간으로 업데이트를 수신하고 해당 데이터를 처리할 수 있습니다.

이제 자바스크립트를 사용하여 GraphQL Subscriptions와 데이터베이스를 연동하는 방법을 알게되었습니다. 실시간 데이터 업데이트를 위해 GraphQL Subscriptions를 사용하면 효율적이고 우수한 사용자 경험을 제공할 수 있습니다.

참고 자료