ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [2020.03.14] Express + GraphQL API 기본적인 Apollo서버 구현 (with TypeScript)
    개발 블로깅/TypeScript 2020. 3. 14. 01:58

     

    이번에 서브 프로젝트를 진행하기 위해, 백엔드를 Express 서버에 GraphQL을 사용하기로 했다.

    트레바리에서는 GraphQL을 사용하기 때문에 평소에 많이 접하기는 하지만, 내가 직접 환경을 구성하지 않아 환경 구성을 어떤식으로 하는지는 몰랐는데, 이번 기회에 내가 직접 GraphQL을 사용하는 Express 서버를 구축해 볼 수 있는 좋은 기회였다.

    TypeScript를 이용한 Express와 GraphQL의 서버 환경을 구축하는 쉬운 튜토리얼을 찾아보려 했지만 그러한 글을 찾아보기가 힘들었던 것 같다.

    그래서 이번에 내가 직접 서버를 구현해 보면서 진행한 과정을 이해하기 쉽도록 정리해보려고 한다.

     

    TypeScript를 사용하기 위한 기본적인 구성

    프로젝트 세팅

    우선 프로젝트로 사용할 폴더를 하나 생성 후, 해당 디렉토리에 package.json을 생성한다.

    $ mkdir backend-server
    $ cd backend-server
    $ npm init -y

     

    TypeScript 기본 설정 & 설치

    npx를 이용해서, 필요한 설정으로만 구성된 tsconfig.json을 생성한다. (tsc -init 명령어를 이용해도 무방하다.)

    그리고 코드를 변경할 때마다 자동으로 컴파일 및 실행 환경을 만들기 위해 nodemonts-node를 설치한다.

    $ npm install -D typescript nodemon ts-node
    $ npx tsc --init --rootDir src --outDir dist --lib dom,es6 --module commonjs --removeComments

     

    TypeScript 환경을 이용한 Hello World

    현재 'backend-server' 디렉토리 내에 /src 디렉토리와 함께 server.ts 파일을 생성한다.

    $ mkdir src
    $ cd src            // backend-server/src/
    $ touch server.ts   // VSCode 등을 이용해서 create File을 해도 무방

     

    server.ts 파일에 테스트 코드를 삽입 후, 실행시켜서 로그가 잘 나오는지 확인한다.

    // server.ts
    console.log("hello TypeScript~!");

    마지막으로 package.json 파일의 스크립트를 아래와 같이 변경한다.

    "scripts": {
      "dev": "nodemon 'src/server.ts' --exec 'ts-node' src/server.ts -e ts,graphql"
    }

    터미널에서 npm run dev 명령어를 실행하면, nodemon이 동작하면서 console.log의 값이 찍힐 것이다. nodemon은 server.ts 파일의 코드가 변경될 때마다 다시 컴파일 할 것이다.

     

    Express 세팅, Apollo와 간단한 GraphQL API 생성

    여기서는 GraphQL에 대한 원리 및 개념은 다루지 않는다. 그러므로 GraphQL을 처음 접한다면 GraphQL의 공식문서를 확인하면 될 것 같다.

    필요한 라이브러리 Install

    $ npm install -S apollo-server-express compression express graphql
    $ npm install -D @types/compression @types/express @types/graphql @types/graphql-depth-limit @types/node graphql-depth-limit graphql-import graphql-import-node
    apollo-server-express : express환경에서 apollo 환경을 쉽게 구축할 수 있게 해주는 라이브러리.
    compression : express 환경에서 Gzip 압축을 통해 response 데이터 사이즈를 크게 줄여 성능을 향상시켜주는 미들웨어. (찾아보니 이게 정말 대박이다. 나중에 더 자세히 알아봐야겠다.)

     

    기본 옵션으로 아폴로 서버 생성

    server.ts 파일의 코드를 아래와 같이 변경한다.

    import express from 'express';
    import { ApolloServer } from 'apollo-server-express';
    import depthLimit from 'graphql-depth-limit';
    import { createServer } from 'http';
    import compression from 'compression';
    import cors from 'cors';
    import schema from './schema';
    
    const app = express();
    const server = new ApolloServer({
      schema,
      validationRules: [depthLimit(7)],
    });
    
    app.use('*', cors());
    app.use(compression());
    
    server.applyMiddleware({ app, path: '/graphql' });
    
    const httpServer = createServer(app);
    httpServer.listen(
      { port: 8000 },
      (): void => console.log(`server Start`)
    );

    위의 코드에서 import를 하고 있는 schema는, 앞으로 생성할 GraphQL의 스키마 부분이다.

    GraphQL 스키마와 resolvers 생성

    /src폴더 안에 /schema 폴더와 schema.graphql 파일을 생성한다.

    $ mkdir schema
    $ cd schema
    $ touch schema.graphql

     

    schema.graphql 파일을 아래와 같이 작성한다.

    // schema.graphql
    type Query {
      helloWorld: String!
    }

     

    그리고 /src 폴더 바로 하위에 resolverMap 파일을 생성한다.

    $ cd ../
    $ touch resolverMap.ts
    
    // src/resolverMap.ts
    import { IResolvers } from 'graphql-tools';
    const resolverMap: IResolvers = {
      Query: {
        helloWorld(_: void, args: void): string {
      return `Hello GraphQL~!`;
        },
      },
    };
    export default resolverMap;

     

    마지막으로, GraphQL schema를 실행시킬 수 있는  schema.ts 파일을 /src 폴더 안에  생성한다.

    $ touch schema.ts
    
    // src/schema.ts
    import 'graphql-import-node';
    import * as typeDefs from './schema/schema.graphql';
    import { makeExecutableSchema } from 'graphql-tools';
    import resolvers from './resolverMap';
    import { GraphQLSchema } from 'graphql';
    const schema: GraphQLSchema = makeExecutableSchema({
      typeDefs,
      resolvers,
    });
    export default schema;

     

    세팅은 모두 끝났다! 이제 GraphQL API를 요청할 수 있는 Insomnia 프로그램을 이용해서, 우리가 구축한 Apollo 서버에 API 요청을 시도해보자.

     

    마지막 세팅: TypeScript 코드 컴파일

    현재는 Typescript 코드를 ts-node를 이용해서 코드를 동작시켰지만, 실제 프로덕션에서 구동시키려면 .ts파일을 컴파일해서 나온 .js파일을 구동시키는 것이 안전하다. 그러므로 ts파일을 컴파일 후 실행시킬 수 있도록 package.json파일의 script 명령어를 아래와 같이 수정한다.

    "scripts": {
        "start": "node 'dist/server.js'",
        "build": "tsc -p . && ncp src/schema dist/schema",
        "dev": "nodemon 'src/server.ts' --exec 'ts-node' src/server.ts -e ts,graphql"
     }

    터미널에 npm run build 명령어를 실행시키면, /dist 폴더 안에 컴파일 된 .js파일이 나타난다.

    이 파일을 npm start 명령어로 실행시키면 정상적으로 작동할 것이다.

     

    Github Repo

    https://github.com/inyong-e/mini-NodeServer-Sequelize-TypeScript-GraphQL

     

    inyong-e/mini-NodeServer-Sequelize-TypeScript-GraphQL

    Sequelize-TypeScript + GraphQL을 이용한 Node 서버 기본 세팅. Contribute to inyong-e/mini-NodeServer-Sequelize-TypeScript-GraphQL development by creating an account on GitHub.

    github.com

     

    반응형

    댓글

Designed by Tistory.