[typescript] 타입스크립트에서의 GraphQL 실습 예제

이번에는 TypeScript와 GraphQL을 함께 사용하는 방법에 대해 살펴보겠습니다. GraphQL은 API를 위한 쿼리 언어이자 런타임 시스템인데, TypeScript와 함께 사용하면 타입 안정성과 쿼리의 유효성을 보다 쉽게 관리할 수 있습니다.

1. GraphQL 서버 설정

먼저, GraphQL 서버를 설정해야 합니다. 아래는 단순한 예제를 위한 기본 설정입니다.

패키지 설치

npm install graphql express express-graphql

서버 코드 작성

import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'HelloWorld',
    fields: {
      message: {
        type: GraphQLString,
        resolve: () => 'Hello, World!'
      }
    }
  })
});

const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}));

app.listen(4000, () => {
  console.log('GraphQL server is running on http://localhost:4000/graphql');
});

2. 타입스크립트에서 GraphQL 사용

이제 GraphQL 서버가 설정되었으니, 타입스크립트에서 이를 사용해보겠습니다.

패키지 설치

npm install graphql apollo-server-express

클라이언트 코드 작성

import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';

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

const resolvers = {
  Query: {
    message: () => 'Hello, World!'
  }
};

const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(`GraphQL server is running on http://localhost:4000${server.graphqlPath}`)
);

결론

이제 단순한 예제를 통해 TypeScript와 GraphQL을 함께 사용하는 방법에 대해 알아보았습니다. 이를 기반으로 본격적인 프로젝트를 진행할 때, 유용한 팁과 기술들을 추가적으로 배워보시기를 권장합니다.

참고 문헌: