[typescript] 타입스크립트를 이용한 GraphQL-js 개발

GraphQL은 API를 쉽게 설계하고 관리할 수 있는 강력한 쿼리 언어입니다. GraphQL을 JavaScript로 구현하는 가장 인기 있는 방법 중 하나는 graphql-js 라이브러리를 사용하는 것입니다. 이번 블로그에서는 타입스크립트를 사용하여 graphql-js를 개발하는 방법에 대해 알아보겠습니다.

1. 타입스크립트 및 GraphQL-js 프로젝트 설정

먼저, 타입스크립트 및 graphql-js 프로젝트를 설정하는 것부터 시작해 보겠습니다. 프로젝트 디렉토리에서 다음 명령을 실행하여 필요한 의존성을 설치합니다.

npm install graphql graphql-tools @types/graphql
npm install typescript ts-node ts-node-dev

그런 다음, tsconfig.json 파일을 프로젝트 루트 디렉토리에 생성하고 다음과 같이 설정합니다.

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

2. GraphQL 스키마 및 리졸버 작성

타입스크립트로 GraphQL 스키마 및 리졸버를 작성할 때는 타입을 명확하게 지정하여 개발할 수 있습니다. 아래는 예시입니다.

// src/schema.ts
import { makeExecutableSchema } from 'graphql-tools';

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

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

export default makeExecutableSchema({ typeDefs, resolvers });

3. 타입스크립트로 GraphQL 서버 실행

마지막으로, expressexpress-graphql을 사용하여 타입스크립트로 GraphQL 서버를 실행할 수 있습니다. 아래는 예시 코드입니다.

// src/server.ts
import express from 'express';
import graphqlHTTP from 'express-graphql';
import schema from './schema';

const app = express();
app.use('/graphql', graphqlHTTP({ schema, graphiql: true }));
app.listen(4000, () => {
  console.log('GraphQL Server is running on http://localhost:4000/graphql');
});

결론

이제 타입스크립트와 graphql-js를 사용하여 강력하고 유연한 GraphQL API를 개발하는 방법에 대해 알아보았습니다. 타입스크립트를 사용하면 명확한 타입 지정과 강력한 개발 도구를 활용하여 GraphQL 개발을 더욱 쉽게 만들 수 있습니다.

관련 참고 문서:

그럼 즐거운 타입스크립트와 GraphQL 개발 되시길 바랍니다!