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

목차


소개

이번 기술 블로그에서는 Apollo Server와 Prisma를 이용하여 자바스크립트 기반의 실시간 알림 시스템을 구축하는 방법을 알아보겠습니다. 실시간 알림 시스템은 사용자들에게 실시간으로 데이터를 업데이트해주는 중요한 기능입니다. Apollo Server는 GraphQL 서버를 쉽게 구축하도록 도와주는 도구이며, Prisma는 데이터베이스 레이어를 추상화하여 데이터를 다루기 쉽게 도와주는 ORM(Object Relation Mapping) 도구입니다.

기술 스택

이 프로젝트에서 사용되는 주요 기술 스택은 다음과 같습니다:

Apollo Server 설정

먼저, Apollo Server를 설정해야 합니다. Apollo Server를 설치하려면 다음 명령을 실행하세요:

npm install apollo-server

그런 다음, Apollo Server의 기본 설정을 다음과 같이 작성할 수 있습니다:

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

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

const resolvers = {
  Query: {
    hello: () => 'Hello, world!'
  }
};

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

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

Prisma 설정

Apollo Server를 설정했다면, 이제 Prisma를 설정해야 합니다. Prisma를 설치하려면 다음 명령을 실행하세요:

npm install prisma

그런 다음, Prisma의 설정 파일(prisma/schema.prisma)을 다음과 같이 작성할 수 있습니다:

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider      = "prisma-client-js"
  previewFeatures = ["computedInputs", "atomicNumberOperations"]
}

model User {
  id         Int      @id @default(autoincrement())
  email      String   @unique
  createdAt  DateTime @default(now())
}

model Notification {
  id            Int      @id @default(autoincrement())
  content       String
  userId        Int
  user          User     @relation(fields: [userId], references: [id])
  createdAt     DateTime @default(now())
}

GraphQL 스키마 작성

Apollo Server와 Prisma를 설정했다면, 이제 GraphQL 스키마를 작성해야 합니다. 다음은 간단한 스키마 예시입니다:

type User {
  id: Int!
  email: String!
  notifications: [Notification!]!
}

type Notification {
  id: Int!
  content: String!
  user: User!
  createdAt: String!
}

type Query {
  user(id: Int!): User
}

type Mutation {
  createNotification(content: String!, userId: Int!): Notification!
}

type Subscription {
  newNotification(userId: Int!): Notification!
}

Subscriptions 구현

Apollo Server는 Subscriptions를 통해 실시간 알림 기능을 구현할 수 있습니다. Subscriptions는 GraphQL 조건에 해당하는 이벤트 발생 시, 클라이언트에게 결과를 실시간으로 전달하는 기능입니다.

const { PubSub } = require('apollo-server');
const pubsub = new PubSub();

const NEW_NOTIFICATION = 'NEW_NOTIFICATION';

const resolvers = {
  Subscription: {
    newNotification: {
      subscribe: (_, { userId }) => pubsub.asyncIterator([NEW_NOTIFICATION]),
      resolve: payload => payload,
    },
  },
  Mutation: {
    createNotification: async (_, { content, userId }, { prisma }) => {
      const newNotification = await prisma.notification.create({
        data: {
          content,
          userId,
        },
      });

      pubsub.publish(NEW_NOTIFICATION, newNotification);

      return newNotification;
    },
  },
};

결론

위에서 설명한 방법을 통해 Apollo Server와 Prisma를 이용하여 자바스크립트 기반의 실시간 알림 시스템을 구현할 수 있습니다. Apollo Server와 Prisma를 사용하면 서버와 데이터베이스를 쉽게 구축할 수 있으며, GraphQL을 통해 효율적인 데이터 통신을 할 수 있습니다. 위 예시 코드를 참고하여 실시간 알림 시스템을 구축해보세요.

#javascript #ApolloServer