[nodejs] Apollo Server를 사용한 GraphQL 서버 구축

최근에 GraphQL은 많은 웹 애플리케이션에서 데이터를 효율적으로 관리하는 데 사용되고 있습니다. Node.js로 GraphQL 서버를 구축하려면 Apollo Server를 사용하는 것이 좋습니다. 이 블로그 포스트에서는 Apollo Server를 사용하여 간단한 GraphQL 서버를 만드는 방법에 대해 알아보겠습니다.

목차

Apollo Server란 무엇인가

Apollo Server는 GraphQL을 위한 완전한 오픈 소스 서버입니다. 이를 사용하면 GraphQL 스키마, 리졸버, 데이터 소스 등을 구성할 수 있으며, 클라이언트 요청을 처리할 수 있습니다.

GraphQL 스키마 정의하기

먼저, GraphQL 스키마를 정의해야 합니다. 스키마는 데이터 그래프를 표현하며, 쿼리, 뮤테이션 등의 요청에 대한 응답을 정의합니다. 아래는 간단한 예제입니다.

type Query {
  hello: String
}

type Mutation {
  setMessage(message: String): String
}

위의 스키마는 hello 쿼리와 setMessage 뮤테이션을 정의합니다.

Apollo Server로 서버 구동하기

이제 Apollo Server를 사용하여 GraphQL 서버를 구동해 보겠습니다. 먼저, Express와 함께 apollo-server-express 패키지를 설치합니다.

npm install apollo-server-express express graphql

다음으로, 서버를 구성하고 실행할 JavaScript 코드를 작성합니다.

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

// 스키마 정의
const typeDefs = gql`
  type Query {
    hello: String
  }

  type Mutation {
    setMessage(message: String): String
  }
`;

// 리졸버 정의
const resolvers = {
  Query: {
    hello: () => 'Hello from GraphQL',
  },
  Mutation: {
    setMessage: (_, { message }) => {
      // 메시지 처리 로직
      return message;
    },
  },
};

// Apollo Server 설정
const server = new ApolloServer({ typeDefs, resolvers });

// Express 앱과 연결
const app = express();
server.applyMiddleware({ app });

// 서버 시작
app.listen({ port: 4000 }, () =>
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);

GraphQL 쿼리 및 뮤테이션 실행하기

이제 서버가 실행되었으므로, Playground 또는 웹 애플리케이션에서 GraphQL 쿼리와 뮤테이션을 실행할 수 있습니다. 아래는 간단한 예제입니다.

쿼리:

query {
  hello
}

뮤테이션:

mutation {
  setMessage(message: "Hello, GraphQL!")
}

이제 Apollo Server를 사용하여 GraphQL 서버를 구성하고 실행하는 방법을 알아보았습니다. Apollo Server는 강력하고 유연한 도구로, GraphQL API를 구축하고 관리하기에 탁월한 선택입니다. 관련 자세한 내용은 공식 문서를 참조하시기 바랍니다.


참고 자료: