wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • gridhelper
  • type-graphql
  • 렌더링 성능 최적화
  • 데이터 포맷
  • 오프-프레미스(off-premise) 방식
  • math.sin()
  • 함수 리터럴
  • 원형적인 움직임
  • getdelta()
  • 초기 환경설정
  • 삼각함수
  • three.js 구성 요소
  • getelapsedtime()
  • axeshelper
  • API
  • mapped types
  • Interface
  • 함수 선언문
  • 스코프
  • 디자인 패턴
  • joi 에러
  • 함수 표현식
  • math.cos()
  • react 성능 최적화
  • reactive variables
  • Decorators
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티
  • isabstract
  • 함수의 범위
  • e.preventdefault()

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

GraphQL Code Generator, 타입스크립트 정의 자동 생성
Frontend/Apollo

GraphQL Code Generator, 타입스크립트 정의 자동 생성

2024. 9. 10. 21:23

GraphQL Code Generator

 

주요 기능:

  • GraphQL 쿼리로부터 타입스크립트 타입 생성
  • Apollo Client, React Hooks와 통합 지원
  • GraphQL 스키마 및 쿼리 자동 생성

 

 

설치, Apollo와 함께 사용할 GraphQL Code Generator 플러그인을 설치

https://the-guild.dev/graphql/codegen/docs/getting-started/installation

npm i graphql
npm i -D typescript @graphql-codegen/cli
npm i-D @graphql-codegen/typescript-operations @graphql-codegen/typescript

 

// codegen.ts

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "<http://localhost:4000/graphql>",
  documents: "./src/**/*.{tsx,ts}",
  generates: {
    "./src/__api__/types.ts": {
      plugins: [
        "typescript",
        "typescript-operations",
        "typescript-react-apollo"
      ],
      config: {
        withHooks: true,
        withHOC: false,
        withComponent: false
      }
    }
  }
};

export default config;
  • GraphQL 스키마를 HTTP URL에서 가져오는 경우, 백엔드 서버가 실행되고 있어야 한다.
  • 스키마를 로드하려면 서버가 요청에 응답할 수 있어야 하기 때문이다.

 

// package.json


"scripts": {
  "tailwind:build": "tailwindcss -i ./src/styles/tailwind.css -o ./src/styles/styles.css --watch",
  "start": "concurrently \\"nodemon --watch src --exec react-scripts start\\" \\"npm run tailwind:build\\"",
  "generate": "graphql-codegen",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject",
  "codegen": "graphql-codegen --config codegen.ts"
}

"generate": "graphql-codegen" 작성해주기

 

 

실행

백엔드 서버 켜져있는 상태로 진행

 npm run generate
  • __api__폴더에 생성되는 것을 확인하기

 

 

사용법

https://www.graphql-code-generator.com/docs/guides/react/

export const LOGIN_MUTATION = gql`
  # (1) gql name을 재설정
  mutation login($loginInput: LoginInput!) {
    login(input: $loginInput) {
      ok
      token
      error
    }
  }
`;

interface ILoginForm {
  email: string;
  password: string;
}

export const Login = () => {
  const {
    register,
    getValues,
    formState: { errors },
    handleSubmit
  } = useForm<ILoginForm>();

  const [loginMutation] = useMutation<LoginMutation, LoginMutationVariables>(
    LOGIN_MUTATION
  );

  const onSubmit = () => {
    const { email, password } = getValues();
    loginMutation({
      variables: {
        // GraphQL 쿼리에서 사용하는 변수 이름으로 맞춰서 변경
        loginInput: {
          email,
          password
        }
      }
    });
  };
  • generate 될때 type명에 Mutation을 자동으로 붙여준다.
  • (1) gql name을 재설정 : loginMutation 으로 이름을 지정하고 generate를 하게되면 loginMutationMutation으로 생성하게 되므로 gql name을 재설정하고 generate하기

 

 

코드 설명

useMutation<LoginMutation, LoginMutationVariables>(LOGIN_MUTATION);
  • LoginMutation은 Mutation의 응답으로 반환될 타입을 정의한다.
  • LoginMutationVariables는Mutation에 전달할 변수의 타입을 정의한다.
  • LOGIN_MUTATION은 GraphQL Mutation 쿼리를 포함하는 gql 템플릿 리터럴이다.

 

 

백엔드 실행 없이도 진행하는 방법, 로컬 스키마 파일을 사용

schema: ./path/to/schema.graphql # 로컬 스키마 파일 경로

// codegen.ts

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: ./path/to/schema.graphql  // 로컬 스키마 파일 경로
  documents: "./src/**/*.{tsx,ts}",
  generates: {
    "./src/__api__/types.ts": {
      plugins: [
        "typescript",
        "typescript-operations",
        "typescript-react-apollo"
      ],
      config: {
        withHooks: true,
        withHOC: false,
        withComponent: false
      }
    }
  }
};

export default config;

 

 

저작자표시 변경금지 (새창열림)

'Frontend > Apollo' 카테고리의 다른 글

useLazyQuery, GraphQL 쿼리를 즉시 실행하지 않고 필요할 때 호출  (0) 2024.10.15
GraphQL 서버와 통신하지 않고 Apollo Client 캐시에서 직접 데이터를 읽고 쓰기  (0) 2024.10.01
Apollo Link 개요와 주요 기능  (0) 2024.09.29
Apollo Client 캐시 동작과 관리 방법  (0) 2024.09.29
[Apollo v.3] Reactive variables  (0) 2024.09.06
    'Frontend/Apollo' 카테고리의 다른 글
    • GraphQL 서버와 통신하지 않고 Apollo Client 캐시에서 직접 데이터를 읽고 쓰기
    • Apollo Link 개요와 주요 기능
    • Apollo Client 캐시 동작과 관리 방법
    • [Apollo v.3] Reactive variables
    wam
    wam

    티스토리툴바