Apollo Server와 Prisma를 이용한 자바스크립트 실시간 알림 기능 구현

개요

이번 글에서는 Apollo Server와 Prisma를 이용하여 자바스크립트로 실시간 알림 기능을 구현하는 방법에 대해 알아보겠습니다. 실시간 알림은 많은 웹 애플리케이션에서 중요한 요소로 사용되며, 실시간으로 새로운 알림을 받는 기능을 제공합니다. 이를 위해 Apollo Server를 사용하여 GraphQL API를 구축하고, Prisma를 사용하여 데이터베이스를 관리할 것입니다.

작업 환경 설정하기

먼저, 프로젝트를 시작하기 위해 Node.js와 npm이 설치되어 있어야 합니다. 설치된 후에는 다음 명령어를 사용하여 필요한 패키지를 설치합니다.

npm install apollo-server apollo-server-express graphql prisma

데이터베이스 설정하기

Prisma를 사용하여 데이터베이스를 설정해야 합니다. prisma.yml 파일을 프로젝트 루트에 생성하고 다음과 같이 작성합니다.

endpoint: <YOUR_DATABASE_URL>
datamodel: datamodel.prisma
generate:
  - generator: javascript-client
    output: ./generated/prisma-client/

<YOUR_DATABASE_URL> 부분을 자신의 데이터베이스 URL로 대체합니다. 그리고 datamodel.prisma 파일을 생성하고, 다음과 같이 스키마를 정의합니다.

type User {
  id: ID! @unique
  name: String!
  email: String @unique
  posts: [Post!]!
}

type Post {
  id: ID! @unique
  title: String!
  content: String!
  author: User!
}

GraphQL API 구축하기

이제 Apollo Server를 사용하여 GraphQL API를 구축해보겠습니다. server.js 파일을 생성하고 다음과 같이 코드를 작성합니다.

const { ApolloServer, gql, PubSub } = require('apollo-server');
const { prisma } = require('./generated/prisma-client');

const pubsub = new PubSub();

const typeDefs = gql`
  type Query {
    posts: [Post!]!
  }

  type Mutation {
    createPost(title: String!, content: String!): Post!
  }

  type Subscription {
    newPost: Post!
  }

  type Post {
    id: ID!
    title: String!
    content: String!
    author: User!
  }

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

const resolvers = {
  Query: {
    posts: () => prisma.posts()
  },
  Mutation: {
    createPost: async (_, { title, content }) => {
      const post = await prisma.createPost({ title, content });
      pubsub.publish('NEW_POST', { newPost: post });
      return post;
    }
  },
  Subscription: {
    newPost: {
      subscribe: () => pubsub.asyncIterator('NEW_POST')
    }
  },
  Post: {
    author: (parent) => prisma.post({ id: parent.id }).author()
  }
};

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

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

클라이언트에서 실시간 알림 사용하기

위의 코드로 API 서버가 실행되면, 클라이언트에서 실시간 알림을 사용할 수 있습니다. 클라이언트에서 사용하는 예제 코드는 다음과 같습니다.

const { ApolloClient, InMemoryCache, gql, ApolloLink, split } = require('apollo-boost');
const { WebSocketLink } = require('apollo-link-ws');
const { getMainDefinition } = require('apollo-utilities');
const ws = require('ws');

const httpLink = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      authorization: 'Bearer <YOUR_AUTH_TOKEN>'
    }
  });
  return forward(operation);
});

const wsLink = new WebSocketLink({
  uri: 'ws://localhost:4000/',
  options: {
    reconnect: true,
    connectionParams: {
      authToken: '<YOUR_AUTH_TOKEN>'
    },
    connectionCallback: (error) => {
      if (error) {
        console.error('WebSocket connection failed:', error);
      } else {
        console.log('WebSocket connection established');
      }
    },
    webSocketImpl: ws
  }
});

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

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

const NEW_POST_SUBSCRIPTION = gql`
  subscription {
    newPost {
      id
      title
      content
      author {
        name
      }
    }
  }
`;

const createPost = async () => {
  const { data } = await client.mutate({
    mutation: gql`
      mutation {
        createPost(title: "New Post", content: "Lorem ipsum dolor sit amet") {
          id
        }
      }
    `
  });
};

const listenForNewPosts = () => {
  const subscription = client.subscribe({ query: NEW_POST_SUBSCRIPTION });
  subscription.subscribe({
    next: ({ data }) => {
      console.log('New post created:', data.newPost);
    },
    error: (error) => {
      console.error('Subscription error:', error);
    }
  });
};

createPost();
listenForNewPosts();

결론

위의 예제를 통해 Apollo Server와 Prisma를 이용하여 자바스크립트로 실시간 알림 기능을 구현하는 방법을 알아보았습니다. GraphQL API를 구축하고 클라이언트에서 실시간 알림을 받는 것은 비교적 간단하며, 확장성과 유연성을 높여줍니다. 이를 통해 웹 애플리케이션에 실시간성을 더하고 사용자 경험을 향상시킬 수 있습니다.

참고 자료

#javascript #graphql #apollo-server #prisma