본문 바로가기
Flutter

Flutter GraphQL Code generator with VSC

by 강깅꽁 2024. 4. 13.

사용 패키지

- graphql_flutter

- graphql_codegen

 

https://pub.dev/packages/graphql_flutter

https://pub.dev/packages/graphql_codegen#clients

 

Server로 부터 Schema를 다운받습니다.

 

package.json

{YOUR_GRAPHQL_ENDPOINT} 를 실제 endpoint로 설정해줍니다.

{
  "scripts": {
    "convert-schema": "node convert-schema.js",
    "download-schema": "apollo schema:download --endpoint={YOUR_GRAPHQL_ENDPOINT} schema.json",
    "update-schema": "npm run download-schema && npm run convert-schema"
  },
  "dependencies": {
    "graphql": "^16.8.1"
  }
}

 

convert-schema.js

 

본인의 폴더 구조에 맞게 아래 file을 읽고 내보내는 코드를 적절하게 수정합니다.

const schemaJson = require("./schema.json");
fs.writeFileSync("lib/schema.graphql", sdlSchema);

const fs = require("fs");
const { buildClientSchema, printSchema } = require("graphql");

const schemaJson = require("./schema.json");
const schema = buildClientSchema(schemaJson);
const sdlSchema = printSchema(schema);

fs.writeFileSync("lib/schema.graphql", sdlSchema);

 

터미널에서 실행

yarn update-schema

 

결과 schema.graphql 예시

 

 

 

graphql_codegen 활용

# build.yaml

targets:
  $default:
    builders:
      graphql_codegen:
        options:
          clients:
            - graphql_flutter

 

원하는 폴더에 graphql file 생성

 

다음 명령어를 통해 code generating

dart run build_runner build

 

다음과 같이 활용