GraphQL Subscriptions를 이용한 자바스크립트 실시간 푸시 알림 서비스 개발하기

이번 블로그 포스트에서는 GraphQL Subscriptions를 사용하여 자바스크립트로 실시간 푸시 알림 서비스를 개발하는 방법에 대해 알아보겠습니다.

목차

GraphQL Subscriptions란?

GraphQL Subscriptions는 GraphQL의 일부 기능으로, 실시간으로 데이터를 업데이트할 수 있는 기능입니다. 기존의 GraphQL 쿼리와 뮤테이션과 달리, Subscription은 클라이언트가 서버로부터 실시간 이벤트를 받을 수 있도록 합니다. 이를 통해 실시간 푸시 알림 서비스를 간편하게 개발할 수 있습니다.

실시간 푸시 알림 서비스 개발 과정

1. 필요한 패키지 설치

먼저, 개발에 필요한 패키지를 설치해야 합니다. Express.js와 GraphQL 관련 패키지를 설치하세요.

npm install express apollo-server graphql graphql-subscriptions subscriptions-transport-ws

2. GraphQL 스키마 설정

GraphQL 스키마를 설정해야 합니다. 스키마는 데이터 모델과 쿼리, 뮤테이션, 서브스크립션을 정의한 파일입니다. 예를 들어, 사용자 정보를 담고 있는 User 타입과 새로운 사용자 등록을 위한 뮤테이션을 정의할 수 있습니다.

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

type Subscription {
  newUser: User!
}

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

type Query {
  users: [User!]!
}

3. Subscription 리졸버 작성

Subscription 리졸버를 작성해야 합니다. 이 리졸버는 클라이언트가 구독할 이벤트를 정의하고, 해당 이벤트가 발생할 때 어떤 데이터를 전송할지를 설정합니다. 위의 예제에서는 newUser 이벤트를 정의하고, 새로운 사용자가 등록될 때 해당 사용자 정보를 클라이언트로 전송하도록 설정한 것입니다.

const resolvers = {
  Subscription: {
    newUser: {
      subscribe: () => pubsub.asyncIterator(['NEW_USER']),
      resolve: (payload) => payload,
    },
  },
  // ...Query 및 Mutation 리졸버 정의
};

4. Express 서버 설정

Express 서버를 설정해야 합니다. Apollo Server를 사용하여 GraphQL 스키마와 리졸버를 연결하고, 웹소켓을 통해 실시간 통신을 가능하도록 설정합니다.

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

const pubsub = new PubSub();

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

const server = new ApolloServer({
  typeDefs: require('./schema'),
  resolvers,
  subscriptions: {
    onConnect: (connectionParams, webSocket) => {
      console.log('Client connected');
    },
    onDisconnect: () => {
      console.log('Client disconnected');
    },
  },
});

server.applyMiddleware({ app });

SubscriptionServer.create(
  {
    schema: server.schema,
    execute,
    subscribe,
    onConnect: (connectionParams, webSocket) => {
      console.log('Client connected');
    },
    onDisconnect: () => {
      console.log('Client disconnected');
    },
  },
  {
    server: httpServer,
    path: server.graphqlPath,
  }
);

httpServer.listen(4000, () => {
  console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
});

5. 클라이언트 예제 작성

마지막으로, 클라이언트에서 GraphQL Subscription을 구독할 수 있는 예제를 작성합니다. Apollo Client를 사용하여 서버와 연결하고, Subscription 리스너를 등록하여 실시간으로 데이터를 받을 수 있습니다.

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

const client = new ApolloClient({
  uri: 'http://localhost:4000/graphql',
  cache: new InMemoryCache(),
});

client.subscribe({
  query: gql`
    subscription {
      newUser {
        id
        name
        email
      }
    }
  `,
}).subscribe({
  next(data) {
    const newUser = data.data.newUser;
    console.log('New User:', newUser);
    // 푸시 알림을 UI에 표시하는 로직을 작성하세요.
  },
  error(err) {
    console.error('Subscription Error:', err);
  },
});

결론

이제 자바스크립트로 GraphQL Subscriptions를 이용한 실시간 푸시 알림 서비스를 개발하는 방법에 대해 알아보았습니다. GraphQL Subscriptions를 사용하면 쉽고 간편하게 실시간 데이터 업데이트 기능을 구현할 수 있으므로, 실시간 푸시 알림 기능을 개발해야 하는 경우 유용하게 활용할 수 있습니다.

해시태그: #GraphQL #실시간푸시알림