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

서론

현대의 웹 애플리케이션은 실시간으로 업데이트되는 정보를 사용자에게 제공하는 것이 중요합니다. 실시간 알림 기능은 이러한 요구에 맞춰 사용자에게 즉각적인 업데이트를 제공할 수 있습니다. 이번 블로그 포스트에서는 Apollo Server와 Prisma를 이용하여 자바스크립트로 실시간 알림 기능을 구현하는 방법에 대해 알아보겠습니다.

Apollo Server 소개

Apollo Server는 GraphQL을 위한 서버 구현체입니다. GraphQL은 클라이언트가 원하는 데이터만 요청할 수 있는 쿼리 언어로, 서버와 클라이언트 간의 효율적인 통신을 가능하게 합니다. Apollo Server는 GraphQL 스키마와 리졸버를 제공하여 빠르고 간편하게 GraphQL API를 구축할 수 있습니다.

Prisma 소개

Prisma는 데이터베이스 작업을 쉽고 효율적으로 처리할 수 있는 ORM(Object-Relational Mapping)으로, TypeScript를 사용하여 강력한 타입 검사 기능을 제공합니다. Prisma는 데이터베이스 스키마를 기반으로 TypeScript 모델을 생성하고, 간단한 API를 통해 데이터베이스 작업을 수행할 수 있습니다.

Apollo Server와 Prisma를 이용한 실시간 알림 기능 구현

필요한 패키지 설치

먼저, 프로젝트 폴더에서 다음 패키지들을 설치해야 합니다:

$ npm install apollo-server prisma

GraphQL 스키마 작성

GraphQL 스키마는 서버와 클라이언트 간의 데이터 요청과 응답을 정의하는 역할을 합니다. schema.graphql 파일을 생성하고 다음과 같이 작성해주세요:

type Notification {
  id: ID!
  message: String!
}

type Query {
  notifications: [Notification!]!
}

type Mutation {
  createNotification(message: String!): Notification!
}

type Subscription {
  newNotification: Notification!
}

위의 스키마는 Notification이라는 타입과 데이터베이스에서 알림을 가져오기 위한 Query, 알림을 생성하기 위한 Mutation, 그리고 실시간 새 알림을 구독하기 위한 Subscription을 정의합니다.

Prisma 모델 생성

Prisma는 데이터베이스 스키마를 기반으로 TypeScript 모델을 생성해줍니다. 프로젝트 폴더에서 다음 명령어를 실행하여 Prisma 모델을 생성해주세요:

$ npx prisma init

위 명령어를 실행하면 prisma 폴더와 prisma/schema.prisma 파일이 생성됩니다. schema.prisma 파일을 다음과 같이 수정해주세요:

model Notification {
  id        Int      @id @default(autoincrement())
  message   String
}

Apollo Server 설정

index.js 파일을 생성하고 다음과 같이 작성해주세요:

const { ApolloServer, PubSub } = require('apollo-server');
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

const pubsub = new PubSub();

const typeDefs = `
  // 이 부분은 위에서 작성한 `schema.graphql` 파일과 동일한 내용을 작성해주세요.
  // ...
`;

const resolvers = {
  Query: {
    notifications: async () => {
      return prisma.notification.findMany();
    },
  },
  Mutation: {
    createNotification: async (_, { message }) => {
      const newNotification = await prisma.notification.create({
        data: {
          message,
        },
      });

      pubsub.publish('NEW_NOTIFICATION', { newNotification });

      return newNotification;
    },
  },
  Subscription: {
    newNotification: {
      subscribe: () => pubsub.asyncIterator('NEW_NOTIFICATION'),
    },
  },
};

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

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

위의 코드는 Apollo Server를 설정하고 필요한 리졸버 함수들을 구현한 예시입니다. PrismaClient를 생성하여 Prisma와 데이터베이스를 연결하고, PubSub을 사용하여 실시간 알림을 발행하고 구독합니다.

클라이언트 구현

실시간 알림을 받기 위해 클라이언트에서는 ApolloClient를 사용하여 Subscription을 구독해야 합니다. 클라이언트에서의 구현은 Apollo Client 문서를 참고하시면 됩니다.

마무리

이번 포스트에서는 Apollo Server와 Prisma를 이용하여 자바스크립트로 실시간 알림 기능을 구현하는 방법에 대해 알아보았습니다. Apollo Server와 Prisma를 함께 사용하면 간편하고 빠르게 GraphQL API를 구축할 수 있습니다. 이러한 기능을 활용하여 실시간 알림 기능을 구현해보세요.

Keywords: 알림, 실시간, Apollo Server, Prisma

References: