[nodejs] GraphQL 서버와 데이터베이스 연동

이번 포스트에서는 GraphQL 서버와 데이터베이스를 연동하는 방법에 대해 알아보겠습니다.

1. GraphQL 서버 구축

먼저, Node.js에서 GraphQL 서버를 구축해야 합니다. 이를 위해 apollo-serverexpress-graphql과 같은 라이브러리를 사용할 수 있습니다.

예시로, apollo-server를 사용하여 GraphQL 서버를 구축하는 방법은 다음과 같습니다.

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 ready at ${url}`);
});

2. 데이터베이스 연동

GraphQL 서버와 데이터베이스를 연동하려면 데이터베이스에 액세스하는 함수를 작성해야 합니다. 예를 들어, MongoDB를 사용하는 경우 mongoose 라이브러리를 이용하여 데이터베이스에 접근할 수 있습니다.

다음은 MongoDB에 연결하는 예시 코드입니다.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database', {useNewUrlParser: true, useUnifiedTopology: true});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to MongoDB");
});

3. Resolver에서 데이터베이스 사용

마지막으로, GraphQL resolver 함수에서 데이터베이스를 사용하여 실제 데이터를 가져오거나 저장할 수 있습니다. 이를 통해 클라이언트의 쿼리에 따라 데이터베이스에서 필요한 정보를 반환할 수 있습니다.

예를 들어, MongoDB에서 데이터를 가져오는 resolver 함수는 다음과 같이 작성할 수 있습니다.

const resolvers = {
  Query: {
    getUser: async (parent, args, context, info) => {
      return await User.find(args.id);
    },
  },
};

이제 여러분은 GraphQL 서버와 데이터베이스를 연동하여 클라이언트의 요청에 따라 데이터를 가져오고 저장할 수 있게 되었습니다.

이상으로 GraphQL 서버와 데이터베이스를 연동하는 방법에 대해 알아보았습니다.

참고 자료: Apollo Server 문서, Mongoose 문서