[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,192 @@
|
||||
id: wiki-2026-0508-graphql-code-generator
|
||||
title: GraphQL Code Generator
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-GQCG-001]
|
||||
aliases: [graphql-codegen, GQL Codegen, Type-safe GraphQL]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.96
|
||||
tags: [auto-reinforced, graphql, code-generator, typescript, type-safety, Schema, automation, api-development]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [graphql, typescript, codegen, type-safety]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: graphql
|
||||
---
|
||||
|
||||
# [[GraphQL-Code-Generator|GraphQL-Code-Generator]]
|
||||
# GraphQL Code Generator
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "서버와 클라이언트의 실시간 동기화: 서버의 GraphQL 스키마를 읽어 클라이언트에서 즉시 사용할 수 있는 완벽한 타입스크립트 타입과 데이터 요청 함수를 자동 생성하여, 수동 작업으로 인한 '타입 미스매치'를 0%로 만드는 자동화 도구."
|
||||
## 매 한 줄
|
||||
> **"매 schema → typed client 의 자동화"**. `.graphql` schema + operation 으로부터 TypeScript types, hook, fragment 의 생성. 매 schema drift 의 compile-time 차단 — `any` 의 X, `User.email` typo 의 즉시 error.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
GraphQL 코드 제너레이터(GraphQL-Code-Generator)는 GraphQL 스키마와 작업(Query, Mutation 등)을 분석하여 다양한 언어의 타입과 코드를 생성해 주는 오픈 소스 라이브러리입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **동작 매커니즘**:
|
||||
* **Input**: `schema.graphql` 파일 + 프론트엔드에서 작성한 `.graphql` 쿼리 파일들.
|
||||
* **[[Processing|Processing]]**: 플러그인 시스템을 통해 AST 분석 및 템플릿 적용.
|
||||
* **Output**: `types.ts`, `hooks.ts` 등 (React Query, Apollo, SWR 대응 가능). ([[Efficiency|Efficiency]]와 연결)
|
||||
2. **왜 중요한가?**:
|
||||
* API 변경 시 클라이언트 코드가 즉시 컴파일 에러를 띄우므로, 런타임 장애 정책을 사전에 완벽히 차단하기 때문임. ([[Reliability|Reliability]]와 연결)
|
||||
### 매 핵심 plugin
|
||||
- **typescript**: schema → TS types (scalar, enum, input, object).
|
||||
- **typescript-operations**: query/mutation operation → typed result.
|
||||
- **typed-document-node**: TypedDocumentNode (apollo-client / urql 의 input).
|
||||
- **client-preset** (modern, 2026 default): 매 fragment-masking, persisted-query 의 통합 preset.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 `any` 타입을 쓰거나 수동으로 인터페이스 정책을 맞췄으나, 현대 정책은 'Schema-first' 또는 'Code-first' 방식 정책을 통해 타입 정책을 100% 자동 생성 정책하는 것이 표준임(RL Update). ([[Distributed-System-Type-Safety|Distributed-System-Type-Safety]]와 연결)
|
||||
- **정책 변화(RL Update)**: 이제는 단순 타입 생성 정책을 넘어, 스키마 정보를 활용하여 목업 데이터(Mocking) 정책이나 유효성 검사 로직(Zod) 정책까지 자동으로 생성해 주는 풀스택 개발 가속기로 진화함.
|
||||
### 매 fragment masking
|
||||
- Component A 가 fragment X 정의 → component B 가 fragment X 의 field 접근 시 compile error.
|
||||
- 매 over-fetching 의 prevention 강제.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Efficiency|Efficiency]], [[Reliability|Reliability]], [[Distributed-System-Type-Safety|Distributed-System-Type-Safety]], [[Technical-Architecture|Technical-Architecture]], Standard-Operating-Procedure, Automation
|
||||
- **Key Ecosystem**: The Guild (Creators).
|
||||
---
|
||||
### 매 응용
|
||||
1. React + Apollo / urql 매 typed hook 자동 생성.
|
||||
2. Backend schema change 시 client compile error 즉시 감지.
|
||||
3. Persisted queries (production safety, query whitelisting).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### codegen.ts (client-preset)
|
||||
```typescript
|
||||
import { CodegenConfig } from '@graphql-codegen/cli';
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const config: CodegenConfig = {
|
||||
schema: 'https://api.example.com/graphql',
|
||||
documents: ['src/**/*.{ts,tsx}', '!src/gql/**/*'],
|
||||
generates: {
|
||||
'./src/gql/': {
|
||||
preset: 'client',
|
||||
presetConfig: {
|
||||
fragmentMasking: { unmaskFunctionName: 'getFragmentData' },
|
||||
},
|
||||
config: {
|
||||
useTypeImports: true,
|
||||
scalars: { DateTime: 'string', UUID: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
hooks: { afterAllFileWrite: ['prettier --write'] },
|
||||
};
|
||||
export default config;
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
```bash
|
||||
pnpm graphql-codegen --watch
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Operation — typed result
|
||||
```typescript
|
||||
// src/components/UserCard.tsx
|
||||
import { graphql } from '../gql';
|
||||
import { useQuery } from '@apollo/client';
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const USER_QUERY = graphql(`
|
||||
query GetUser($id: ID!) {
|
||||
user(id: $id) { id name email avatarUrl }
|
||||
}
|
||||
`);
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
export function UserCard({ id }: { id: string }) {
|
||||
const { data } = useQuery(USER_QUERY, { variables: { id } });
|
||||
// 매 data?.user 의 type 의 fully inferred
|
||||
return <div>{data?.user?.name}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Fragment masking
|
||||
```typescript
|
||||
const USER_AVATAR_FRAGMENT = graphql(`
|
||||
fragment UserAvatar on User { avatarUrl name }
|
||||
`);
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
function Avatar({ user }: { user: FragmentType<typeof USER_AVATAR_FRAGMENT> }) {
|
||||
const u = getFragmentData(USER_AVATAR_FRAGMENT, user);
|
||||
return <img src={u.avatarUrl} alt={u.name} />;
|
||||
}
|
||||
|
||||
// parent — 매 user 의 email 의 access X (fragment 의 declare X)
|
||||
function Parent({ user }) {
|
||||
return <Avatar user={user} />;
|
||||
// user.email 의 access 시 TS error
|
||||
}
|
||||
```
|
||||
|
||||
### Persisted queries
|
||||
```typescript
|
||||
{
|
||||
generates: {
|
||||
'./persisted-operations.json': {
|
||||
preset: 'client',
|
||||
presetConfig: { persistedDocuments: true },
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// runtime — query string 의 X, hash 만 전송
|
||||
import { createPersistedQueryLink } from '@apollo/client/link/persisted-queries';
|
||||
const link = createPersistedQueryLink({ generateHash: doc => doc['__meta__']['hash'] });
|
||||
```
|
||||
|
||||
### Custom scalar mapping
|
||||
```typescript
|
||||
config: {
|
||||
scalars: {
|
||||
DateTime: 'string', // ISO 8601
|
||||
JSON: 'Record<string, unknown>',
|
||||
BigInt: 'string',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Watch + CI
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"codegen": "graphql-codegen",
|
||||
"codegen:watch": "graphql-codegen --watch",
|
||||
"ci:codegen-check": "graphql-codegen && git diff --exit-code src/gql/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Multi-schema (federation)
|
||||
```typescript
|
||||
{
|
||||
schema: ['./schema/users.graphql', './schema/products.graphql'],
|
||||
// 매 federated graph 의 single typed client
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 새 React + GraphQL | client-preset + fragment masking |
|
||||
| Apollo Client (legacy) | typescript + typescript-react-apollo |
|
||||
| urql | client-preset (urql 의 native 지원) |
|
||||
| Production 보안 | persisted queries 의 enable |
|
||||
| Backend schema 의 evolve | CI 의 codegen drift check |
|
||||
|
||||
**기본값**: client-preset + fragmentMasking, CI 의 codegen drift check.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[GraphQL]] · [[TypeScript]]
|
||||
- 변형: [[urql]] · [[Apollo-Client]] · [[Relay]]
|
||||
- 응용: [[Type-Safe-API-Client]] · [[Persisted-Queries]]
|
||||
- Adjacent: [[OpenAPI-Codegen]] · [[tRPC]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: GraphQL schema 가 있는 TS project, multi-team 의 schema drift 방지, persisted query 도입.
|
||||
**언제 X**: REST-only, 매 GraphQL schema 의 unstable 한 prototype phase.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **codegen output 의 manual edit**: 매 next run 시 overwrite, 매 변경 의 lost.
|
||||
- **fragment 의 component 외 정의**: fragment masking 의 weak — co-location 강제.
|
||||
- **DateTime 의 `Date` mapping**: GraphQL response 는 string, 매 runtime mismatch 유발.
|
||||
- **CI 에 codegen drift check 의 X**: schema 의 silent breakage.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (graphql-code-generator.com docs, client-preset migration guide).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — GraphQL Codegen client-preset 패턴 정리 |
|
||||
|
||||
Reference in New Issue
Block a user