자바스크립트를 활용한 GraphQL Subscriptions 예제

GraphQL은 클라이언트와 서버 간의 데이터 교환을 위한 강력한 쿼리 언어입니다. 기본적으로는 클라이언트가 쿼리를 보내고 서버는 해당 쿼리에 대한 데이터를 응답하는 방식으로 작동합니다. 그러나 GraphQL Subscriptions을 사용하면 실시간으로 데이터를 전송하고 감지할 수 있습니다.

이번 예제에서는 자바스크립트와 함께 GraphQL Subscriptions을 사용하는 방법에 대해 알아보겠습니다. 예제를 작성하기 위해 우리는 Apollo Server와 Apollo Client를 사용할 것입니다.

서버 설정

먼저 서버를 설정해야 합니다. 아래는 Apollo Server를 사용하여 GraphQL Subscriptions을 활성화하는 예제입니다.

const { ApolloServer, gql, PubSub } = require('apollo-server');

const typeDefs = gql`
  type Query {
    hello: String
  }

  type Mutation {
    sendMessage(message: String!): String
  }

  type Subscription {
    newMessage: String
  }
`;

const pubsub = new PubSub();

const resolvers = {
  Query: {
    hello: () => 'Hello, World!',
  },
  Mutation: {
    sendMessage: (_, { message }) => {
      pubsub.publish('NEW_MESSAGE', { newMessage: message });
      return "Message sent!";
    },
  },
  Subscription: {
    newMessage: {
      subscribe: () => pubsub.asyncIterator('NEW_MESSAGE'),
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`);
});

위 코드에서는 typeDefs에 GraphQL 스키마를 정의하고, pubsub을 생성하여 Pub/Sub을 구현합니다. Mutation에서는 sendMessage을 통해 새로운 메시지를 발행하고, Subscription에서는 newMessage를 구독합니다.

클라이언트 설정

이제 클라이언트를 설정해야 합니다. 아래는 Apollo Client를 사용하여 GraphQL Subscriptions을 수신하는 예제입니다.

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

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

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

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

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

const subscription = gql`
  subscription {
    newMessage
  }
`;

const subscriptionObserver = client.subscribe({ query: subscription }).subscribe({
  next(result) {
    console.log(result.data.newMessage);
  },
  error(error) {
    console.error(error);
  },
});

위 코드에서는 httpLinkwsLink를 생성하여 HTTP 및 WebSocket 프로토콜을 사용하여 서버와 통신합니다. split 함수를 사용하여 쿼리의 종류에 따라 적절한 링크를 선택합니다.

그리고 마지막으로, subscription을 정의하고 이를 구독하기 위해 client.subscribe() 메소드를 호출합니다. subscribe 함수를 이용하여 신규 메시지가 도착할 때마다 결과를 출력합니다.

위 예제를 실행하면 서버에서 발행한 새로운 메시지를 실시간으로 수신할 수 있습니다.

이제 자바스크립트를 활용하여 GraphQL Subscriptions을 구현하는 방법을 알게 되었습니다. 이를 활용하여 실시간 데이터 전송 및 감지를 구현하실 수 있습니다. 더 자세한 내용은 Apollo 공식 문서를 참조하세요.

#GraphQL #Subscriptions