이번 블로그 포스트에서는 GraphQL Subscriptions를 이용하여 자바스크립트로 실시간 투표 애플리케이션을 개발하는 방법에 대해 알아보겠습니다.
GraphQL Subscriptions란?
GraphQL Subscriptions는 GraphQL의 기능 중 하나로, 클라이언트와 서버 간의 실시간 통신을 가능하게 합니다. 이를 통해 데이터의 변경 사항을 실시간으로 알릴 수 있으며, 실시간 채팅, 알림, 푸시 알림 등 다양한 실시간 기능을 구현할 수 있습니다.
개발 환경 설정
이번 예제에서는 Node.js와 Apollo Server, Apollo Client, 그리고 React를 사용합니다.
-
Node.js 설치: Node.js를 설치해주세요. 설치된 버전은
node -v
명령어로 확인할 수 있습니다. -
프로젝트 초기화: 새로운 디렉토리를 생성하고,
npm init
명령어를 실행하여 새로운 프로젝트를 초기화합니다. -
필요한 패키지 설치: 다음 명령어를 실행하여 필요한 패키지를 설치합니다.
npm install apollo-server apollo-boost graphql react react-dom
서버 개발하기
server.js
파일을 생성하고 다음과 같이 코드를 작성합니다. ```javascript const { ApolloServer, gql, PubSub } = require(‘apollo-server’);
const typeDefs = gql` type Query { votes: [Int!]! }
type Mutation { vote(index: Int!): [Int!]! }
type Subscription { onVote: Int! } `;
const pubsub = new PubSub(); let voteCount = [0, 0, 0];
const resolvers = { Query: { votes: () => voteCount, }, Mutation: { vote: (_, { index }) => { voteCount[index]++; pubsub.publish(‘VOTE_UPDATE’, { onVote: index }); return voteCount; }, }, Subscription: { onVote: { subscribe: () => pubsub.asyncIterator(‘VOTE_UPDATE’), }, }, };
const server = new ApolloServer({ typeDefs, resolvers, });
server.listen().then(({ url }) => {
console.log(Server ready at ${url}
);
});
2. 다음 명령어를 실행하여 서버를 실행합니다.
```bash
node server.js
클라이언트 개발하기
index.js
파일을 생성하고 다음과 같이 코드를 작성합니다. ```javascript import React from ‘react’; import ReactDOM from ‘react-dom’; import { ApolloProvider, useMutation, useSubscription, useQuery, gql } from ‘@apollo/client’; import { WebSocketLink } from ‘@apollo/client/link/ws’; import { split } from ‘@apollo/client’; import { getMainDefinition } from ‘@apollo/client/utilities’;
const httpLink = new createHttpLink({ uri: ‘http://localhost:4000’ });
const wsLink = new WebSocketLink({ uri: ‘ws://localhost:4000/graphql’, options: { reconnect: true, }, });
const splitLink = split( ({ query }) => { const definition = getMainDefinition(query); return ( definition.kind === ‘OperationDefinition’ && definition.operation === ‘subscription’ ); }, wsLink, httpLink, );
const client = new ApolloClient({ link: splitLink, cache: new InMemoryCache() });
const GET_VOTES = gql
query {
votes
}
;
const ON_VOTE = gql
subscription {
onVote
}
;
const VOTE = gql
mutation Vote($index: Int!) {
vote(index: $index)
}
;
const VoteApp = () => { const { data } = useQuery(GET_VOTES); const { data: voteData } = useSubscription(ON_VOTE); const [vote] = useMutation(VOTE);
const handleVote = (index) => { vote({ variables: { index, }, }); };
return (
<div>
<h1>실시간 투표 애플리케이션</h1>
<h2>투표 결과:</h2>
<ul>
{data && data.votes.map((count, index) => (
<li key={index}>{투표 ${index + 1}: ${count}
}</li>
))}
</ul>
<h3>투표하기:</h3>
<button onClick={() => handleVote(0)}>투표 1</button>
<button onClick={() => handleVote(1)}>투표 2</button>
<button onClick={() => handleVote(2)}>투표 3</button>
{voteData && <p>{새로운 투표: ${voteData.onVote + 1}
}</p>}
</div>
);
};
ReactDOM.render(
<ApolloProvider client={client}>
2. 다음 명령어를 실행하여 클라이언트 애플리케이션을 실행합니다.
```bash
npm start
결론
이번 포스트에서는 GraphQL Subscriptions를 이용하여 자바스크립트로 실시간 투표 애플리케이션을 개발하는 방법을 알아보았습니다. 실시간 통신을 구현하는 GraphQL Subscriptions는 웹 애플리케이션 개발에 있어 매우 유용하며, 실시간 데이터 업데이트를 처리하는데 효과적입니다. 추가로 GraphQL Subscriptions의 공식 문서를 참고하시는 것을 추천드립니다.