본문 바로가기
IT/javascript

[TS]graphQL 샘플 프로젝트 생성 ( feat. GraphQL과 타입스크립트로 개발하는 웹 서비스 )

by 가능성1g 2024. 9. 9.
반응형

node -v : 20.16.0

 

# 프로젝트 구성 ( 프로젝트 루트 /graphql-book-fullstack-project )
npm i -g yarn
git init
.gitignore 파일 생성 ( 아래 사이트에서 react, node 를 넣고 파일로 생성 )

gitignore.io - 자신의 프로젝트에 꼭 맞는 .gitignore 파일을 만드세요 (toptal.com)


# 프론트 생성
make project

cd project
yarn create react-app --template @chakra-ui/typescript web
cd web
yarn start

yarn add @apollo/client graphql



# 백엔드 생성
## /project 에서
mkdir server
cd server
yarn init -y -p
yarn add express apollo-server-express graphql reflect-metadata typescript apollo-server-core
mkdir src
cd src
index.ts 파일 생성

import 'reflect-metadata';
import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';
import { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';
import http from 'http';

async function main() {
    const app = express();

    const apolloServer = new ApolloServer({
        typeDefs: gql`
            type Query {
                hello: String
            }
        `
        ,
        resolvers: {
            Query: {
                hello: () => `Hello world`,
            },
        },
        plugins: [ApolloServerPluginLandingPageLocalDefault()],
    });
    await apolloServer.start();
    apolloServer.applyMiddleware({app});

    const httpServer = http.createServer(app);

    httpServer.listen(process.env.PORT || 4000, () => {
        if (process.env.NODE_ENV !== 'production') {
            console.log(`
                server started on  => http://localhost:4000
                graphql playground => http://localhost:4000/graphql
            `);
        } else {
            console.log(`
                Production server Started...
            `);
        }
    });
}

main().catch(err => console.error(err));

yarn add ts-node --dev
start 스크립트 추가

  "scripts": {
    "start": "ts-node src/index.ts"    
  },


yarn start


yarn add --dev nodemon
dev 스크립트 추가

  "scripts": {
    "start": "ts-node src/index.ts",
    "dev": "nodemon --watch *.ts --exec ts-node src/index.ts"
  },


yarn dev

 

책의 깃헙 주소

https://github.com/hwasurr/graphql-book-fullstack-project

 

GitHub - hwasurr/graphql-book-fullstack-project: "GraphQL과 타입스크립트로 개발하는 웹 서비스" 도서의 예제

"GraphQL과 타입스크립트로 개발하는 웹 서비스" 도서의 예제 코드 저장소. Contribute to hwasurr/graphql-book-fullstack-project development by creating an account on GitHub.

github.com

 

** 오류관련 추가 처리

type-graphql 어노테이션이 빨간줄!!

설정 파일을 /project/server/tsconfig.json 으로 추가

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "lib": [
            "dom",
            "es6",
            "es2017",
            "esnext.asynciterable"
        ],
        "skipLibCheck": false,
        "sourceMap": true,
        "outDir": "./dist",
        "moduleResolution": "node",
        "removeComments": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "strictFunctionTypes": true,
        "noImplicitThis": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "resolveJsonModule": true,
        "baseUrl": "."
    },
    "exclude": [
        "node_modules"
    ],
    "include": [
        "./**/*.ts"
    ]
}

 

** 프로젝트 진행중 오류로 추가된 모듈

yarn add graphql-scalars

 

** 추가 설정

# GraphQL Code Generator

project/web 이동 후, 설치

yarn add --dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo @graphql-codegen/add

 

/project/web/codegen.yml 생성

overwrite: true
schema: "http://localhost:4000/graphql"
documents: "src/**/*.graphql"
generates:
  src/generated/graphql.tsx:
    plugins:
      - add:
          content: '/* eslint-disable */'
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"

 

스크립트 추가

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "codegen": "graphql-codegen --config codegen.yml"
  },

 

설정파일 처럼 src 밑에 .graphql  로 정의된 파일을 보고 클라이언트의 쿼리훅을 생성해 준다. 

문서 -

https://www.graphql-code-generator.com/

 

Home (GraphQL-Codegen)

GraphQL-Codegen Documentation

the-guild.dev

 

# react waypoint - 페이지네이션 한종류로, 마지막 페이지에서 자동 로딩

yarn add react-waypoint

 

참고 구현 페이지

react-waypoint를 이용한 Infinite-scrolling 구현 (tistory.com)

 

react-waypoint를 이용한 Infinite-scrolling 구현

들어가며 피드 관련 기능을 개발할 때 Infinite-scrolling을 구현해야 할 일이 있었습니다. 구현할 때 react-waypoint를 활용했었는데, 이번 시간에는 구현 원리와 과정을 설명해볼까 합니다. react-waypoint:

pewww.tistory.com

 

# react-router-dom@5 -> 5.3.4, 타입스크립트 정의 같이 설치

yarn add react-router-dom@5
yarn add --dev @types/react-router-dom@5

 

# react-lazyload 이미지 지연 로딩 (-> 3.2.1 네트워크 트래픽 감소 )

yarn add react-lazyload
yarn add --dev @types/react-lazyload

 

# typeorm - mysql 데이터베이스 ORM 라이브러리

yarn add typeorm mysql2

 

# nanoid jsonwebtoken ( -> jwt 인증 )  server  설치

yarn add nanoid jsonwebtoken
yarn add --dev @types/nanoid @types/jsonwebtoken
반응형